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