1 /*
   2  * Copyright (c) 2011, 2013, 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 java.lang.annotation.*;
  29 import java.lang.reflect.Method;
  30 import java.util.List;
  31 import java.util.Arrays;
  32 import java.util.HashMap;
  33 
  34 import sun.invoke.util.Wrapper;
  35 import java.lang.reflect.Field;
  36 
  37 import static java.lang.invoke.LambdaForm.BasicType.*;
  38 import static java.lang.invoke.MethodHandleStatics.*;
  39 import static java.lang.invoke.MethodHandleNatives.Constants.*;
  40 
  41 /**
  42  * The symbolic, non-executable form of a method handle's invocation semantics.
  43  * It consists of a series of names.
  44  * The first N (N=arity) names are parameters,
  45  * while any remaining names are temporary values.
  46  * Each temporary specifies the application of a function to some arguments.
  47  * The functions are method handles, while the arguments are mixes of
  48  * constant values and local names.
  49  * The result of the lambda is defined as one of the names, often the last one.
  50  * <p>
  51  * Here is an approximate grammar:
  52  * <blockquote><pre>{@code
  53  * LambdaForm = "(" ArgName* ")=>{" TempName* Result "}"
  54  * ArgName = "a" N ":" T
  55  * TempName = "t" N ":" T "=" Function "(" Argument* ");"
  56  * Function = ConstantValue
  57  * Argument = NameRef | ConstantValue
  58  * Result = NameRef | "void"
  59  * NameRef = "a" N | "t" N
  60  * N = (any whole number)
  61  * T = "L" | "I" | "J" | "F" | "D" | "V"
  62  * }</pre></blockquote>
  63  * Names are numbered consecutively from left to right starting at zero.
  64  * (The letters are merely a taste of syntax sugar.)
  65  * Thus, the first temporary (if any) is always numbered N (where N=arity).
  66  * Every occurrence of a name reference in an argument list must refer to
  67  * a name previously defined within the same lambda.
  68  * A lambda has a void result if and only if its result index is -1.
  69  * If a temporary has the type "V", it cannot be the subject of a NameRef,
  70  * even though possesses a number.
  71  * Note that all reference types are erased to "L", which stands for {@code Object}.
  72  * All subword types (boolean, byte, short, char) are erased to "I" which is {@code int}.
  73  * The other types stand for the usual primitive types.
  74  * <p>
  75  * Function invocation closely follows the static rules of the Java verifier.
  76  * Arguments and return values must exactly match when their "Name" types are
  77  * considered.
  78  * Conversions are allowed only if they do not change the erased type.
  79  * <ul>
  80  * <li>L = Object: casts are used freely to convert into and out of reference types
  81  * <li>I = int: subword types are forcibly narrowed when passed as arguments (see {@code explicitCastArguments})
  82  * <li>J = long: no implicit conversions
  83  * <li>F = float: no implicit conversions
  84  * <li>D = double: no implicit conversions
  85  * <li>V = void: a function result may be void if and only if its Name is of type "V"
  86  * </ul>
  87  * Although implicit conversions are not allowed, explicit ones can easily be
  88  * encoded by using temporary expressions which call type-transformed identity functions.
  89  * <p>
  90  * Examples:
  91  * <blockquote><pre>{@code
  92  * (a0:J)=>{ a0 }
  93  *     == identity(long)
  94  * (a0:I)=>{ t1:V = System.out#println(a0); void }
  95  *     == System.out#println(int)
  96  * (a0:L)=>{ t1:V = System.out#println(a0); a0 }
  97  *     == identity, with printing side-effect
  98  * (a0:L, a1:L)=>{ t2:L = BoundMethodHandle#argument(a0);
  99  *                 t3:L = BoundMethodHandle#target(a0);
 100  *                 t4:L = MethodHandle#invoke(t3, t2, a1); t4 }
 101  *     == general invoker for unary insertArgument combination
 102  * (a0:L, a1:L)=>{ t2:L = FilterMethodHandle#filter(a0);
 103  *                 t3:L = MethodHandle#invoke(t2, a1);
 104  *                 t4:L = FilterMethodHandle#target(a0);
 105  *                 t5:L = MethodHandle#invoke(t4, t3); t5 }
 106  *     == general invoker for unary filterArgument combination
 107  * (a0:L, a1:L)=>{ ...(same as previous example)...
 108  *                 t5:L = MethodHandle#invoke(t4, t3, a1); t5 }
 109  *     == general invoker for unary/unary foldArgument combination
 110  * (a0:L, a1:I)=>{ t2:I = identity(long).asType((int)->long)(a1); t2 }
 111  *     == invoker for identity method handle which performs i2l
 112  * (a0:L, a1:L)=>{ t2:L = BoundMethodHandle#argument(a0);
 113  *                 t3:L = Class#cast(t2,a1); t3 }
 114  *     == invoker for identity method handle which performs cast
 115  * }</pre></blockquote>
 116  * <p>
 117  * @author John Rose, JSR 292 EG
 118  */
 119 class LambdaForm {
 120     final int arity;
 121     final int result;
 122     final boolean forceInline;
 123     @Stable final Name[] names;
 124     final String debugName;
 125     MemberName vmentry;   // low-level behavior, or null if not yet prepared
 126     private boolean isCompiled;
 127 
 128     volatile Object transformCache;  // managed by LambdaFormEditor
 129 
 130     public static final int VOID_RESULT = -1, LAST_RESULT = -2;
 131 
 132     enum BasicType {
 133         L_TYPE('L', Object.class, Wrapper.OBJECT),  // all reference types
 134         I_TYPE('I', int.class,    Wrapper.INT),
 135         J_TYPE('J', long.class,   Wrapper.LONG),
 136         F_TYPE('F', float.class,  Wrapper.FLOAT),
 137         D_TYPE('D', double.class, Wrapper.DOUBLE),  // all primitive types
 138         V_TYPE('V', void.class,   Wrapper.VOID);    // not valid in all contexts
 139 
 140         static final BasicType[] ALL_TYPES = BasicType.values();
 141         static final BasicType[] ARG_TYPES = Arrays.copyOf(ALL_TYPES, ALL_TYPES.length-1);
 142 
 143         static final int ARG_TYPE_LIMIT = ARG_TYPES.length;
 144         static final int TYPE_LIMIT = ALL_TYPES.length;
 145 
 146         private final char btChar;
 147         private final Class<?> btClass;
 148         private final Wrapper btWrapper;
 149 
 150         private BasicType(char btChar, Class<?> btClass, Wrapper wrapper) {
 151             this.btChar = btChar;
 152             this.btClass = btClass;
 153             this.btWrapper = wrapper;
 154         }
 155 
 156         char basicTypeChar() {
 157             return btChar;
 158         }
 159         Class<?> basicTypeClass() {
 160             return btClass;
 161         }
 162         Wrapper basicTypeWrapper() {
 163             return btWrapper;
 164         }
 165         int basicTypeSlots() {
 166             return btWrapper.stackSlots();
 167         }
 168 
 169         static BasicType basicType(byte type) {
 170             return ALL_TYPES[type];
 171         }
 172         static BasicType basicType(char type) {
 173             switch (type) {
 174                 case 'L': return L_TYPE;
 175                 case 'I': return I_TYPE;
 176                 case 'J': return J_TYPE;
 177                 case 'F': return F_TYPE;
 178                 case 'D': return D_TYPE;
 179                 case 'V': return V_TYPE;
 180                 // all subword types are represented as ints
 181                 case 'Z':
 182                 case 'B':
 183                 case 'S':
 184                 case 'C':
 185                     return I_TYPE;
 186                 default:
 187                     throw newInternalError("Unknown type char: '"+type+"'");
 188             }
 189         }
 190         static BasicType basicType(Wrapper type) {
 191             char c = type.basicTypeChar();
 192             return basicType(c);
 193         }
 194         static BasicType basicType(Class<?> type) {
 195             if (!type.isPrimitive())  return L_TYPE;
 196             return basicType(Wrapper.forPrimitiveType(type));
 197         }
 198 
 199         static char basicTypeChar(Class<?> type) {
 200             return basicType(type).btChar;
 201         }
 202         static BasicType[] basicTypes(List<Class<?>> types) {
 203             BasicType[] btypes = new BasicType[types.size()];
 204             for (int i = 0; i < btypes.length; i++) {
 205                 btypes[i] = basicType(types.get(i));
 206             }
 207             return btypes;
 208         }
 209         static BasicType[] basicTypes(String types) {
 210             BasicType[] btypes = new BasicType[types.length()];
 211             for (int i = 0; i < btypes.length; i++) {
 212                 btypes[i] = basicType(types.charAt(i));
 213             }
 214             return btypes;
 215         }
 216         static byte[] basicTypesOrd(BasicType[] btypes) {
 217             byte[] ords = new byte[btypes.length];
 218             for (int i = 0; i < btypes.length; i++) {
 219                 ords[i] = (byte)btypes[i].ordinal();
 220             }
 221             return ords;
 222         }
 223         static boolean isBasicTypeChar(char c) {
 224             return "LIJFDV".indexOf(c) >= 0;
 225         }
 226         static boolean isArgBasicTypeChar(char c) {
 227             return "LIJFD".indexOf(c) >= 0;
 228         }
 229 
 230         static { assert(checkBasicType()); }
 231         private static boolean checkBasicType() {
 232             for (int i = 0; i < ARG_TYPE_LIMIT; i++) {
 233                 assert ARG_TYPES[i].ordinal() == i;
 234                 assert ARG_TYPES[i] == ALL_TYPES[i];
 235             }
 236             for (int i = 0; i < TYPE_LIMIT; i++) {
 237                 assert ALL_TYPES[i].ordinal() == i;
 238             }
 239             assert ALL_TYPES[TYPE_LIMIT - 1] == V_TYPE;
 240             assert !Arrays.asList(ARG_TYPES).contains(V_TYPE);
 241             return true;
 242         }
 243     }
 244 
 245     LambdaForm(String debugName,
 246                int arity, Name[] names, int result) {
 247         this(debugName, arity, names, result, /*forceInline=*/true);
 248     }
 249     LambdaForm(String debugName,
 250                int arity, Name[] names, int result, boolean forceInline) {
 251         assert(namesOK(arity, names));
 252         this.arity = arity;
 253         this.result = fixResult(result, names);
 254         this.names = names.clone();
 255         this.debugName = fixDebugName(debugName);
 256         this.forceInline = forceInline;
 257         int maxOutArity = normalize();
 258         if (maxOutArity > MethodType.MAX_MH_INVOKER_ARITY) {
 259             // Cannot use LF interpreter on very high arity expressions.
 260             assert(maxOutArity <= MethodType.MAX_JVM_ARITY);
 261             compileToBytecode();
 262         }
 263     }
 264     LambdaForm(String debugName,
 265                int arity, Name[] names) {
 266         this(debugName, arity, names, LAST_RESULT, /*forceInline=*/true);
 267     }
 268     LambdaForm(String debugName,
 269                int arity, Name[] names, boolean forceInline) {
 270         this(debugName, arity, names, LAST_RESULT, forceInline);
 271     }
 272     LambdaForm(String debugName,
 273                Name[] formals, Name[] temps, Name result) {
 274         this(debugName,
 275              formals.length, buildNames(formals, temps, result), LAST_RESULT, /*forceInline=*/true);
 276     }
 277     LambdaForm(String debugName,
 278                Name[] formals, Name[] temps, Name result, boolean forceInline) {
 279         this(debugName,
 280              formals.length, buildNames(formals, temps, result), LAST_RESULT, forceInline);
 281     }
 282 
 283     private static Name[] buildNames(Name[] formals, Name[] temps, Name result) {
 284         int arity = formals.length;
 285         int length = arity + temps.length + (result == null ? 0 : 1);
 286         Name[] names = Arrays.copyOf(formals, length);
 287         System.arraycopy(temps, 0, names, arity, temps.length);
 288         if (result != null)
 289             names[length - 1] = result;
 290         return names;
 291     }
 292 
 293     private LambdaForm(String sig) {
 294         // Make a blank lambda form, which returns a constant zero or null.
 295         // It is used as a template for managing the invocation of similar forms that are non-empty.
 296         // Called only from getPreparedForm.
 297         assert(isValidSignature(sig));
 298         this.arity = signatureArity(sig);
 299         this.result = (signatureReturn(sig) == V_TYPE ? -1 : arity);
 300         this.names = buildEmptyNames(arity, sig);
 301         this.debugName = "LF.zero";
 302         this.forceInline = true;
 303         assert(nameRefsAreLegal());
 304         assert(isEmpty());
 305         assert(sig.equals(basicTypeSignature())) : sig + " != " + basicTypeSignature();
 306     }
 307 
 308     private static Name[] buildEmptyNames(int arity, String basicTypeSignature) {
 309         assert(isValidSignature(basicTypeSignature));
 310         int resultPos = arity + 1;  // skip '_'
 311         if (arity < 0 || basicTypeSignature.length() != resultPos+1)
 312             throw new IllegalArgumentException("bad arity for "+basicTypeSignature);
 313         int numRes = (basicType(basicTypeSignature.charAt(resultPos)) == V_TYPE ? 0 : 1);
 314         Name[] names = arguments(numRes, basicTypeSignature.substring(0, arity));
 315         for (int i = 0; i < numRes; i++) {
 316             Name zero = new Name(constantZero(basicType(basicTypeSignature.charAt(resultPos + i))));
 317             names[arity + i] = zero.newIndex(arity + i);
 318         }
 319         return names;
 320     }
 321 
 322     private static int fixResult(int result, Name[] names) {
 323         if (result == LAST_RESULT)
 324             result = names.length - 1;  // might still be void
 325         if (result >= 0 && names[result].type == V_TYPE)
 326             result = VOID_RESULT;
 327         return result;
 328     }
 329 
 330     private static String fixDebugName(String debugName) {
 331         if (DEBUG_NAME_COUNTERS != null) {
 332             int under = debugName.indexOf('_');
 333             int length = debugName.length();
 334             if (under < 0)  under = length;
 335             String debugNameStem = debugName.substring(0, under);
 336             Integer ctr;
 337             synchronized (DEBUG_NAME_COUNTERS) {
 338                 ctr = DEBUG_NAME_COUNTERS.get(debugNameStem);
 339                 if (ctr == null)  ctr = 0;
 340                 DEBUG_NAME_COUNTERS.put(debugNameStem, ctr+1);
 341             }
 342             StringBuilder buf = new StringBuilder(debugNameStem);
 343             buf.append('_');
 344             int leadingZero = buf.length();
 345             buf.append((int) ctr);
 346             for (int i = buf.length() - leadingZero; i < 3; i++)
 347                 buf.insert(leadingZero, '0');
 348             if (under < length) {
 349                 ++under;    // skip "_"
 350                 while (under < length && Character.isDigit(debugName.charAt(under))) {
 351                     ++under;
 352                 }
 353                 if (under < length && debugName.charAt(under) == '_')  ++under;
 354                 if (under < length)
 355                     buf.append('_').append(debugName, under, length);
 356             }
 357             return buf.toString();
 358         }
 359         return debugName;
 360     }
 361 
 362     private static boolean namesOK(int arity, Name[] names) {
 363         for (int i = 0; i < names.length; i++) {
 364             Name n = names[i];
 365             assert(n != null) : "n is null";
 366             if (i < arity)
 367                 assert( n.isParam()) : n + " is not param at " + i;
 368             else
 369                 assert(!n.isParam()) : n + " is param at " + i;
 370         }
 371         return true;
 372     }
 373 
 374     /** Renumber and/or replace params so that they are interned and canonically numbered.
 375      *  @return maximum argument list length among the names (since we have to pass over them anyway)
 376      */
 377     private int normalize() {
 378         Name[] oldNames = null;
 379         int maxOutArity = 0;
 380         int changesStart = 0;
 381         for (int i = 0; i < names.length; i++) {
 382             Name n = names[i];
 383             if (!n.initIndex(i)) {
 384                 if (oldNames == null) {
 385                     oldNames = names.clone();
 386                     changesStart = i;
 387                 }
 388                 names[i] = n.cloneWithIndex(i);
 389             }
 390             if (n.arguments != null && maxOutArity < n.arguments.length)
 391                 maxOutArity = n.arguments.length;
 392         }
 393         if (oldNames != null) {
 394             int startFixing = arity;
 395             if (startFixing <= changesStart)
 396                 startFixing = changesStart+1;
 397             for (int i = startFixing; i < names.length; i++) {
 398                 Name fixed = names[i].replaceNames(oldNames, names, changesStart, i);
 399                 names[i] = fixed.newIndex(i);
 400             }
 401         }
 402         assert(nameRefsAreLegal());
 403         int maxInterned = Math.min(arity, INTERNED_ARGUMENT_LIMIT);
 404         boolean needIntern = false;
 405         for (int i = 0; i < maxInterned; i++) {
 406             Name n = names[i], n2 = internArgument(n);
 407             if (n != n2) {
 408                 names[i] = n2;
 409                 needIntern = true;
 410             }
 411         }
 412         if (needIntern) {
 413             for (int i = arity; i < names.length; i++) {
 414                 names[i].internArguments();
 415             }
 416             assert(nameRefsAreLegal());
 417         }
 418         return maxOutArity;
 419     }
 420 
 421     /**
 422      * Check that all embedded Name references are localizable to this lambda,
 423      * and are properly ordered after their corresponding definitions.
 424      * <p>
 425      * Note that a Name can be local to multiple lambdas, as long as
 426      * it possesses the same index in each use site.
 427      * This allows Name references to be freely reused to construct
 428      * fresh lambdas, without confusion.
 429      */
 430     boolean nameRefsAreLegal() {
 431         assert(arity >= 0 && arity <= names.length);
 432         assert(result >= -1 && result < names.length);
 433         // Do all names possess an index consistent with their local definition order?
 434         for (int i = 0; i < arity; i++) {
 435             Name n = names[i];
 436             assert(n.index() == i) : Arrays.asList(n.index(), i);
 437             assert(n.isParam());
 438         }
 439         // Also, do all local name references
 440         for (int i = arity; i < names.length; i++) {
 441             Name n = names[i];
 442             assert(n.index() == i);
 443             for (Object arg : n.arguments) {
 444                 if (arg instanceof Name) {
 445                     Name n2 = (Name) arg;
 446                     int i2 = n2.index;
 447                     assert(0 <= i2 && i2 < names.length) : n.debugString() + ": 0 <= i2 && i2 < names.length: 0 <= " + i2 + " < " + names.length;
 448                     assert(names[i2] == n2) : Arrays.asList("-1-", i, "-2-", n.debugString(), "-3-", i2, "-4-", n2.debugString(), "-5-", names[i2].debugString(), "-6-", this);
 449                     assert(i2 < i);  // ref must come after def!
 450                 }
 451             }
 452         }
 453         return true;
 454     }
 455 
 456     /** Invoke this form on the given arguments. */
 457     // final Object invoke(Object... args) throws Throwable {
 458     //     // NYI: fit this into the fast path?
 459     //     return interpretWithArguments(args);
 460     // }
 461 
 462     /** Report the return type. */
 463     BasicType returnType() {
 464         if (result < 0)  return V_TYPE;
 465         Name n = names[result];
 466         return n.type;
 467     }
 468 
 469     /** Report the N-th argument type. */
 470     BasicType parameterType(int n) {
 471         return parameter(n).type;
 472     }
 473 
 474     /** Report the N-th argument name. */
 475     Name parameter(int n) {
 476         assert(n < arity);
 477         Name param = names[n];
 478         assert(param.isParam());
 479         return param;
 480     }
 481 
 482     /** Report the N-th argument type constraint. */
 483     Object parameterConstraint(int n) {
 484         return parameter(n).constraint;
 485     }
 486 
 487     /** Report the arity. */
 488     int arity() {
 489         return arity;
 490     }
 491 
 492     /** Report the number of expressions (non-parameter names). */
 493     int expressionCount() {
 494         return names.length - arity;
 495     }
 496 
 497     /** Return the method type corresponding to my basic type signature. */
 498     MethodType methodType() {
 499         return signatureType(basicTypeSignature());
 500     }
 501     /** Return ABC_Z, where the ABC are parameter type characters, and Z is the return type character. */
 502     final String basicTypeSignature() {
 503         StringBuilder buf = new StringBuilder(arity() + 3);
 504         for (int i = 0, a = arity(); i < a; i++)
 505             buf.append(parameterType(i).basicTypeChar());
 506         return buf.append('_').append(returnType().basicTypeChar()).toString();
 507     }
 508     static int signatureArity(String sig) {
 509         assert(isValidSignature(sig));
 510         return sig.indexOf('_');
 511     }
 512     static BasicType signatureReturn(String sig) {
 513         return basicType(sig.charAt(signatureArity(sig) + 1));
 514     }
 515     static boolean isValidSignature(String sig) {
 516         int arity = sig.indexOf('_');
 517         if (arity < 0)  return false;  // must be of the form *_*
 518         int siglen = sig.length();
 519         if (siglen != arity + 2)  return false;  // *_X
 520         for (int i = 0; i < siglen; i++) {
 521             if (i == arity)  continue;  // skip '_'
 522             char c = sig.charAt(i);
 523             if (c == 'V')
 524                 return (i == siglen - 1 && arity == siglen - 2);
 525             if (!isArgBasicTypeChar(c))  return false; // must be [LIJFD]
 526         }
 527         return true;  // [LIJFD]*_[LIJFDV]
 528     }
 529     static MethodType signatureType(String sig) {
 530         Class<?>[] ptypes = new Class<?>[signatureArity(sig)];
 531         for (int i = 0; i < ptypes.length; i++)
 532             ptypes[i] = basicType(sig.charAt(i)).btClass;
 533         Class<?> rtype = signatureReturn(sig).btClass;
 534         return MethodType.methodType(rtype, ptypes);
 535     }
 536 
 537     /*
 538      * Code generation issues:
 539      *
 540      * Compiled LFs should be reusable in general.
 541      * The biggest issue is how to decide when to pull a name into
 542      * the bytecode, versus loading a reified form from the MH data.
 543      *
 544      * For example, an asType wrapper may require execution of a cast
 545      * after a call to a MH.  The target type of the cast can be placed
 546      * as a constant in the LF itself.  This will force the cast type
 547      * to be compiled into the bytecodes and native code for the MH.
 548      * Or, the target type of the cast can be erased in the LF, and
 549      * loaded from the MH data.  (Later on, if the MH as a whole is
 550      * inlined, the data will flow into the inlined instance of the LF,
 551      * as a constant, and the end result will be an optimal cast.)
 552      *
 553      * This erasure of cast types can be done with any use of
 554      * reference types.  It can also be done with whole method
 555      * handles.  Erasing a method handle might leave behind
 556      * LF code that executes correctly for any MH of a given
 557      * type, and load the required MH from the enclosing MH's data.
 558      * Or, the erasure might even erase the expected MT.
 559      *
 560      * Also, for direct MHs, the MemberName of the target
 561      * could be erased, and loaded from the containing direct MH.
 562      * As a simple case, a LF for all int-valued non-static
 563      * field getters would perform a cast on its input argument
 564      * (to non-constant base type derived from the MemberName)
 565      * and load an integer value from the input object
 566      * (at a non-constant offset also derived from the MemberName).
 567      * Such MN-erased LFs would be inlinable back to optimized
 568      * code, whenever a constant enclosing DMH is available
 569      * to supply a constant MN from its data.
 570      *
 571      * The main problem here is to keep LFs reasonably generic,
 572      * while ensuring that hot spots will inline good instances.
 573      * "Reasonably generic" means that we don't end up with
 574      * repeated versions of bytecode or machine code that do
 575      * not differ in their optimized form.  Repeated versions
 576      * of machine would have the undesirable overheads of
 577      * (a) redundant compilation work and (b) extra I$ pressure.
 578      * To control repeated versions, we need to be ready to
 579      * erase details from LFs and move them into MH data,
 580      * whevener those details are not relevant to significant
 581      * optimization.  "Significant" means optimization of
 582      * code that is actually hot.
 583      *
 584      * Achieving this may require dynamic splitting of MHs, by replacing
 585      * a generic LF with a more specialized one, on the same MH,
 586      * if (a) the MH is frequently executed and (b) the MH cannot
 587      * be inlined into a containing caller, such as an invokedynamic.
 588      *
 589      * Compiled LFs that are no longer used should be GC-able.
 590      * If they contain non-BCP references, they should be properly
 591      * interlinked with the class loader(s) that their embedded types
 592      * depend on.  This probably means that reusable compiled LFs
 593      * will be tabulated (indexed) on relevant class loaders,
 594      * or else that the tables that cache them will have weak links.
 595      */
 596 
 597     /**
 598      * Make this LF directly executable, as part of a MethodHandle.
 599      * Invariant:  Every MH which is invoked must prepare its LF
 600      * before invocation.
 601      * (In principle, the JVM could do this very lazily,
 602      * as a sort of pre-invocation linkage step.)
 603      */
 604     public void prepare() {
 605         if (COMPILE_THRESHOLD == 0) {
 606             compileToBytecode();
 607         }
 608         if (this.vmentry != null) {
 609             // already prepared (e.g., a primitive DMH invoker form)
 610             return;
 611         }
 612         LambdaForm prep = getPreparedForm(basicTypeSignature());
 613         this.vmentry = prep.vmentry;
 614         // TO DO: Maybe add invokeGeneric, invokeWithArguments
 615     }
 616 
 617     /** Generate optimizable bytecode for this form. */
 618     MemberName compileToBytecode() {
 619         MethodType invokerType = methodType();
 620         assert(vmentry == null || vmentry.getMethodType().basicType().equals(invokerType));
 621         if (vmentry != null && isCompiled) {
 622             return vmentry;  // already compiled somehow
 623         }
 624         try {
 625             vmentry = InvokerBytecodeGenerator.generateCustomizedCode(this, invokerType);
 626             if (TRACE_INTERPRETER)
 627                 traceInterpreter("compileToBytecode", this);
 628             isCompiled = true;
 629             return vmentry;
 630         } catch (Error | Exception ex) {
 631             throw newInternalError(this.toString(), ex);
 632         }
 633     }
 634 
 635     private static void computeInitialPreparedForms() {
 636         // Find all predefined invokers and associate them with canonical empty lambda forms.
 637         for (MemberName m : MemberName.getFactory().getMethods(LambdaForm.class, false, null, null, null)) {
 638             if (!m.isStatic() || !m.isPackage())  continue;
 639             MethodType mt = m.getMethodType();
 640             if (mt.parameterCount() > 0 &&
 641                 mt.parameterType(0) == MethodHandle.class &&
 642                 m.getName().startsWith("interpret_")) {
 643                 String sig = basicTypeSignature(mt);
 644                 assert(m.getName().equals("interpret" + sig.substring(sig.indexOf('_'))));
 645                 LambdaForm form = new LambdaForm(sig);
 646                 form.vmentry = m;
 647                 form = mt.form().setCachedLambdaForm(MethodTypeForm.LF_INTERPRET, form);
 648             }
 649         }
 650     }
 651 
 652     // Set this false to disable use of the interpret_L methods defined in this file.
 653     private static final boolean USE_PREDEFINED_INTERPRET_METHODS = true;
 654 
 655     // The following are predefined exact invokers.  The system must build
 656     // a separate invoker for each distinct signature.
 657     static Object interpret_L(MethodHandle mh) throws Throwable {
 658         Object[] av = {mh};
 659         String sig = null;
 660         assert(argumentTypesMatch(sig = "L_L", av));
 661         Object res = mh.form.interpretWithArguments(av);
 662         assert(returnTypesMatch(sig, av, res));
 663         return res;
 664     }
 665     static Object interpret_L(MethodHandle mh, Object x1) throws Throwable {
 666         Object[] av = {mh, x1};
 667         String sig = null;
 668         assert(argumentTypesMatch(sig = "LL_L", av));
 669         Object res = mh.form.interpretWithArguments(av);
 670         assert(returnTypesMatch(sig, av, res));
 671         return res;
 672     }
 673     static Object interpret_L(MethodHandle mh, Object x1, Object x2) throws Throwable {
 674         Object[] av = {mh, x1, x2};
 675         String sig = null;
 676         assert(argumentTypesMatch(sig = "LLL_L", av));
 677         Object res = mh.form.interpretWithArguments(av);
 678         assert(returnTypesMatch(sig, av, res));
 679         return res;
 680     }
 681     private static LambdaForm getPreparedForm(String sig) {
 682         MethodType mtype = signatureType(sig);
 683         LambdaForm prep =  mtype.form().cachedLambdaForm(MethodTypeForm.LF_INTERPRET);
 684         if (prep != null)  return prep;
 685         assert(isValidSignature(sig));
 686         prep = new LambdaForm(sig);
 687         prep.vmentry = InvokerBytecodeGenerator.generateLambdaFormInterpreterEntryPoint(sig);
 688         return mtype.form().setCachedLambdaForm(MethodTypeForm.LF_INTERPRET, prep);
 689     }
 690 
 691     // The next few routines are called only from assert expressions
 692     // They verify that the built-in invokers process the correct raw data types.
 693     private static boolean argumentTypesMatch(String sig, Object[] av) {
 694         int arity = signatureArity(sig);
 695         assert(av.length == arity) : "av.length == arity: av.length=" + av.length + ", arity=" + arity;
 696         assert(av[0] instanceof MethodHandle) : "av[0] not instace of MethodHandle: " + av[0];
 697         MethodHandle mh = (MethodHandle) av[0];
 698         MethodType mt = mh.type();
 699         assert(mt.parameterCount() == arity-1);
 700         for (int i = 0; i < av.length; i++) {
 701             Class<?> pt = (i == 0 ? MethodHandle.class : mt.parameterType(i-1));
 702             assert(valueMatches(basicType(sig.charAt(i)), pt, av[i]));
 703         }
 704         return true;
 705     }
 706     private static boolean valueMatches(BasicType tc, Class<?> type, Object x) {
 707         // The following line is needed because (...)void method handles can use non-void invokers
 708         if (type == void.class)  tc = V_TYPE;   // can drop any kind of value
 709         assert tc == basicType(type) : tc + " == basicType(" + type + ")=" + basicType(type);
 710         switch (tc) {
 711         case I_TYPE: assert checkInt(type, x)   : "checkInt(" + type + "," + x +")";   break;
 712         case J_TYPE: assert x instanceof Long   : "instanceof Long: " + x;             break;
 713         case F_TYPE: assert x instanceof Float  : "instanceof Float: " + x;            break;
 714         case D_TYPE: assert x instanceof Double : "instanceof Double: " + x;           break;
 715         case L_TYPE: assert checkRef(type, x)   : "checkRef(" + type + "," + x + ")";  break;
 716         case V_TYPE: break;  // allow anything here; will be dropped
 717         default:  assert(false);
 718         }
 719         return true;
 720     }
 721     private static boolean returnTypesMatch(String sig, Object[] av, Object res) {
 722         MethodHandle mh = (MethodHandle) av[0];
 723         return valueMatches(signatureReturn(sig), mh.type().returnType(), res);
 724     }
 725     private static boolean checkInt(Class<?> type, Object x) {
 726         assert(x instanceof Integer);
 727         if (type == int.class)  return true;
 728         Wrapper w = Wrapper.forBasicType(type);
 729         assert(w.isSubwordOrInt());
 730         Object x1 = Wrapper.INT.wrap(w.wrap(x));
 731         return x.equals(x1);
 732     }
 733     private static boolean checkRef(Class<?> type, Object x) {
 734         assert(!type.isPrimitive());
 735         if (x == null)  return true;
 736         if (type.isInterface())  return true;
 737         return type.isInstance(x);
 738     }
 739 
 740     /** If the invocation count hits the threshold we spin bytecodes and call that subsequently. */
 741     private static final int COMPILE_THRESHOLD;
 742     static {
 743         COMPILE_THRESHOLD = Math.max(-1, MethodHandleStatics.COMPILE_THRESHOLD);
 744     }
 745     private int invocationCounter = 0;
 746 
 747     @Hidden
 748     @DontInline
 749     /** Interpretively invoke this form on the given arguments. */
 750     Object interpretWithArguments(Object... argumentValues) throws Throwable {
 751         if (TRACE_INTERPRETER)
 752             return interpretWithArgumentsTracing(argumentValues);
 753         checkInvocationCounter();
 754         assert(arityCheck(argumentValues));
 755         Object[] values = Arrays.copyOf(argumentValues, names.length);
 756         for (int i = argumentValues.length; i < values.length; i++) {
 757             values[i] = interpretName(names[i], values);
 758         }
 759         Object rv = (result < 0) ? null : values[result];
 760         assert(resultCheck(argumentValues, rv));
 761         return rv;
 762     }
 763 
 764     @Hidden
 765     @DontInline
 766     /** Evaluate a single Name within this form, applying its function to its arguments. */
 767     Object interpretName(Name name, Object[] values) throws Throwable {
 768         if (TRACE_INTERPRETER)
 769             traceInterpreter("| interpretName", name.debugString(), (Object[]) null);
 770         Object[] arguments = Arrays.copyOf(name.arguments, name.arguments.length, Object[].class);
 771         for (int i = 0; i < arguments.length; i++) {
 772             Object a = arguments[i];
 773             if (a instanceof Name) {
 774                 int i2 = ((Name)a).index();
 775                 assert(names[i2] == a);
 776                 a = values[i2];
 777                 arguments[i] = a;
 778             }
 779         }
 780         return name.function.invokeWithArguments(arguments);
 781     }
 782 
 783     private void checkInvocationCounter() {
 784         if (COMPILE_THRESHOLD != 0 &&
 785             invocationCounter < COMPILE_THRESHOLD) {
 786             invocationCounter++;  // benign race
 787             if (invocationCounter >= COMPILE_THRESHOLD) {
 788                 // Replace vmentry with a bytecode version of this LF.
 789                 compileToBytecode();
 790             }
 791         }
 792     }
 793     Object interpretWithArgumentsTracing(Object... argumentValues) throws Throwable {
 794         traceInterpreter("[ interpretWithArguments", this, argumentValues);
 795         if (invocationCounter < COMPILE_THRESHOLD) {
 796             int ctr = invocationCounter++;  // benign race
 797             traceInterpreter("| invocationCounter", ctr);
 798             if (invocationCounter >= COMPILE_THRESHOLD) {
 799                 compileToBytecode();
 800             }
 801         }
 802         Object rval;
 803         try {
 804             assert(arityCheck(argumentValues));
 805             Object[] values = Arrays.copyOf(argumentValues, names.length);
 806             for (int i = argumentValues.length; i < values.length; i++) {
 807                 values[i] = interpretName(names[i], values);
 808             }
 809             rval = (result < 0) ? null : values[result];
 810         } catch (Throwable ex) {
 811             traceInterpreter("] throw =>", ex);
 812             throw ex;
 813         }
 814         traceInterpreter("] return =>", rval);
 815         return rval;
 816     }
 817 
 818     static void traceInterpreter(String event, Object obj, Object... args) {
 819         if (TRACE_INTERPRETER) {
 820             System.out.println("LFI: "+event+" "+(obj != null ? obj : "")+(args != null && args.length != 0 ? Arrays.asList(args) : ""));
 821         }
 822     }
 823     static void traceInterpreter(String event, Object obj) {
 824         traceInterpreter(event, obj, (Object[])null);
 825     }
 826     private boolean arityCheck(Object[] argumentValues) {
 827         assert(argumentValues.length == arity) : arity+"!="+Arrays.asList(argumentValues)+".length";
 828         // also check that the leading (receiver) argument is somehow bound to this LF:
 829         assert(argumentValues[0] instanceof MethodHandle) : "not MH: " + argumentValues[0];
 830         MethodHandle mh = (MethodHandle) argumentValues[0];
 831         assert(mh.internalForm() == this);
 832         // note:  argument #0 could also be an interface wrapper, in the future
 833         argumentTypesMatch(basicTypeSignature(), argumentValues);
 834         return true;
 835     }
 836     private boolean resultCheck(Object[] argumentValues, Object result) {
 837         MethodHandle mh = (MethodHandle) argumentValues[0];
 838         MethodType mt = mh.type();
 839         assert(valueMatches(returnType(), mt.returnType(), result));
 840         return true;
 841     }
 842 
 843     private boolean isEmpty() {
 844         if (result < 0)
 845             return (names.length == arity);
 846         else if (result == arity && names.length == arity + 1)
 847             return names[arity].isConstantZero();
 848         else
 849             return false;
 850     }
 851 
 852     public String toString() {
 853         StringBuilder buf = new StringBuilder(debugName+"=Lambda(");
 854         for (int i = 0; i < names.length; i++) {
 855             if (i == arity)  buf.append(")=>{");
 856             Name n = names[i];
 857             if (i >= arity)  buf.append("\n    ");
 858             buf.append(n.paramString());
 859             if (i < arity) {
 860                 if (i+1 < arity)  buf.append(",");
 861                 continue;
 862             }
 863             buf.append("=").append(n.exprString());
 864             buf.append(";");
 865         }
 866         if (arity == names.length)  buf.append(")=>{");
 867         buf.append(result < 0 ? "void" : names[result]).append("}");
 868         if (TRACE_INTERPRETER) {
 869             // Extra verbosity:
 870             buf.append(":").append(basicTypeSignature());
 871             buf.append("/").append(vmentry);
 872         }
 873         return buf.toString();
 874     }
 875 
 876     @Override
 877     public boolean equals(Object obj) {
 878         return obj instanceof LambdaForm && equals((LambdaForm)obj);
 879     }
 880     public boolean equals(LambdaForm that) {
 881         if (this.result != that.result)  return false;
 882         return Arrays.equals(this.names, that.names);
 883     }
 884     public int hashCode() {
 885         return result + 31 * Arrays.hashCode(names);
 886     }
 887     LambdaFormEditor editor() {
 888         return LambdaFormEditor.lambdaFormEditor(this);
 889     }
 890 
 891     boolean contains(Name name) {
 892         int pos = name.index();
 893         if (pos >= 0) {
 894             return pos < names.length && name.equals(names[pos]);
 895         }
 896         for (int i = arity; i < names.length; i++) {
 897             if (name.equals(names[i]))
 898                 return true;
 899         }
 900         return false;
 901     }
 902 
 903     LambdaForm addArguments(int pos, BasicType... types) {
 904         // names array has MH in slot 0; skip it.
 905         int argpos = pos + 1;
 906         assert(argpos <= arity);
 907         int length = names.length;
 908         int inTypes = types.length;
 909         Name[] names2 = Arrays.copyOf(names, length + inTypes);
 910         int arity2 = arity + inTypes;
 911         int result2 = result;
 912         if (result2 >= argpos)
 913             result2 += inTypes;
 914         // Note:  The LF constructor will rename names2[argpos...].
 915         // Make space for new arguments (shift temporaries).
 916         System.arraycopy(names, argpos, names2, argpos + inTypes, length - argpos);
 917         for (int i = 0; i < inTypes; i++) {
 918             names2[argpos + i] = new Name(types[i]);
 919         }
 920         return new LambdaForm(debugName, arity2, names2, result2);
 921     }
 922 
 923     LambdaForm addArguments(int pos, List<Class<?>> types) {
 924         return addArguments(pos, basicTypes(types));
 925     }
 926 
 927     LambdaForm permuteArguments(int skip, int[] reorder, BasicType[] types) {
 928         // Note:  When inArg = reorder[outArg], outArg is fed by a copy of inArg.
 929         // The types are the types of the new (incoming) arguments.
 930         int length = names.length;
 931         int inTypes = types.length;
 932         int outArgs = reorder.length;
 933         assert(skip+outArgs == arity);
 934         assert(permutedTypesMatch(reorder, types, names, skip));
 935         int pos = 0;
 936         // skip trivial first part of reordering:
 937         while (pos < outArgs && reorder[pos] == pos)  pos += 1;
 938         Name[] names2 = new Name[length - outArgs + inTypes];
 939         System.arraycopy(names, 0, names2, 0, skip+pos);
 940         // copy the body:
 941         int bodyLength = length - arity;
 942         System.arraycopy(names, skip+outArgs, names2, skip+inTypes, bodyLength);
 943         int arity2 = names2.length - bodyLength;
 944         int result2 = result;
 945         if (result2 >= 0) {
 946             if (result2 < skip+outArgs) {
 947                 // return the corresponding inArg
 948                 result2 = reorder[result2-skip];
 949             } else {
 950                 result2 = result2 - outArgs + inTypes;
 951             }
 952         }
 953         // rework names in the body:
 954         for (int j = pos; j < outArgs; j++) {
 955             Name n = names[skip+j];
 956             int i = reorder[j];
 957             // replace names[skip+j] by names2[skip+i]
 958             Name n2 = names2[skip+i];
 959             if (n2 == null)
 960                 names2[skip+i] = n2 = new Name(types[i]);
 961             else
 962                 assert(n2.type == types[i]);
 963             for (int k = arity2; k < names2.length; k++) {
 964                 names2[k] = names2[k].replaceName(n, n2);
 965             }
 966         }
 967         // some names are unused, but must be filled in
 968         for (int i = skip+pos; i < arity2; i++) {
 969             if (names2[i] == null)
 970                 names2[i] = argument(i, types[i - skip]);
 971         }
 972         for (int j = arity; j < names.length; j++) {
 973             int i = j - arity + arity2;
 974             // replace names2[i] by names[j]
 975             Name n = names[j];
 976             Name n2 = names2[i];
 977             if (n != n2) {
 978                 for (int k = i+1; k < names2.length; k++) {
 979                     names2[k] = names2[k].replaceName(n, n2);
 980                 }
 981             }
 982         }
 983         return new LambdaForm(debugName, arity2, names2, result2);
 984     }
 985 
 986     static boolean permutedTypesMatch(int[] reorder, BasicType[] types, Name[] names, int skip) {
 987         int inTypes = types.length;
 988         int outArgs = reorder.length;
 989         for (int i = 0; i < outArgs; i++) {
 990             assert(names[skip+i].isParam());
 991             assert(names[skip+i].type == types[reorder[i]]);
 992         }
 993         return true;
 994     }
 995 
 996     static class NamedFunction {
 997         final MemberName member;
 998         @Stable MethodHandle resolvedHandle;
 999         @Stable MethodHandle invoker;
1000 
1001         NamedFunction(MethodHandle resolvedHandle) {
1002             this(resolvedHandle.internalMemberName(), resolvedHandle);
1003         }
1004         NamedFunction(MemberName member, MethodHandle resolvedHandle) {
1005             this.member = member;
1006             this.resolvedHandle = resolvedHandle;
1007              // The following assert is almost always correct, but will fail for corner cases, such as PrivateInvokeTest.
1008              //assert(!isInvokeBasic());
1009         }
1010         NamedFunction(MethodType basicInvokerType) {
1011             assert(basicInvokerType == basicInvokerType.basicType()) : basicInvokerType;
1012             if (basicInvokerType.parameterSlotCount() < MethodType.MAX_MH_INVOKER_ARITY) {
1013                 this.resolvedHandle = basicInvokerType.invokers().basicInvoker();
1014                 this.member = resolvedHandle.internalMemberName();
1015             } else {
1016                 // necessary to pass BigArityTest
1017                 this.member = Invokers.invokeBasicMethod(basicInvokerType);
1018             }
1019             assert(isInvokeBasic());
1020         }
1021 
1022         private boolean isInvokeBasic() {
1023             return member != null &&
1024                    member.isMethodHandleInvoke() &&
1025                    "invokeBasic".equals(member.getName());
1026         }
1027 
1028         // The next 3 constructors are used to break circular dependencies on MH.invokeStatic, etc.
1029         // Any LambdaForm containing such a member is not interpretable.
1030         // This is OK, since all such LFs are prepared with special primitive vmentry points.
1031         // And even without the resolvedHandle, the name can still be compiled and optimized.
1032         NamedFunction(Method method) {
1033             this(new MemberName(method));
1034         }
1035         NamedFunction(Field field) {
1036             this(new MemberName(field));
1037         }
1038         NamedFunction(MemberName member) {
1039             this.member = member;
1040             this.resolvedHandle = null;
1041         }
1042 
1043         MethodHandle resolvedHandle() {
1044             if (resolvedHandle == null)  resolve();
1045             return resolvedHandle;
1046         }
1047 
1048         void resolve() {
1049             resolvedHandle = DirectMethodHandle.make(member);
1050         }
1051 
1052         @Override
1053         public boolean equals(Object other) {
1054             if (this == other) return true;
1055             if (other == null) return false;
1056             if (!(other instanceof NamedFunction)) return false;
1057             NamedFunction that = (NamedFunction) other;
1058             return this.member != null && this.member.equals(that.member);
1059         }
1060 
1061         @Override
1062         public int hashCode() {
1063             if (member != null)
1064                 return member.hashCode();
1065             return super.hashCode();
1066         }
1067 
1068         // Put the predefined NamedFunction invokers into the table.
1069         static void initializeInvokers() {
1070             for (MemberName m : MemberName.getFactory().getMethods(NamedFunction.class, false, null, null, null)) {
1071                 if (!m.isStatic() || !m.isPackage())  continue;
1072                 MethodType type = m.getMethodType();
1073                 if (type.equals(INVOKER_METHOD_TYPE) &&
1074                     m.getName().startsWith("invoke_")) {
1075                     String sig = m.getName().substring("invoke_".length());
1076                     int arity = LambdaForm.signatureArity(sig);
1077                     MethodType srcType = MethodType.genericMethodType(arity);
1078                     if (LambdaForm.signatureReturn(sig) == V_TYPE)
1079                         srcType = srcType.changeReturnType(void.class);
1080                     MethodTypeForm typeForm = srcType.form();
1081                     typeForm.setCachedMethodHandle(MethodTypeForm.MH_NF_INV, DirectMethodHandle.make(m));
1082                 }
1083             }
1084         }
1085 
1086         // The following are predefined NamedFunction invokers.  The system must build
1087         // a separate invoker for each distinct signature.
1088         /** void return type invokers. */
1089         @Hidden
1090         static Object invoke__V(MethodHandle mh, Object[] a) throws Throwable {
1091             assert(arityCheck(0, void.class, mh, a));
1092             mh.invokeBasic();
1093             return null;
1094         }
1095         @Hidden
1096         static Object invoke_L_V(MethodHandle mh, Object[] a) throws Throwable {
1097             assert(arityCheck(1, void.class, mh, a));
1098             mh.invokeBasic(a[0]);
1099             return null;
1100         }
1101         @Hidden
1102         static Object invoke_LL_V(MethodHandle mh, Object[] a) throws Throwable {
1103             assert(arityCheck(2, void.class, mh, a));
1104             mh.invokeBasic(a[0], a[1]);
1105             return null;
1106         }
1107         @Hidden
1108         static Object invoke_LLL_V(MethodHandle mh, Object[] a) throws Throwable {
1109             assert(arityCheck(3, void.class, mh, a));
1110             mh.invokeBasic(a[0], a[1], a[2]);
1111             return null;
1112         }
1113         @Hidden
1114         static Object invoke_LLLL_V(MethodHandle mh, Object[] a) throws Throwable {
1115             assert(arityCheck(4, void.class, mh, a));
1116             mh.invokeBasic(a[0], a[1], a[2], a[3]);
1117             return null;
1118         }
1119         @Hidden
1120         static Object invoke_LLLLL_V(MethodHandle mh, Object[] a) throws Throwable {
1121             assert(arityCheck(5, void.class, mh, a));
1122             mh.invokeBasic(a[0], a[1], a[2], a[3], a[4]);
1123             return null;
1124         }
1125         /** Object return type invokers. */
1126         @Hidden
1127         static Object invoke__L(MethodHandle mh, Object[] a) throws Throwable {
1128             assert(arityCheck(0, mh, a));
1129             return mh.invokeBasic();
1130         }
1131         @Hidden
1132         static Object invoke_L_L(MethodHandle mh, Object[] a) throws Throwable {
1133             assert(arityCheck(1, mh, a));
1134             return mh.invokeBasic(a[0]);
1135         }
1136         @Hidden
1137         static Object invoke_LL_L(MethodHandle mh, Object[] a) throws Throwable {
1138             assert(arityCheck(2, mh, a));
1139             return mh.invokeBasic(a[0], a[1]);
1140         }
1141         @Hidden
1142         static Object invoke_LLL_L(MethodHandle mh, Object[] a) throws Throwable {
1143             assert(arityCheck(3, mh, a));
1144             return mh.invokeBasic(a[0], a[1], a[2]);
1145         }
1146         @Hidden
1147         static Object invoke_LLLL_L(MethodHandle mh, Object[] a) throws Throwable {
1148             assert(arityCheck(4, mh, a));
1149             return mh.invokeBasic(a[0], a[1], a[2], a[3]);
1150         }
1151         @Hidden
1152         static Object invoke_LLLLL_L(MethodHandle mh, Object[] a) throws Throwable {
1153             assert(arityCheck(5, mh, a));
1154             return mh.invokeBasic(a[0], a[1], a[2], a[3], a[4]);
1155         }
1156         private static boolean arityCheck(int arity, MethodHandle mh, Object[] a) {
1157             return arityCheck(arity, Object.class, mh, a);
1158         }
1159         private static boolean arityCheck(int arity, Class<?> rtype, MethodHandle mh, Object[] a) {
1160             assert(a.length == arity)
1161                     : Arrays.asList(a.length, arity);
1162             assert(mh.type().basicType() == MethodType.genericMethodType(arity).changeReturnType(rtype))
1163                     : Arrays.asList(mh, rtype, arity);
1164             MemberName member = mh.internalMemberName();
1165             if (member != null && member.getName().equals("invokeBasic") && member.isMethodHandleInvoke()) {
1166                 assert(arity > 0);
1167                 assert(a[0] instanceof MethodHandle);
1168                 MethodHandle mh2 = (MethodHandle) a[0];
1169                 assert(mh2.type().basicType() == MethodType.genericMethodType(arity-1).changeReturnType(rtype))
1170                         : Arrays.asList(member, mh2, rtype, arity);
1171             }
1172             return true;
1173         }
1174 
1175         static final MethodType INVOKER_METHOD_TYPE =
1176             MethodType.methodType(Object.class, MethodHandle.class, Object[].class);
1177 
1178         private static MethodHandle computeInvoker(MethodTypeForm typeForm) {
1179             typeForm = typeForm.basicType().form();  // normalize to basic type
1180             MethodHandle mh = typeForm.cachedMethodHandle(MethodTypeForm.MH_NF_INV);
1181             if (mh != null)  return mh;
1182             MemberName invoker = InvokerBytecodeGenerator.generateNamedFunctionInvoker(typeForm);  // this could take a while
1183             mh = DirectMethodHandle.make(invoker);
1184             MethodHandle mh2 = typeForm.cachedMethodHandle(MethodTypeForm.MH_NF_INV);
1185             if (mh2 != null)  return mh2;  // benign race
1186             if (!mh.type().equals(INVOKER_METHOD_TYPE))
1187                 throw newInternalError(mh.debugString());
1188             return typeForm.setCachedMethodHandle(MethodTypeForm.MH_NF_INV, mh);
1189         }
1190 
1191         @Hidden
1192         Object invokeWithArguments(Object... arguments) throws Throwable {
1193             // If we have a cached invoker, call it right away.
1194             // NOTE: The invoker always returns a reference value.
1195             if (TRACE_INTERPRETER)  return invokeWithArgumentsTracing(arguments);
1196             assert(checkArgumentTypes(arguments, methodType()));
1197             return invoker().invokeBasic(resolvedHandle(), arguments);
1198         }
1199 
1200         @Hidden
1201         Object invokeWithArgumentsTracing(Object[] arguments) throws Throwable {
1202             Object rval;
1203             try {
1204                 traceInterpreter("[ call", this, arguments);
1205                 if (invoker == null) {
1206                     traceInterpreter("| getInvoker", this);
1207                     invoker();
1208                 }
1209                 if (resolvedHandle == null) {
1210                     traceInterpreter("| resolve", this);
1211                     resolvedHandle();
1212                 }
1213                 assert(checkArgumentTypes(arguments, methodType()));
1214                 rval = invoker().invokeBasic(resolvedHandle(), arguments);
1215             } catch (Throwable ex) {
1216                 traceInterpreter("] throw =>", ex);
1217                 throw ex;
1218             }
1219             traceInterpreter("] return =>", rval);
1220             return rval;
1221         }
1222 
1223         private MethodHandle invoker() {
1224             if (invoker != null)  return invoker;
1225             // Get an invoker and cache it.
1226             return invoker = computeInvoker(methodType().form());
1227         }
1228 
1229         private static boolean checkArgumentTypes(Object[] arguments, MethodType methodType) {
1230             if (true)  return true;  // FIXME
1231             MethodType dstType = methodType.form().erasedType();
1232             MethodType srcType = dstType.basicType().wrap();
1233             Class<?>[] ptypes = new Class<?>[arguments.length];
1234             for (int i = 0; i < arguments.length; i++) {
1235                 Object arg = arguments[i];
1236                 Class<?> ptype = arg == null ? Object.class : arg.getClass();
1237                 // If the dest. type is a primitive we keep the
1238                 // argument type.
1239                 ptypes[i] = dstType.parameterType(i).isPrimitive() ? ptype : Object.class;
1240             }
1241             MethodType argType = MethodType.methodType(srcType.returnType(), ptypes).wrap();
1242             assert(argType.isConvertibleTo(srcType)) : "wrong argument types: cannot convert " + argType + " to " + srcType;
1243             return true;
1244         }
1245 
1246         MethodType methodType() {
1247             if (resolvedHandle != null)
1248                 return resolvedHandle.type();
1249             else
1250                 // only for certain internal LFs during bootstrapping
1251                 return member.getInvocationType();
1252         }
1253 
1254         MemberName member() {
1255             assert(assertMemberIsConsistent());
1256             return member;
1257         }
1258 
1259         // Called only from assert.
1260         private boolean assertMemberIsConsistent() {
1261             if (resolvedHandle instanceof DirectMethodHandle) {
1262                 MemberName m = resolvedHandle.internalMemberName();
1263                 assert(m.equals(member));
1264             }
1265             return true;
1266         }
1267 
1268         Class<?> memberDeclaringClassOrNull() {
1269             return (member == null) ? null : member.getDeclaringClass();
1270         }
1271 
1272         BasicType returnType() {
1273             return basicType(methodType().returnType());
1274         }
1275 
1276         BasicType parameterType(int n) {
1277             return basicType(methodType().parameterType(n));
1278         }
1279 
1280         int arity() {
1281             return methodType().parameterCount();
1282         }
1283 
1284         public String toString() {
1285             if (member == null)  return String.valueOf(resolvedHandle);
1286             return member.getDeclaringClass().getSimpleName()+"."+member.getName();
1287         }
1288 
1289         public boolean isIdentity() {
1290             return this.equals(identity(returnType()));
1291         }
1292 
1293         public boolean isConstantZero() {
1294             return this.equals(constantZero(returnType()));
1295         }
1296 
1297         public MethodHandleImpl.Intrinsic intrinsicName() {
1298             return resolvedHandle == null ? MethodHandleImpl.Intrinsic.NONE
1299                                           : resolvedHandle.intrinsicName();
1300         }
1301     }
1302 
1303     public static String basicTypeSignature(MethodType type) {
1304         char[] sig = new char[type.parameterCount() + 2];
1305         int sigp = 0;
1306         for (Class<?> pt : type.parameterList()) {
1307             sig[sigp++] = basicTypeChar(pt);
1308         }
1309         sig[sigp++] = '_';
1310         sig[sigp++] = basicTypeChar(type.returnType());
1311         assert(sigp == sig.length);
1312         return String.valueOf(sig);
1313     }
1314     public static String shortenSignature(String signature) {
1315         // Hack to make signatures more readable when they show up in method names.
1316         final int NO_CHAR = -1, MIN_RUN = 3;
1317         int c0, c1 = NO_CHAR, c1reps = 0;
1318         StringBuilder buf = null;
1319         int len = signature.length();
1320         if (len < MIN_RUN)  return signature;
1321         for (int i = 0; i <= len; i++) {
1322             // shift in the next char:
1323             c0 = c1; c1 = (i == len ? NO_CHAR : signature.charAt(i));
1324             if (c1 == c0) { ++c1reps; continue; }
1325             // shift in the next count:
1326             int c0reps = c1reps; c1reps = 1;
1327             // end of a  character run
1328             if (c0reps < MIN_RUN) {
1329                 if (buf != null) {
1330                     while (--c0reps >= 0)
1331                         buf.append((char)c0);
1332                 }
1333                 continue;
1334             }
1335             // found three or more in a row
1336             if (buf == null)
1337                 buf = new StringBuilder().append(signature, 0, i - c0reps);
1338             buf.append((char)c0).append(c0reps);
1339         }
1340         return (buf == null) ? signature : buf.toString();
1341     }
1342 
1343     static final class Name {
1344         final BasicType type;
1345         private short index;
1346         final NamedFunction function;
1347         final Object constraint;  // additional type information, if not null
1348         @Stable final Object[] arguments;
1349 
1350         private Name(int index, BasicType type, NamedFunction function, Object[] arguments) {
1351             this.index = (short)index;
1352             this.type = type;
1353             this.function = function;
1354             this.arguments = arguments;
1355             this.constraint = null;
1356             assert(this.index == index);
1357         }
1358         private Name(Name that, Object constraint) {
1359             this.index = that.index;
1360             this.type = that.type;
1361             this.function = that.function;
1362             this.arguments = that.arguments;
1363             this.constraint = constraint;
1364             assert(constraint == null || isParam());  // only params have constraints
1365             assert(constraint == null || constraint instanceof BoundMethodHandle.SpeciesData || constraint instanceof Class);
1366         }
1367         Name(MethodHandle function, Object... arguments) {
1368             this(new NamedFunction(function), arguments);
1369         }
1370         Name(MethodType functionType, Object... arguments) {
1371             this(new NamedFunction(functionType), arguments);
1372             assert(arguments[0] instanceof Name && ((Name)arguments[0]).type == L_TYPE);
1373         }
1374         Name(MemberName function, Object... arguments) {
1375             this(new NamedFunction(function), arguments);
1376         }
1377         Name(NamedFunction function, Object... arguments) {
1378             this(-1, function.returnType(), function, arguments = Arrays.copyOf(arguments, arguments.length, Object[].class));
1379             assert(arguments.length == function.arity()) : "arity mismatch: arguments.length=" + arguments.length + " == function.arity()=" + function.arity() + " in " + debugString();
1380             for (int i = 0; i < arguments.length; i++)
1381                 assert(typesMatch(function.parameterType(i), arguments[i])) : "types don't match: function.parameterType(" + i + ")=" + function.parameterType(i) + ", arguments[" + i + "]=" + arguments[i] + " in " + debugString();
1382         }
1383         /** Create a raw parameter of the given type, with an expected index. */
1384         Name(int index, BasicType type) {
1385             this(index, type, null, null);
1386         }
1387         /** Create a raw parameter of the given type. */
1388         Name(BasicType type) { this(-1, type); }
1389 
1390         BasicType type() { return type; }
1391         int index() { return index; }
1392         boolean initIndex(int i) {
1393             if (index != i) {
1394                 if (index != -1)  return false;
1395                 index = (short)i;
1396             }
1397             return true;
1398         }
1399         char typeChar() {
1400             return type.btChar;
1401         }
1402 
1403         void resolve() {
1404             if (function != null)
1405                 function.resolve();
1406         }
1407 
1408         Name newIndex(int i) {
1409             if (initIndex(i))  return this;
1410             return cloneWithIndex(i);
1411         }
1412         Name cloneWithIndex(int i) {
1413             Object[] newArguments = (arguments == null) ? null : arguments.clone();
1414             return new Name(i, type, function, newArguments).withConstraint(constraint);
1415         }
1416         Name withConstraint(Object constraint) {
1417             if (constraint == this.constraint)  return this;
1418             return new Name(this, constraint);
1419         }
1420         Name replaceName(Name oldName, Name newName) {  // FIXME: use replaceNames uniformly
1421             if (oldName == newName)  return this;
1422             @SuppressWarnings("LocalVariableHidesMemberVariable")
1423             Object[] arguments = this.arguments;
1424             if (arguments == null)  return this;
1425             boolean replaced = false;
1426             for (int j = 0; j < arguments.length; j++) {
1427                 if (arguments[j] == oldName) {
1428                     if (!replaced) {
1429                         replaced = true;
1430                         arguments = arguments.clone();
1431                     }
1432                     arguments[j] = newName;
1433                 }
1434             }
1435             if (!replaced)  return this;
1436             return new Name(function, arguments);
1437         }
1438         /** In the arguments of this Name, replace oldNames[i] pairwise by newNames[i].
1439          *  Limit such replacements to {@code start<=i<end}.  Return possibly changed self.
1440          */
1441         Name replaceNames(Name[] oldNames, Name[] newNames, int start, int end) {
1442             if (start >= end)  return this;
1443             @SuppressWarnings("LocalVariableHidesMemberVariable")
1444             Object[] arguments = this.arguments;
1445             boolean replaced = false;
1446         eachArg:
1447             for (int j = 0; j < arguments.length; j++) {
1448                 if (arguments[j] instanceof Name) {
1449                     Name n = (Name) arguments[j];
1450                     int check = n.index;
1451                     // harmless check to see if the thing is already in newNames:
1452                     if (check >= 0 && check < newNames.length && n == newNames[check])
1453                         continue eachArg;
1454                     // n might not have the correct index: n != oldNames[n.index].
1455                     for (int i = start; i < end; i++) {
1456                         if (n == oldNames[i]) {
1457                             if (n == newNames[i])
1458                                 continue eachArg;
1459                             if (!replaced) {
1460                                 replaced = true;
1461                                 arguments = arguments.clone();
1462                             }
1463                             arguments[j] = newNames[i];
1464                             continue eachArg;
1465                         }
1466                     }
1467                 }
1468             }
1469             if (!replaced)  return this;
1470             return new Name(function, arguments);
1471         }
1472         void internArguments() {
1473             @SuppressWarnings("LocalVariableHidesMemberVariable")
1474             Object[] arguments = this.arguments;
1475             for (int j = 0; j < arguments.length; j++) {
1476                 if (arguments[j] instanceof Name) {
1477                     Name n = (Name) arguments[j];
1478                     if (n.isParam() && n.index < INTERNED_ARGUMENT_LIMIT)
1479                         arguments[j] = internArgument(n);
1480                 }
1481             }
1482         }
1483         boolean isParam() {
1484             return function == null;
1485         }
1486         boolean isConstantZero() {
1487             return !isParam() && arguments.length == 0 && function.isConstantZero();
1488         }
1489 
1490         public String toString() {
1491             return (isParam()?"a":"t")+(index >= 0 ? index : System.identityHashCode(this))+":"+typeChar();
1492         }
1493         public String debugString() {
1494             String s = paramString();
1495             return (function == null) ? s : s + "=" + exprString();
1496         }
1497         public String paramString() {
1498             String s = toString();
1499             Object c = constraint;
1500             if (c == null)
1501                 return s;
1502             if (c instanceof Class)  c = ((Class<?>)c).getSimpleName();
1503             return s + "/" + c;
1504         }
1505         public String exprString() {
1506             if (function == null)  return toString();
1507             StringBuilder buf = new StringBuilder(function.toString());
1508             buf.append("(");
1509             String cma = "";
1510             for (Object a : arguments) {
1511                 buf.append(cma); cma = ",";
1512                 if (a instanceof Name || a instanceof Integer)
1513                     buf.append(a);
1514                 else
1515                     buf.append("(").append(a).append(")");
1516             }
1517             buf.append(")");
1518             return buf.toString();
1519         }
1520 
1521         static boolean typesMatch(BasicType parameterType, Object object) {
1522             if (object instanceof Name) {
1523                 return ((Name)object).type == parameterType;
1524             }
1525             switch (parameterType) {
1526                 case I_TYPE:  return object instanceof Integer;
1527                 case J_TYPE:  return object instanceof Long;
1528                 case F_TYPE:  return object instanceof Float;
1529                 case D_TYPE:  return object instanceof Double;
1530             }
1531             assert(parameterType == L_TYPE);
1532             return true;
1533         }
1534 
1535         /** Return the index of the last occurrence of n in the argument array.
1536          *  Return -1 if the name is not used.
1537          */
1538         int lastUseIndex(Name n) {
1539             if (arguments == null)  return -1;
1540             for (int i = arguments.length; --i >= 0; ) {
1541                 if (arguments[i] == n)  return i;
1542             }
1543             return -1;
1544         }
1545 
1546         /** Return the number of occurrences of n in the argument array.
1547          *  Return 0 if the name is not used.
1548          */
1549         int useCount(Name n) {
1550             if (arguments == null)  return 0;
1551             int count = 0;
1552             for (int i = arguments.length; --i >= 0; ) {
1553                 if (arguments[i] == n)  ++count;
1554             }
1555             return count;
1556         }
1557 
1558         boolean contains(Name n) {
1559             return this == n || lastUseIndex(n) >= 0;
1560         }
1561 
1562         public boolean equals(Name that) {
1563             if (this == that)  return true;
1564             if (isParam())
1565                 // each parameter is a unique atom
1566                 return false;  // this != that
1567             return
1568                 //this.index == that.index &&
1569                 this.type == that.type &&
1570                 this.function.equals(that.function) &&
1571                 Arrays.equals(this.arguments, that.arguments);
1572         }
1573         @Override
1574         public boolean equals(Object x) {
1575             return x instanceof Name && equals((Name)x);
1576         }
1577         @Override
1578         public int hashCode() {
1579             if (isParam())
1580                 return index | (type.ordinal() << 8);
1581             return function.hashCode() ^ Arrays.hashCode(arguments);
1582         }
1583     }
1584 
1585     /** Return the index of the last name which contains n as an argument.
1586      *  Return -1 if the name is not used.  Return names.length if it is the return value.
1587      */
1588     int lastUseIndex(Name n) {
1589         int ni = n.index, nmax = names.length;
1590         assert(names[ni] == n);
1591         if (result == ni)  return nmax;  // live all the way beyond the end
1592         for (int i = nmax; --i > ni; ) {
1593             if (names[i].lastUseIndex(n) >= 0)
1594                 return i;
1595         }
1596         return -1;
1597     }
1598 
1599     /** Return the number of times n is used as an argument or return value. */
1600     int useCount(Name n) {
1601         int ni = n.index, nmax = names.length;
1602         int end = lastUseIndex(n);
1603         if (end < 0)  return 0;
1604         int count = 0;
1605         if (end == nmax) { count++; end--; }
1606         int beg = n.index() + 1;
1607         if (beg < arity)  beg = arity;
1608         for (int i = beg; i <= end; i++) {
1609             count += names[i].useCount(n);
1610         }
1611         return count;
1612     }
1613 
1614     static Name argument(int which, char type) {
1615         return argument(which, basicType(type));
1616     }
1617     static Name argument(int which, BasicType type) {
1618         if (which >= INTERNED_ARGUMENT_LIMIT)
1619             return new Name(which, type);
1620         return INTERNED_ARGUMENTS[type.ordinal()][which];
1621     }
1622     static Name internArgument(Name n) {
1623         assert(n.isParam()) : "not param: " + n;
1624         assert(n.index < INTERNED_ARGUMENT_LIMIT);
1625         if (n.constraint != null)  return n;
1626         return argument(n.index, n.type);
1627     }
1628     static Name[] arguments(int extra, String types) {
1629         int length = types.length();
1630         Name[] names = new Name[length + extra];
1631         for (int i = 0; i < length; i++)
1632             names[i] = argument(i, types.charAt(i));
1633         return names;
1634     }
1635     static Name[] arguments(int extra, char... types) {
1636         int length = types.length;
1637         Name[] names = new Name[length + extra];
1638         for (int i = 0; i < length; i++)
1639             names[i] = argument(i, types[i]);
1640         return names;
1641     }
1642     static Name[] arguments(int extra, List<Class<?>> types) {
1643         int length = types.size();
1644         Name[] names = new Name[length + extra];
1645         for (int i = 0; i < length; i++)
1646             names[i] = argument(i, basicType(types.get(i)));
1647         return names;
1648     }
1649     static Name[] arguments(int extra, Class<?>... types) {
1650         int length = types.length;
1651         Name[] names = new Name[length + extra];
1652         for (int i = 0; i < length; i++)
1653             names[i] = argument(i, basicType(types[i]));
1654         return names;
1655     }
1656     static Name[] arguments(int extra, MethodType types) {
1657         int length = types.parameterCount();
1658         Name[] names = new Name[length + extra];
1659         for (int i = 0; i < length; i++)
1660             names[i] = argument(i, basicType(types.parameterType(i)));
1661         return names;
1662     }
1663     static final int INTERNED_ARGUMENT_LIMIT = 10;
1664     private static final Name[][] INTERNED_ARGUMENTS
1665             = new Name[ARG_TYPE_LIMIT][INTERNED_ARGUMENT_LIMIT];
1666     static {
1667         for (BasicType type : BasicType.ARG_TYPES) {
1668             int ord = type.ordinal();
1669             for (int i = 0; i < INTERNED_ARGUMENTS[ord].length; i++) {
1670                 INTERNED_ARGUMENTS[ord][i] = new Name(i, type);
1671             }
1672         }
1673     }
1674 
1675     private static final MemberName.Factory IMPL_NAMES = MemberName.getFactory();
1676 
1677     static LambdaForm identityForm(BasicType type) {
1678         return LF_identityForm[type.ordinal()];
1679     }
1680     static LambdaForm zeroForm(BasicType type) {
1681         return LF_zeroForm[type.ordinal()];
1682     }
1683     static NamedFunction identity(BasicType type) {
1684         return NF_identity[type.ordinal()];
1685     }
1686     static NamedFunction constantZero(BasicType type) {
1687         return NF_zero[type.ordinal()];
1688     }
1689     private static final LambdaForm[] LF_identityForm = new LambdaForm[TYPE_LIMIT];
1690     private static final LambdaForm[] LF_zeroForm = new LambdaForm[TYPE_LIMIT];
1691     private static final NamedFunction[] NF_identity = new NamedFunction[TYPE_LIMIT];
1692     private static final NamedFunction[] NF_zero = new NamedFunction[TYPE_LIMIT];
1693     private static void createIdentityForms() {
1694         for (BasicType type : BasicType.ALL_TYPES) {
1695             int ord = type.ordinal();
1696             char btChar = type.basicTypeChar();
1697             boolean isVoid = (type == V_TYPE);
1698             Class<?> btClass = type.btClass;
1699             MethodType zeType = MethodType.methodType(btClass);
1700             MethodType idType = isVoid ? zeType : zeType.appendParameterTypes(btClass);
1701 
1702             // Look up some symbolic names.  It might not be necessary to have these,
1703             // but if we need to emit direct references to bytecodes, it helps.
1704             // Zero is built from a call to an identity function with a constant zero input.
1705             MemberName idMem = new MemberName(LambdaForm.class, "identity_"+btChar, idType, REF_invokeStatic);
1706             MemberName zeMem = new MemberName(LambdaForm.class, "zero_"+btChar, zeType, REF_invokeStatic);
1707             try {
1708                 zeMem = IMPL_NAMES.resolveOrFail(REF_invokeStatic, zeMem, null, NoSuchMethodException.class);
1709                 idMem = IMPL_NAMES.resolveOrFail(REF_invokeStatic, idMem, null, NoSuchMethodException.class);
1710             } catch (IllegalAccessException|NoSuchMethodException ex) {
1711                 throw newInternalError(ex);
1712             }
1713 
1714             NamedFunction idFun = new NamedFunction(idMem);
1715             LambdaForm idForm;
1716             if (isVoid) {
1717                 Name[] idNames = new Name[] { argument(0, L_TYPE) };
1718                 idForm = new LambdaForm(idMem.getName(), 1, idNames, VOID_RESULT);
1719             } else {
1720                 Name[] idNames = new Name[] { argument(0, L_TYPE), argument(1, type) };
1721                 idForm = new LambdaForm(idMem.getName(), 2, idNames, 1);
1722             }
1723             LF_identityForm[ord] = idForm;
1724             NF_identity[ord] = idFun;
1725 
1726             NamedFunction zeFun = new NamedFunction(zeMem);
1727             LambdaForm zeForm;
1728             if (isVoid) {
1729                 zeForm = idForm;
1730             } else {
1731                 Object zeValue = Wrapper.forBasicType(btChar).zero();
1732                 Name[] zeNames = new Name[] { argument(0, L_TYPE), new Name(idFun, zeValue) };
1733                 zeForm = new LambdaForm(zeMem.getName(), 1, zeNames, 1);
1734             }
1735             LF_zeroForm[ord] = zeForm;
1736             NF_zero[ord] = zeFun;
1737 
1738             assert(idFun.isIdentity());
1739             assert(zeFun.isConstantZero());
1740             assert(new Name(zeFun).isConstantZero());
1741         }
1742 
1743         // Do this in a separate pass, so that SimpleMethodHandle.make can see the tables.
1744         for (BasicType type : BasicType.ALL_TYPES) {
1745             int ord = type.ordinal();
1746             NamedFunction idFun = NF_identity[ord];
1747             LambdaForm idForm = LF_identityForm[ord];
1748             MemberName idMem = idFun.member;
1749             idFun.resolvedHandle = SimpleMethodHandle.make(idMem.getInvocationType(), idForm);
1750 
1751             NamedFunction zeFun = NF_zero[ord];
1752             LambdaForm zeForm = LF_zeroForm[ord];
1753             MemberName zeMem = zeFun.member;
1754             zeFun.resolvedHandle = SimpleMethodHandle.make(zeMem.getInvocationType(), zeForm);
1755 
1756             assert(idFun.isIdentity());
1757             assert(zeFun.isConstantZero());
1758             assert(new Name(zeFun).isConstantZero());
1759         }
1760     }
1761 
1762     // Avoid appealing to ValueConversions at bootstrap time:
1763     private static int identity_I(int x) { return x; }
1764     private static long identity_J(long x) { return x; }
1765     private static float identity_F(float x) { return x; }
1766     private static double identity_D(double x) { return x; }
1767     private static Object identity_L(Object x) { return x; }
1768     private static void identity_V() { return; }  // same as zeroV, but that's OK
1769     private static int zero_I() { return 0; }
1770     private static long zero_J() { return 0; }
1771     private static float zero_F() { return 0; }
1772     private static double zero_D() { return 0; }
1773     private static Object zero_L() { return null; }
1774     private static void zero_V() { return; }
1775 
1776     /**
1777      * Internal marker for byte-compiled LambdaForms.
1778      */
1779     /*non-public*/
1780     @Target(ElementType.METHOD)
1781     @Retention(RetentionPolicy.RUNTIME)
1782     @interface Compiled {
1783     }
1784 
1785     /**
1786      * Internal marker for LambdaForm interpreter frames.
1787      */
1788     /*non-public*/
1789     @Target(ElementType.METHOD)
1790     @Retention(RetentionPolicy.RUNTIME)
1791     @interface Hidden {
1792     }
1793 
1794     private static final HashMap<String,Integer> DEBUG_NAME_COUNTERS;
1795     static {
1796         if (debugEnabled())
1797             DEBUG_NAME_COUNTERS = new HashMap<>();
1798         else
1799             DEBUG_NAME_COUNTERS = null;
1800     }
1801 
1802     // Put this last, so that previous static inits can run before.
1803     static {
1804         createIdentityForms();
1805         if (USE_PREDEFINED_INTERPRET_METHODS)
1806             computeInitialPreparedForms();
1807         NamedFunction.initializeInvokers();
1808     }
1809 
1810     // The following hack is necessary in order to suppress TRACE_INTERPRETER
1811     // during execution of the static initializes of this class.
1812     // Turning on TRACE_INTERPRETER too early will cause
1813     // stack overflows and other misbehavior during attempts to trace events
1814     // that occur during LambdaForm.<clinit>.
1815     // Therefore, do not move this line higher in this file, and do not remove.
1816     private static final boolean TRACE_INTERPRETER = MethodHandleStatics.TRACE_INTERPRETER;
1817 }