rt/emul/compact/src/main/java/java/lang/invoke/LambdaForm.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Sun, 10 Aug 2014 07:02:12 +0200
branchjdk8
changeset 1653 bd151459ee4f
parent 1646 c880a8a8803b
permissions -rw-r--r--
Capable to compile the java.lang.invoke stuff
     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.ArrayList;
    34 import java.util.HashMap;
    35 import java.util.concurrent.ConcurrentHashMap;
    36 import sun.invoke.util.Wrapper;
    37 import static java.lang.invoke.MethodHandleStatics.*;
    38 import static java.lang.invoke.MethodHandleNatives.Constants.*;
    39 import java.lang.reflect.Field;
    40 import java.util.Objects;
    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     LambdaForm(String debugName,
   134                int arity, Name[] names, int result) {
   135         assert(namesOK(arity, names));
   136         this.arity = arity;
   137         this.result = fixResult(result, names);
   138         this.names = names.clone();
   139         this.debugName = debugName;
   140         normalize();
   141     }
   142 
   143     LambdaForm(String debugName,
   144                int arity, Name[] names) {
   145         this(debugName,
   146              arity, names, LAST_RESULT);
   147     }
   148 
   149     LambdaForm(String debugName,
   150                Name[] formals, Name[] temps, Name result) {
   151         this(debugName,
   152              formals.length, buildNames(formals, temps, result), LAST_RESULT);
   153     }
   154 
   155     private static Name[] buildNames(Name[] formals, Name[] temps, Name result) {
   156         int arity = formals.length;
   157         int length = arity + temps.length + (result == null ? 0 : 1);
   158         Name[] names = Arrays.copyOf(formals, length);
   159         System.arraycopy(temps, 0, names, arity, temps.length);
   160         if (result != null)
   161             names[length - 1] = result;
   162         return names;
   163     }
   164 
   165     private LambdaForm(String sig) {
   166         // Make a blank lambda form, which returns a constant zero or null.
   167         // It is used as a template for managing the invocation of similar forms that are non-empty.
   168         // Called only from getPreparedForm.
   169         assert(isValidSignature(sig));
   170         this.arity = signatureArity(sig);
   171         this.result = (signatureReturn(sig) == 'V' ? -1 : arity);
   172         this.names = buildEmptyNames(arity, sig);
   173         this.debugName = "LF.zero";
   174         assert(nameRefsAreLegal());
   175         assert(isEmpty());
   176         assert(sig.equals(basicTypeSignature()));
   177     }
   178 
   179     private static Name[] buildEmptyNames(int arity, String basicTypeSignature) {
   180         assert(isValidSignature(basicTypeSignature));
   181         int resultPos = arity + 1;  // skip '_'
   182         if (arity < 0 || basicTypeSignature.length() != resultPos+1)
   183             throw new IllegalArgumentException("bad arity for "+basicTypeSignature);
   184         int numRes = (basicTypeSignature.charAt(resultPos) == 'V' ? 0 : 1);
   185         Name[] names = arguments(numRes, basicTypeSignature.substring(0, arity));
   186         for (int i = 0; i < numRes; i++) {
   187             names[arity + i] = constantZero(arity + i, basicTypeSignature.charAt(resultPos + i));
   188         }
   189         return names;
   190     }
   191 
   192     private static int fixResult(int result, Name[] names) {
   193         if (result >= 0) {
   194             if (names[result].type == 'V')
   195                 return -1;
   196         } else if (result == LAST_RESULT) {
   197             return names.length - 1;
   198         }
   199         return result;
   200     }
   201 
   202     private static boolean namesOK(int arity, Name[] names) {
   203         for (int i = 0; i < names.length; i++) {
   204             Name n = names[i];
   205             assert(n != null) : "n is null";
   206             if (i < arity)
   207                 assert( n.isParam()) : n + " is not param at " + i;
   208             else
   209                 assert(!n.isParam()) : n + " is param at " + i;
   210         }
   211         return true;
   212     }
   213 
   214     /** Renumber and/or replace params so that they are interned and canonically numbered. */
   215     private void normalize() {
   216         Name[] oldNames = null;
   217         int changesStart = 0;
   218         for (int i = 0; i < names.length; i++) {
   219             Name n = names[i];
   220             if (!n.initIndex(i)) {
   221                 if (oldNames == null) {
   222                     oldNames = names.clone();
   223                     changesStart = i;
   224                 }
   225                 names[i] = n.cloneWithIndex(i);
   226             }
   227         }
   228         if (oldNames != null) {
   229             int startFixing = arity;
   230             if (startFixing <= changesStart)
   231                 startFixing = changesStart+1;
   232             for (int i = startFixing; i < names.length; i++) {
   233                 Name fixed = names[i].replaceNames(oldNames, names, changesStart, i);
   234                 names[i] = fixed.newIndex(i);
   235             }
   236         }
   237         assert(nameRefsAreLegal());
   238         int maxInterned = Math.min(arity, INTERNED_ARGUMENT_LIMIT);
   239         boolean needIntern = false;
   240         for (int i = 0; i < maxInterned; i++) {
   241             Name n = names[i], n2 = internArgument(n);
   242             if (n != n2) {
   243                 names[i] = n2;
   244                 needIntern = true;
   245             }
   246         }
   247         if (needIntern) {
   248             for (int i = arity; i < names.length; i++) {
   249                 names[i].internArguments();
   250             }
   251             assert(nameRefsAreLegal());
   252         }
   253     }
   254 
   255     /**
   256      * Check that all embedded Name references are localizable to this lambda,
   257      * and are properly ordered after their corresponding definitions.
   258      * <p>
   259      * Note that a Name can be local to multiple lambdas, as long as
   260      * it possesses the same index in each use site.
   261      * This allows Name references to be freely reused to construct
   262      * fresh lambdas, without confusion.
   263      */
   264     private boolean nameRefsAreLegal() {
   265         assert(arity >= 0 && arity <= names.length);
   266         assert(result >= -1 && result < names.length);
   267         // Do all names possess an index consistent with their local definition order?
   268         for (int i = 0; i < arity; i++) {
   269             Name n = names[i];
   270             assert(n.index() == i) : Arrays.asList(n.index(), i);
   271             assert(n.isParam());
   272         }
   273         // Also, do all local name references
   274         for (int i = arity; i < names.length; i++) {
   275             Name n = names[i];
   276             assert(n.index() == i);
   277             for (Object arg : n.arguments) {
   278                 if (arg instanceof Name) {
   279                     Name n2 = (Name) arg;
   280                     int i2 = n2.index;
   281                     assert(0 <= i2 && i2 < names.length) : n.debugString() + ": 0 <= i2 && i2 < names.length: 0 <= " + i2 + " < " + names.length;
   282                     assert(names[i2] == n2) : Arrays.asList("-1-", i, "-2-", n.debugString(), "-3-", i2, "-4-", n2.debugString(), "-5-", names[i2].debugString(), "-6-", this);
   283                     assert(i2 < i);  // ref must come after def!
   284                 }
   285             }
   286         }
   287         return true;
   288     }
   289 
   290     /** Invoke this form on the given arguments. */
   291     // final Object invoke(Object... args) throws Throwable {
   292     //     // NYI: fit this into the fast path?
   293     //     return interpretWithArguments(args);
   294     // }
   295 
   296     /** Report the return type. */
   297     char returnType() {
   298         if (result < 0)  return 'V';
   299         Name n = names[result];
   300         return n.type;
   301     }
   302 
   303     /** Report the N-th argument type. */
   304     char parameterType(int n) {
   305         assert(n < arity);
   306         return names[n].type;
   307     }
   308 
   309     /** Report the arity. */
   310     int arity() {
   311         return arity;
   312     }
   313 
   314     /** Return the method type corresponding to my basic type signature. */
   315     MethodType methodType() {
   316         return signatureType(basicTypeSignature());
   317     }
   318     /** Return ABC_Z, where the ABC are parameter type characters, and Z is the return type character. */
   319     final String basicTypeSignature() {
   320         StringBuilder buf = new StringBuilder(arity() + 3);
   321         for (int i = 0, a = arity(); i < a; i++)
   322             buf.append(parameterType(i));
   323         return buf.append('_').append(returnType()).toString();
   324     }
   325     static int signatureArity(String sig) {
   326         assert(isValidSignature(sig));
   327         return sig.indexOf('_');
   328     }
   329     static char signatureReturn(String sig) {
   330         return sig.charAt(signatureArity(sig)+1);
   331     }
   332     static boolean isValidSignature(String sig) {
   333         int arity = sig.indexOf('_');
   334         if (arity < 0)  return false;  // must be of the form *_*
   335         int siglen = sig.length();
   336         if (siglen != arity + 2)  return false;  // *_X
   337         for (int i = 0; i < siglen; i++) {
   338             if (i == arity)  continue;  // skip '_'
   339             char c = sig.charAt(i);
   340             if (c == 'V')
   341                 return (i == siglen - 1 && arity == siglen - 2);
   342             if (ALL_TYPES.indexOf(c) < 0)  return false; // must be [LIJFD]
   343         }
   344         return true;  // [LIJFD]*_[LIJFDV]
   345     }
   346     static Class<?> typeClass(char t) {
   347         switch (t) {
   348         case 'I': return int.class;
   349         case 'J': return long.class;
   350         case 'F': return float.class;
   351         case 'D': return double.class;
   352         case 'L': return Object.class;
   353         case 'V': return void.class;
   354         default: assert false;
   355         }
   356         return null;
   357     }
   358     static MethodType signatureType(String sig) {
   359         Class<?>[] ptypes = new Class<?>[signatureArity(sig)];
   360         for (int i = 0; i < ptypes.length; i++)
   361             ptypes[i] = typeClass(sig.charAt(i));
   362         Class<?> rtype = typeClass(signatureReturn(sig));
   363         return MethodType.methodType(rtype, ptypes);
   364     }
   365 
   366     /*
   367      * Code generation issues:
   368      *
   369      * Compiled LFs should be reusable in general.
   370      * The biggest issue is how to decide when to pull a name into
   371      * the bytecode, versus loading a reified form from the MH data.
   372      *
   373      * For example, an asType wrapper may require execution of a cast
   374      * after a call to a MH.  The target type of the cast can be placed
   375      * as a constant in the LF itself.  This will force the cast type
   376      * to be compiled into the bytecodes and native code for the MH.
   377      * Or, the target type of the cast can be erased in the LF, and
   378      * loaded from the MH data.  (Later on, if the MH as a whole is
   379      * inlined, the data will flow into the inlined instance of the LF,
   380      * as a constant, and the end result will be an optimal cast.)
   381      *
   382      * This erasure of cast types can be done with any use of
   383      * reference types.  It can also be done with whole method
   384      * handles.  Erasing a method handle might leave behind
   385      * LF code that executes correctly for any MH of a given
   386      * type, and load the required MH from the enclosing MH's data.
   387      * Or, the erasure might even erase the expected MT.
   388      *
   389      * Also, for direct MHs, the MemberName of the target
   390      * could be erased, and loaded from the containing direct MH.
   391      * As a simple case, a LF for all int-valued non-static
   392      * field getters would perform a cast on its input argument
   393      * (to non-constant base type derived from the MemberName)
   394      * and load an integer value from the input object
   395      * (at a non-constant offset also derived from the MemberName).
   396      * Such MN-erased LFs would be inlinable back to optimized
   397      * code, whenever a constant enclosing DMH is available
   398      * to supply a constant MN from its data.
   399      *
   400      * The main problem here is to keep LFs reasonably generic,
   401      * while ensuring that hot spots will inline good instances.
   402      * "Reasonably generic" means that we don't end up with
   403      * repeated versions of bytecode or machine code that do
   404      * not differ in their optimized form.  Repeated versions
   405      * of machine would have the undesirable overheads of
   406      * (a) redundant compilation work and (b) extra I$ pressure.
   407      * To control repeated versions, we need to be ready to
   408      * erase details from LFs and move them into MH data,
   409      * whevener those details are not relevant to significant
   410      * optimization.  "Significant" means optimization of
   411      * code that is actually hot.
   412      *
   413      * Achieving this may require dynamic splitting of MHs, by replacing
   414      * a generic LF with a more specialized one, on the same MH,
   415      * if (a) the MH is frequently executed and (b) the MH cannot
   416      * be inlined into a containing caller, such as an invokedynamic.
   417      *
   418      * Compiled LFs that are no longer used should be GC-able.
   419      * If they contain non-BCP references, they should be properly
   420      * interlinked with the class loader(s) that their embedded types
   421      * depend on.  This probably means that reusable compiled LFs
   422      * will be tabulated (indexed) on relevant class loaders,
   423      * or else that the tables that cache them will have weak links.
   424      */
   425 
   426     /**
   427      * Make this LF directly executable, as part of a MethodHandle.
   428      * Invariant:  Every MH which is invoked must prepare its LF
   429      * before invocation.
   430      * (In principle, the JVM could do this very lazily,
   431      * as a sort of pre-invocation linkage step.)
   432      */
   433     public void prepare() {
   434         if (COMPILE_THRESHOLD == 0) {
   435             compileToBytecode();
   436         }
   437         if (this.vmentry != null) {
   438             // already prepared (e.g., a primitive DMH invoker form)
   439             return;
   440         }
   441         LambdaForm prep = getPreparedForm(basicTypeSignature());
   442         this.vmentry = prep.vmentry;
   443         // TO DO: Maybe add invokeGeneric, invokeWithArguments
   444     }
   445 
   446     /** Generate optimizable bytecode for this form. */
   447     MemberName compileToBytecode() {
   448         MethodType invokerType = methodType();
   449         assert(vmentry == null || vmentry.getMethodType().basicType().equals(invokerType));
   450         if (vmentry != null && isCompiled) {
   451             return vmentry;  // already compiled somehow
   452         }
   453         throw newInternalError("compileToBytecode", new Exception());
   454 //        try {
   455 //            vmentry = InvokerBytecodeGenerator.generateCustomizedCode(this, invokerType);
   456 //            if (TRACE_INTERPRETER)
   457 //                traceInterpreter("compileToBytecode", this);
   458 //            isCompiled = true;
   459 //            return vmentry;
   460 //        } catch (Error | Exception ex) {
   461 //            throw newInternalError("compileToBytecode", ex);
   462 //        }
   463     }
   464 
   465     private static final ConcurrentHashMap<String,LambdaForm> PREPARED_FORMS;
   466     static {
   467         int   capacity   = 512;    // expect many distinct signatures over time
   468         float loadFactor = 0.75f;  // normal default
   469         int   writers    = 1;
   470         PREPARED_FORMS = new ConcurrentHashMap<>(capacity, loadFactor, writers);
   471     }
   472 
   473     private static Map<String,LambdaForm> computeInitialPreparedForms() {
   474         // Find all predefined invokers and associate them with canonical empty lambda forms.
   475         HashMap<String,LambdaForm> forms = new HashMap<>();
   476         for (MemberName m : MemberName.getFactory().getMethods(LambdaForm.class, false, null, null, null)) {
   477             if (!m.isStatic() || !m.isPackage())  continue;
   478             MethodType mt = m.getMethodType();
   479             if (mt.parameterCount() > 0 &&
   480                 mt.parameterType(0) == MethodHandle.class &&
   481                 m.getName().startsWith("interpret_")) {
   482                 String sig = basicTypeSignature(mt);
   483                 assert(m.getName().equals("interpret" + sig.substring(sig.indexOf('_'))));
   484                 LambdaForm form = new LambdaForm(sig);
   485                 form.vmentry = m;
   486                 mt.form().setCachedLambdaForm(MethodTypeForm.LF_COUNTER, form);
   487                 // FIXME: get rid of PREPARED_FORMS; use MethodTypeForm cache only
   488                 forms.put(sig, form);
   489             }
   490         }
   491         //System.out.println("computeInitialPreparedForms => "+forms);
   492         return forms;
   493     }
   494 
   495     // Set this false to disable use of the interpret_L methods defined in this file.
   496     private static final boolean USE_PREDEFINED_INTERPRET_METHODS = true;
   497 
   498     // The following are predefined exact invokers.  The system must build
   499     // a separate invoker for each distinct signature.
   500     static Object interpret_L(MethodHandle mh) throws Throwable {
   501         Object[] av = {mh};
   502         String sig = null;
   503         assert(argumentTypesMatch(sig = "L_L", av));
   504         Object res = mh.form.interpretWithArguments(av);
   505         assert(returnTypesMatch(sig, av, res));
   506         return res;
   507     }
   508     static Object interpret_L(MethodHandle mh, Object x1) throws Throwable {
   509         Object[] av = {mh, x1};
   510         String sig = null;
   511         assert(argumentTypesMatch(sig = "LL_L", av));
   512         Object res = mh.form.interpretWithArguments(av);
   513         assert(returnTypesMatch(sig, av, res));
   514         return res;
   515     }
   516     static Object interpret_L(MethodHandle mh, Object x1, Object x2) throws Throwable {
   517         Object[] av = {mh, x1, x2};
   518         String sig = null;
   519         assert(argumentTypesMatch(sig = "LLL_L", av));
   520         Object res = mh.form.interpretWithArguments(av);
   521         assert(returnTypesMatch(sig, av, res));
   522         return res;
   523     }
   524     private static LambdaForm getPreparedForm(String sig) {
   525         MethodType mtype = signatureType(sig);
   526         //LambdaForm prep = PREPARED_FORMS.get(sig);
   527         LambdaForm prep =  mtype.form().cachedLambdaForm(MethodTypeForm.LF_INTERPRET);
   528         if (prep != null)  return prep;
   529         assert(isValidSignature(sig));
   530         prep = new LambdaForm(sig);
   531 //        prep.vmentry = InvokerBytecodeGenerator.generateLambdaFormInterpreterEntryPoint(sig);
   532         if (true) throw new IllegalStateException();
   533 
   534         //LambdaForm prep2 = PREPARED_FORMS.putIfAbsent(sig.intern(), prep);
   535         return mtype.form().setCachedLambdaForm(MethodTypeForm.LF_INTERPRET, prep);
   536     }
   537 
   538     // The next few routines are called only from assert expressions
   539     // They verify that the built-in invokers process the correct raw data types.
   540     private static boolean argumentTypesMatch(String sig, Object[] av) {
   541         int arity = signatureArity(sig);
   542         assert(av.length == arity) : "av.length == arity: av.length=" + av.length + ", arity=" + arity;
   543         assert(av[0] instanceof MethodHandle) : "av[0] not instace of MethodHandle: " + av[0];
   544         MethodHandle mh = (MethodHandle) av[0];
   545         MethodType mt = mh.type();
   546         assert(mt.parameterCount() == arity-1);
   547         for (int i = 0; i < av.length; i++) {
   548             Class<?> pt = (i == 0 ? MethodHandle.class : mt.parameterType(i-1));
   549             assert(valueMatches(sig.charAt(i), pt, av[i]));
   550         }
   551         return true;
   552     }
   553     private static boolean valueMatches(char tc, Class<?> type, Object x) {
   554         // The following line is needed because (...)void method handles can use non-void invokers
   555         if (type == void.class)  tc = 'V';   // can drop any kind of value
   556         assert tc == basicType(type) : tc + " == basicType(" + type + ")=" + basicType(type);
   557         switch (tc) {
   558         case 'I': assert checkInt(type, x)   : "checkInt(" + type + "," + x +")";   break;
   559         case 'J': assert x instanceof Long   : "instanceof Long: " + x;             break;
   560         case 'F': assert x instanceof Float  : "instanceof Float: " + x;            break;
   561         case 'D': assert x instanceof Double : "instanceof Double: " + x;           break;
   562         case 'L': assert checkRef(type, x)   : "checkRef(" + type + "," + x + ")";  break;
   563         case 'V': break;  // allow anything here; will be dropped
   564         default:  assert(false);
   565         }
   566         return true;
   567     }
   568     private static boolean returnTypesMatch(String sig, Object[] av, Object res) {
   569         MethodHandle mh = (MethodHandle) av[0];
   570         return valueMatches(signatureReturn(sig), mh.type().returnType(), res);
   571     }
   572     private static boolean checkInt(Class<?> type, Object x) {
   573         assert(x instanceof Integer);
   574         if (type == int.class)  return true;
   575         Wrapper w = Wrapper.forBasicType(type);
   576         assert(w.isSubwordOrInt());
   577         Object x1 = Wrapper.INT.wrap(w.wrap(x));
   578         return x.equals(x1);
   579     }
   580     private static boolean checkRef(Class<?> type, Object x) {
   581         assert(!type.isPrimitive());
   582         if (x == null)  return true;
   583         if (type.isInterface())  return true;
   584         return type.isInstance(x);
   585     }
   586 
   587     /** If the invocation count hits the threshold we spin bytecodes and call that subsequently. */
   588     private static final int COMPILE_THRESHOLD;
   589     static {
   590         if (MethodHandleStatics.COMPILE_THRESHOLD != null)
   591             COMPILE_THRESHOLD = MethodHandleStatics.COMPILE_THRESHOLD;
   592         else
   593             COMPILE_THRESHOLD = 30;  // default value
   594     }
   595     private int invocationCounter = 0;
   596 
   597     @Hidden
   598     @DontInline
   599     /** Interpretively invoke this form on the given arguments. */
   600     Object interpretWithArguments(Object... argumentValues) throws Throwable {
   601         if (TRACE_INTERPRETER)
   602             return interpretWithArgumentsTracing(argumentValues);
   603         checkInvocationCounter();
   604         assert(arityCheck(argumentValues));
   605         Object[] values = Arrays.copyOf(argumentValues, names.length);
   606         for (int i = argumentValues.length; i < values.length; i++) {
   607             values[i] = interpretName(names[i], values);
   608         }
   609         return (result < 0) ? null : values[result];
   610     }
   611 
   612     @Hidden
   613     @DontInline
   614     /** Evaluate a single Name within this form, applying its function to its arguments. */
   615     Object interpretName(Name name, Object[] values) throws Throwable {
   616         if (TRACE_INTERPRETER)
   617             traceInterpreter("| interpretName", name.debugString(), (Object[]) null);
   618         Object[] arguments = Arrays.copyOf(name.arguments, name.arguments.length, Object[].class);
   619         for (int i = 0; i < arguments.length; i++) {
   620             Object a = arguments[i];
   621             if (a instanceof Name) {
   622                 int i2 = ((Name)a).index();
   623                 assert(names[i2] == a);
   624                 a = values[i2];
   625                 arguments[i] = a;
   626             }
   627         }
   628         return name.function.invokeWithArguments(arguments);
   629     }
   630 
   631     private void checkInvocationCounter() {
   632         if (COMPILE_THRESHOLD != 0 &&
   633             invocationCounter < COMPILE_THRESHOLD) {
   634             invocationCounter++;  // benign race
   635             if (invocationCounter >= COMPILE_THRESHOLD) {
   636                 // Replace vmentry with a bytecode version of this LF.
   637                 compileToBytecode();
   638             }
   639         }
   640     }
   641     Object interpretWithArgumentsTracing(Object... argumentValues) throws Throwable {
   642         traceInterpreter("[ interpretWithArguments", this, argumentValues);
   643         if (invocationCounter < COMPILE_THRESHOLD) {
   644             int ctr = invocationCounter++;  // benign race
   645             traceInterpreter("| invocationCounter", ctr);
   646             if (invocationCounter >= COMPILE_THRESHOLD) {
   647                 compileToBytecode();
   648             }
   649         }
   650         Object rval;
   651         try {
   652             assert(arityCheck(argumentValues));
   653             Object[] values = Arrays.copyOf(argumentValues, names.length);
   654             for (int i = argumentValues.length; i < values.length; i++) {
   655                 values[i] = interpretName(names[i], values);
   656             }
   657             rval = (result < 0) ? null : values[result];
   658         } catch (Throwable ex) {
   659             traceInterpreter("] throw =>", ex);
   660             throw ex;
   661         }
   662         traceInterpreter("] return =>", rval);
   663         return rval;
   664     }
   665 
   666     //** This transform is applied (statically) to every name.function. */
   667     /*
   668     private static MethodHandle eraseSubwordTypes(MethodHandle mh) {
   669         MethodType mt = mh.type();
   670         if (mt.hasPrimitives()) {
   671             mt = mt.changeReturnType(eraseSubwordType(mt.returnType()));
   672             for (int i = 0; i < mt.parameterCount(); i++) {
   673                 mt = mt.changeParameterType(i, eraseSubwordType(mt.parameterType(i)));
   674             }
   675             mh = MethodHandles.explicitCastArguments(mh, mt);
   676         }
   677         return mh;
   678     }
   679     private static Class<?> eraseSubwordType(Class<?> type) {
   680         if (!type.isPrimitive())  return type;
   681         if (type == int.class)  return type;
   682         Wrapper w = Wrapper.forPrimitiveType(type);
   683         if (w.isSubwordOrInt())  return int.class;
   684         return type;
   685     }
   686     */
   687 
   688     static void traceInterpreter(String event, Object obj, Object... args) {
   689         if (TRACE_INTERPRETER) {
   690             System.out.println("LFI: "+event+" "+(obj != null ? obj : "")+(args != null && args.length != 0 ? Arrays.asList(args) : ""));
   691         }
   692     }
   693     static void traceInterpreter(String event, Object obj) {
   694         traceInterpreter(event, obj, (Object[])null);
   695     }
   696     private boolean arityCheck(Object[] argumentValues) {
   697         assert(argumentValues.length == arity) : arity+"!="+Arrays.asList(argumentValues)+".length";
   698         // also check that the leading (receiver) argument is somehow bound to this LF:
   699         assert(argumentValues[0] instanceof MethodHandle) : "not MH: " + argumentValues[0];
   700         assert(((MethodHandle)argumentValues[0]).internalForm() == this);
   701         // note:  argument #0 could also be an interface wrapper, in the future
   702         return true;
   703     }
   704 
   705     private boolean isEmpty() {
   706         if (result < 0)
   707             return (names.length == arity);
   708         else if (result == arity && names.length == arity + 1)
   709             return names[arity].isConstantZero();
   710         else
   711             return false;
   712     }
   713 
   714     public String toString() {
   715         StringBuilder buf = new StringBuilder(debugName+"=Lambda(");
   716         for (int i = 0; i < names.length; i++) {
   717             if (i == arity)  buf.append(")=>{");
   718             Name n = names[i];
   719             if (i >= arity)  buf.append("\n    ");
   720             buf.append(n);
   721             if (i < arity) {
   722                 if (i+1 < arity)  buf.append(",");
   723                 continue;
   724             }
   725             buf.append("=").append(n.exprString());
   726             buf.append(";");
   727         }
   728         buf.append(result < 0 ? "void" : names[result]).append("}");
   729         if (TRACE_INTERPRETER) {
   730             // Extra verbosity:
   731             buf.append(":").append(basicTypeSignature());
   732             buf.append("/").append(vmentry);
   733         }
   734         return buf.toString();
   735     }
   736 
   737     /**
   738      * Apply immediate binding for a Name in this form indicated by its position relative to the form.
   739      * The first parameter to a LambdaForm, a0:L, always represents the form's method handle, so 0 is not
   740      * accepted as valid.
   741      */
   742     LambdaForm bindImmediate(int pos, char basicType, Object value) {
   743         // must be an argument, and the types must match
   744         assert pos > 0 && pos < arity && names[pos].type == basicType && Name.typesMatch(basicType, value);
   745 
   746         int arity2 = arity - 1;
   747         Name[] names2 = new Name[names.length - 1];
   748         for (int r = 0, w = 0; r < names.length; ++r, ++w) { // (r)ead from names, (w)rite to names2
   749             Name n = names[r];
   750             if (n.isParam()) {
   751                 if (n.index == pos) {
   752                     // do not copy over the argument that is to be replaced with a literal,
   753                     // but adjust the write index
   754                     --w;
   755                 } else {
   756                     names2[w] = new Name(w, n.type);
   757                 }
   758             } else {
   759                 Object[] arguments2 = new Object[n.arguments.length];
   760                 for (int i = 0; i < n.arguments.length; ++i) {
   761                     Object arg = n.arguments[i];
   762                     if (arg instanceof Name) {
   763                         int ni = ((Name) arg).index;
   764                         if (ni == pos) {
   765                             arguments2[i] = value;
   766                         } else if (ni < pos) {
   767                             // replacement position not yet passed
   768                             arguments2[i] = names2[ni];
   769                         } else {
   770                             // replacement position passed
   771                             arguments2[i] = names2[ni - 1];
   772                         }
   773                     } else {
   774                         arguments2[i] = arg;
   775                     }
   776                 }
   777                 names2[w] = new Name(n.function, arguments2);
   778                 names2[w].initIndex(w);
   779             }
   780         }
   781 
   782         int result2 = result == -1 ? -1 : result - 1;
   783         return new LambdaForm(debugName, arity2, names2, result2);
   784     }
   785 
   786     LambdaForm bind(int namePos, BoundMethodHandle.SpeciesData oldData) {
   787         Name name = names[namePos];
   788         BoundMethodHandle.SpeciesData newData = oldData.extendWithType(name.type);
   789         return bind(name, newData.getterName(names[0], oldData.fieldCount()), oldData, newData);
   790     }
   791     LambdaForm bind(Name name, Name binding,
   792                     BoundMethodHandle.SpeciesData oldData,
   793                     BoundMethodHandle.SpeciesData newData) {
   794         int pos = name.index;
   795         assert(name.isParam());
   796         assert(!binding.isParam());
   797         assert(name.type == binding.type);
   798         assert(0 <= pos && pos < arity && names[pos] == name);
   799         assert(binding.function.memberDeclaringClassOrNull() == newData.clazz);
   800         assert(oldData.getters.length == newData.getters.length-1);
   801         if (bindCache != null) {
   802             LambdaForm form = bindCache[pos];
   803             if (form != null) {
   804                 assert(form.contains(binding)) : "form << " + form + " >> does not contain binding << " + binding + " >>";
   805                 return form;
   806             }
   807         } else {
   808             bindCache = new LambdaForm[arity];
   809         }
   810         assert(nameRefsAreLegal());
   811         int arity2 = arity-1;
   812         Name[] names2 = names.clone();
   813         names2[pos] = binding;  // we might move this in a moment
   814 
   815         // The newly created LF will run with a different BMH.
   816         // Switch over any pre-existing BMH field references to the new BMH class.
   817         int firstOldRef = -1;
   818         for (int i = 0; i < names2.length; i++) {
   819             Name n = names[i];
   820             if (n.function != null &&
   821                 n.function.memberDeclaringClassOrNull() == oldData.clazz) {
   822                 MethodHandle oldGetter = n.function.resolvedHandle;
   823                 MethodHandle newGetter = null;
   824                 for (int j = 0; j < oldData.getters.length; j++) {
   825                     if (oldGetter == oldData.getters[j])
   826                         newGetter =  newData.getters[j];
   827                 }
   828                 if (newGetter != null) {
   829                     if (firstOldRef < 0)  firstOldRef = i;
   830                     Name n2 = new Name(newGetter, n.arguments);
   831                     names2[i] = n2;
   832                 }
   833             }
   834         }
   835 
   836         // Walk over the new list of names once, in forward order.
   837         // Replace references to 'name' with 'binding'.
   838         // Replace data structure references to the old BMH species with the new.
   839         // This might cause a ripple effect, but it will settle in one pass.
   840         assert(firstOldRef < 0 || firstOldRef > pos);
   841         for (int i = pos+1; i < names2.length; i++) {
   842             if (i <= arity2)  continue;
   843             names2[i] = names2[i].replaceNames(names, names2, pos, i);
   844         }
   845 
   846         //  (a0, a1, name=a2, a3, a4)  =>  (a0, a1, a3, a4, binding)
   847         int insPos = pos;
   848         for (; insPos+1 < names2.length; insPos++) {
   849             Name n = names2[insPos+1];
   850             if (n.isSiblingBindingBefore(binding)) {
   851                 names2[insPos] = n;
   852             } else {
   853                 break;
   854             }
   855         }
   856         names2[insPos] = binding;
   857 
   858         // Since we moved some stuff, maybe update the result reference:
   859         int result2 = result;
   860         if (result2 == pos)
   861             result2 = insPos;
   862         else if (result2 > pos && result2 <= insPos)
   863             result2 -= 1;
   864 
   865         return bindCache[pos] = new LambdaForm(debugName, arity2, names2, result2);
   866     }
   867 
   868     boolean contains(Name name) {
   869         int pos = name.index();
   870         if (pos >= 0) {
   871             return pos < names.length && name.equals(names[pos]);
   872         }
   873         for (int i = arity; i < names.length; i++) {
   874             if (name.equals(names[i]))
   875                 return true;
   876         }
   877         return false;
   878     }
   879 
   880     LambdaForm addArguments(int pos, char... types) {
   881         assert(pos <= arity);
   882         int length = names.length;
   883         int inTypes = types.length;
   884         Name[] names2 = Arrays.copyOf(names, length + inTypes);
   885         int arity2 = arity + inTypes;
   886         int result2 = result;
   887         if (result2 >= arity)
   888             result2 += inTypes;
   889         // names array has MH in slot 0; skip it.
   890         int argpos = pos + 1;
   891         // Note:  The LF constructor will rename names2[argpos...].
   892         // Make space for new arguments (shift temporaries).
   893         System.arraycopy(names, argpos, names2, argpos + inTypes, length - argpos);
   894         for (int i = 0; i < inTypes; i++) {
   895             names2[argpos + i] = new Name(types[i]);
   896         }
   897         return new LambdaForm(debugName, arity2, names2, result2);
   898     }
   899 
   900     LambdaForm addArguments(int pos, List<Class<?>> types) {
   901         char[] basicTypes = new char[types.size()];
   902         for (int i = 0; i < basicTypes.length; i++)
   903             basicTypes[i] = basicType(types.get(i));
   904         return addArguments(pos, basicTypes);
   905     }
   906 
   907     LambdaForm permuteArguments(int skip, int[] reorder, char[] types) {
   908         // Note:  When inArg = reorder[outArg], outArg is fed by a copy of inArg.
   909         // The types are the types of the new (incoming) arguments.
   910         int length = names.length;
   911         int inTypes = types.length;
   912         int outArgs = reorder.length;
   913         assert(skip+outArgs == arity);
   914         assert(permutedTypesMatch(reorder, types, names, skip));
   915         int pos = 0;
   916         // skip trivial first part of reordering:
   917         while (pos < outArgs && reorder[pos] == pos)  pos += 1;
   918         Name[] names2 = new Name[length - outArgs + inTypes];
   919         System.arraycopy(names, 0, names2, 0, skip+pos);
   920         // copy the body:
   921         int bodyLength = length - arity;
   922         System.arraycopy(names, skip+outArgs, names2, skip+inTypes, bodyLength);
   923         int arity2 = names2.length - bodyLength;
   924         int result2 = result;
   925         if (result2 >= 0) {
   926             if (result2 < skip+outArgs) {
   927                 // return the corresponding inArg
   928                 result2 = reorder[result2-skip];
   929             } else {
   930                 result2 = result2 - outArgs + inTypes;
   931             }
   932         }
   933         // rework names in the body:
   934         for (int j = pos; j < outArgs; j++) {
   935             Name n = names[skip+j];
   936             int i = reorder[j];
   937             // replace names[skip+j] by names2[skip+i]
   938             Name n2 = names2[skip+i];
   939             if (n2 == null)
   940                 names2[skip+i] = n2 = new Name(types[i]);
   941             else
   942                 assert(n2.type == types[i]);
   943             for (int k = arity2; k < names2.length; k++) {
   944                 names2[k] = names2[k].replaceName(n, n2);
   945             }
   946         }
   947         // some names are unused, but must be filled in
   948         for (int i = skip+pos; i < arity2; i++) {
   949             if (names2[i] == null)
   950                 names2[i] = argument(i, types[i - skip]);
   951         }
   952         for (int j = arity; j < names.length; j++) {
   953             int i = j - arity + arity2;
   954             // replace names2[i] by names[j]
   955             Name n = names[j];
   956             Name n2 = names2[i];
   957             if (n != n2) {
   958                 for (int k = i+1; k < names2.length; k++) {
   959                     names2[k] = names2[k].replaceName(n, n2);
   960                 }
   961             }
   962         }
   963         return new LambdaForm(debugName, arity2, names2, result2);
   964     }
   965 
   966     static boolean permutedTypesMatch(int[] reorder, char[] types, Name[] names, int skip) {
   967         int inTypes = types.length;
   968         int outArgs = reorder.length;
   969         for (int i = 0; i < outArgs; i++) {
   970             assert(names[skip+i].isParam());
   971             assert(names[skip+i].type == types[reorder[i]]);
   972         }
   973         return true;
   974     }
   975 
   976     static class NamedFunction {
   977         final MemberName member;
   978         @Stable MethodHandle resolvedHandle;
   979         @Stable MethodHandle invoker;
   980 
   981         NamedFunction(MethodHandle resolvedHandle) {
   982             this(resolvedHandle.internalMemberName(), resolvedHandle);
   983         }
   984         NamedFunction(MemberName member, MethodHandle resolvedHandle) {
   985             this.member = member;
   986             //resolvedHandle = eraseSubwordTypes(resolvedHandle);
   987             this.resolvedHandle = resolvedHandle;
   988         }
   989         NamedFunction(MethodType basicInvokerType) {
   990             assert(basicInvokerType == basicInvokerType.basicType()) : basicInvokerType;
   991             if (basicInvokerType.parameterSlotCount() < MethodType.MAX_MH_INVOKER_ARITY) {
   992                 this.resolvedHandle = basicInvokerType.invokers().basicInvoker();
   993                 this.member = resolvedHandle.internalMemberName();
   994             } else {
   995                 // necessary to pass BigArityTest
   996                 this.member = Invokers.invokeBasicMethod(basicInvokerType);
   997             }
   998         }
   999 
  1000         // The next 3 constructors are used to break circular dependencies on MH.invokeStatic, etc.
  1001         // Any LambdaForm containing such a member is not interpretable.
  1002         // This is OK, since all such LFs are prepared with special primitive vmentry points.
  1003         // And even without the resolvedHandle, the name can still be compiled and optimized.
  1004         NamedFunction(Method method) {
  1005             this(new MemberName(method));
  1006         }
  1007         NamedFunction(Field field) {
  1008             this(new MemberName(field));
  1009         }
  1010         NamedFunction(MemberName member) {
  1011             this.member = member;
  1012             this.resolvedHandle = null;
  1013         }
  1014 
  1015         MethodHandle resolvedHandle() {
  1016             if (resolvedHandle == null)  resolve();
  1017             return resolvedHandle;
  1018         }
  1019 
  1020         void resolve() {
  1021             resolvedHandle = DirectMethodHandle.make(member);
  1022         }
  1023 
  1024         @Override
  1025         public boolean equals(Object other) {
  1026             if (this == other) return true;
  1027             if (other == null) return false;
  1028             if (!(other instanceof NamedFunction)) return false;
  1029             NamedFunction that = (NamedFunction) other;
  1030             return this.member != null && this.member.equals(that.member);
  1031         }
  1032 
  1033         @Override
  1034         public int hashCode() {
  1035             if (member != null)
  1036                 return member.hashCode();
  1037             return super.hashCode();
  1038         }
  1039 
  1040         // Put the predefined NamedFunction invokers into the table.
  1041         static void initializeInvokers() {
  1042             for (MemberName m : MemberName.getFactory().getMethods(NamedFunction.class, false, null, null, null)) {
  1043                 if (!m.isStatic() || !m.isPackage())  continue;
  1044                 MethodType type = m.getMethodType();
  1045                 if (type.equals(INVOKER_METHOD_TYPE) &&
  1046                     m.getName().startsWith("invoke_")) {
  1047                     String sig = m.getName().substring("invoke_".length());
  1048                     int arity = LambdaForm.signatureArity(sig);
  1049                     MethodType srcType = MethodType.genericMethodType(arity);
  1050                     if (LambdaForm.signatureReturn(sig) == 'V')
  1051                         srcType = srcType.changeReturnType(void.class);
  1052                     MethodTypeForm typeForm = srcType.form();
  1053                     typeForm.namedFunctionInvoker = DirectMethodHandle.make(m);
  1054                 }
  1055             }
  1056         }
  1057 
  1058         // The following are predefined NamedFunction invokers.  The system must build
  1059         // a separate invoker for each distinct signature.
  1060         /** void return type invokers. */
  1061         @Hidden
  1062         static Object invoke__V(MethodHandle mh, Object[] a) throws Throwable {
  1063             assert(a.length == 0);
  1064             mh.invokeBasic();
  1065             return null;
  1066         }
  1067         @Hidden
  1068         static Object invoke_L_V(MethodHandle mh, Object[] a) throws Throwable {
  1069             assert(a.length == 1);
  1070             mh.invokeBasic(a[0]);
  1071             return null;
  1072         }
  1073         @Hidden
  1074         static Object invoke_LL_V(MethodHandle mh, Object[] a) throws Throwable {
  1075             assert(a.length == 2);
  1076             mh.invokeBasic(a[0], a[1]);
  1077             return null;
  1078         }
  1079         @Hidden
  1080         static Object invoke_LLL_V(MethodHandle mh, Object[] a) throws Throwable {
  1081             assert(a.length == 3);
  1082             mh.invokeBasic(a[0], a[1], a[2]);
  1083             return null;
  1084         }
  1085         @Hidden
  1086         static Object invoke_LLLL_V(MethodHandle mh, Object[] a) throws Throwable {
  1087             assert(a.length == 4);
  1088             mh.invokeBasic(a[0], a[1], a[2], a[3]);
  1089             return null;
  1090         }
  1091         @Hidden
  1092         static Object invoke_LLLLL_V(MethodHandle mh, Object[] a) throws Throwable {
  1093             assert(a.length == 5);
  1094             mh.invokeBasic(a[0], a[1], a[2], a[3], a[4]);
  1095             return null;
  1096         }
  1097         /** Object return type invokers. */
  1098         @Hidden
  1099         static Object invoke__L(MethodHandle mh, Object[] a) throws Throwable {
  1100             assert(a.length == 0);
  1101             return mh.invokeBasic();
  1102         }
  1103         @Hidden
  1104         static Object invoke_L_L(MethodHandle mh, Object[] a) throws Throwable {
  1105             assert(a.length == 1);
  1106             return mh.invokeBasic(a[0]);
  1107         }
  1108         @Hidden
  1109         static Object invoke_LL_L(MethodHandle mh, Object[] a) throws Throwable {
  1110             assert(a.length == 2);
  1111             return mh.invokeBasic(a[0], a[1]);
  1112         }
  1113         @Hidden
  1114         static Object invoke_LLL_L(MethodHandle mh, Object[] a) throws Throwable {
  1115             assert(a.length == 3);
  1116             return mh.invokeBasic(a[0], a[1], a[2]);
  1117         }
  1118         @Hidden
  1119         static Object invoke_LLLL_L(MethodHandle mh, Object[] a) throws Throwable {
  1120             assert(a.length == 4);
  1121             return mh.invokeBasic(a[0], a[1], a[2], a[3]);
  1122         }
  1123         @Hidden
  1124         static Object invoke_LLLLL_L(MethodHandle mh, Object[] a) throws Throwable {
  1125             assert(a.length == 5);
  1126             return mh.invokeBasic(a[0], a[1], a[2], a[3], a[4]);
  1127         }
  1128 
  1129         static final MethodType INVOKER_METHOD_TYPE =
  1130             MethodType.methodType(Object.class, MethodHandle.class, Object[].class);
  1131 
  1132         private static MethodHandle computeInvoker(MethodTypeForm typeForm) {
  1133             MethodHandle mh = typeForm.namedFunctionInvoker;
  1134             if (mh != null)  return mh;
  1135 //            MemberName invoker = InvokerBytecodeGenerator.generateNamedFunctionInvoker(typeForm);  // this could take a while
  1136             if (true) throw new IllegalStateException();
  1137 //            mh = DirectMethodHandle.make(invoker);
  1138             MethodHandle mh2 = typeForm.namedFunctionInvoker;
  1139             if (mh2 != null)  return mh2;  // benign race
  1140             if (!mh.type().equals(INVOKER_METHOD_TYPE))
  1141                 throw new InternalError(mh.debugString());
  1142             return typeForm.namedFunctionInvoker = mh;
  1143         }
  1144 
  1145         @Hidden
  1146         Object invokeWithArguments(Object... arguments) throws Throwable {
  1147             // If we have a cached invoker, call it right away.
  1148             // NOTE: The invoker always returns a reference value.
  1149             if (TRACE_INTERPRETER)  return invokeWithArgumentsTracing(arguments);
  1150             assert(checkArgumentTypes(arguments, methodType()));
  1151             return invoker().invokeBasic(resolvedHandle(), arguments);
  1152         }
  1153 
  1154         @Hidden
  1155         Object invokeWithArgumentsTracing(Object[] arguments) throws Throwable {
  1156             Object rval;
  1157             try {
  1158                 traceInterpreter("[ call", this, arguments);
  1159                 if (invoker == null) {
  1160                     traceInterpreter("| getInvoker", this);
  1161                     invoker();
  1162                 }
  1163                 if (resolvedHandle == null) {
  1164                     traceInterpreter("| resolve", this);
  1165                     resolvedHandle();
  1166                 }
  1167                 assert(checkArgumentTypes(arguments, methodType()));
  1168                 rval = invoker().invokeBasic(resolvedHandle(), arguments);
  1169             } catch (Throwable ex) {
  1170                 traceInterpreter("] throw =>", ex);
  1171                 throw ex;
  1172             }
  1173             traceInterpreter("] return =>", rval);
  1174             return rval;
  1175         }
  1176 
  1177         private MethodHandle invoker() {
  1178             if (invoker != null)  return invoker;
  1179             // Get an invoker and cache it.
  1180             return invoker = computeInvoker(methodType().form());
  1181         }
  1182 
  1183         private static boolean checkArgumentTypes(Object[] arguments, MethodType methodType) {
  1184             if (true)  return true;  // FIXME
  1185             MethodType dstType = methodType.form().erasedType();
  1186             MethodType srcType = dstType.basicType().wrap();
  1187             Class<?>[] ptypes = new Class<?>[arguments.length];
  1188             for (int i = 0; i < arguments.length; i++) {
  1189                 Object arg = arguments[i];
  1190                 Class<?> ptype = arg == null ? Object.class : arg.getClass();
  1191                 // If the dest. type is a primitive we keep the
  1192                 // argument type.
  1193                 ptypes[i] = dstType.parameterType(i).isPrimitive() ? ptype : Object.class;
  1194             }
  1195             MethodType argType = MethodType.methodType(srcType.returnType(), ptypes).wrap();
  1196             assert(argType.isConvertibleTo(srcType)) : "wrong argument types: cannot convert " + argType + " to " + srcType;
  1197             return true;
  1198         }
  1199 
  1200         String basicTypeSignature() {
  1201             //return LambdaForm.basicTypeSignature(resolvedHandle.type());
  1202             return LambdaForm.basicTypeSignature(methodType());
  1203         }
  1204 
  1205         MethodType methodType() {
  1206             if (resolvedHandle != null)
  1207                 return resolvedHandle.type();
  1208             else
  1209                 // only for certain internal LFs during bootstrapping
  1210                 return member.getInvocationType();
  1211         }
  1212 
  1213         MemberName member() {
  1214             assert(assertMemberIsConsistent());
  1215             return member;
  1216         }
  1217 
  1218         // Called only from assert.
  1219         private boolean assertMemberIsConsistent() {
  1220             if (resolvedHandle instanceof DirectMethodHandle) {
  1221                 MemberName m = resolvedHandle.internalMemberName();
  1222                 assert(m.equals(member));
  1223             }
  1224             return true;
  1225         }
  1226 
  1227         Class<?> memberDeclaringClassOrNull() {
  1228             return (member == null) ? null : member.getDeclaringClass();
  1229         }
  1230 
  1231         char returnType() {
  1232             return basicType(methodType().returnType());
  1233         }
  1234 
  1235         char parameterType(int n) {
  1236             return basicType(methodType().parameterType(n));
  1237         }
  1238 
  1239         int arity() {
  1240             //int siglen = member.getMethodType().parameterCount();
  1241             //if (!member.isStatic())  siglen += 1;
  1242             //return siglen;
  1243             return methodType().parameterCount();
  1244         }
  1245 
  1246         public String toString() {
  1247             if (member == null)  return String.valueOf(resolvedHandle);
  1248             return member.getDeclaringClass().getSimpleName()+"."+member.getName();
  1249         }
  1250     }
  1251 
  1252     void resolve() {
  1253         for (Name n : names) n.resolve();
  1254     }
  1255 
  1256     public static char basicType(Class<?> type) {
  1257         char c = Wrapper.basicTypeChar(type);
  1258         if ("ZBSC".indexOf(c) >= 0)  c = 'I';
  1259         assert("LIJFDV".indexOf(c) >= 0);
  1260         return c;
  1261     }
  1262     public static char[] basicTypes(List<Class<?>> types) {
  1263         char[] btypes = new char[types.size()];
  1264         for (int i = 0; i < btypes.length; i++) {
  1265             btypes[i] = basicType(types.get(i));
  1266         }
  1267         return btypes;
  1268     }
  1269     public static String basicTypeSignature(MethodType type) {
  1270         char[] sig = new char[type.parameterCount() + 2];
  1271         int sigp = 0;
  1272         for (Class<?> pt : type.parameterList()) {
  1273             sig[sigp++] = basicType(pt);
  1274         }
  1275         sig[sigp++] = '_';
  1276         sig[sigp++] = basicType(type.returnType());
  1277         assert(sigp == sig.length);
  1278         return String.valueOf(sig);
  1279     }
  1280 
  1281     static final class Name {
  1282         final char type;
  1283         private short index;
  1284         final NamedFunction function;
  1285         @Stable final Object[] arguments;
  1286 
  1287         private Name(int index, char type, NamedFunction function, Object[] arguments) {
  1288             this.index = (short)index;
  1289             this.type = type;
  1290             this.function = function;
  1291             this.arguments = arguments;
  1292             assert(this.index == index);
  1293         }
  1294         Name(MethodHandle function, Object... arguments) {
  1295             this(new NamedFunction(function), arguments);
  1296         }
  1297         Name(MethodType functionType, Object... arguments) {
  1298             this(new NamedFunction(functionType), arguments);
  1299             assert(arguments[0] instanceof Name && ((Name)arguments[0]).type == 'L');
  1300         }
  1301         Name(MemberName function, Object... arguments) {
  1302             this(new NamedFunction(function), arguments);
  1303         }
  1304         Name(NamedFunction function, Object... arguments) {
  1305             this(-1, function.returnType(), function, arguments = arguments.clone());
  1306             assert(arguments.length == function.arity()) : "arity mismatch: arguments.length=" + arguments.length + " == function.arity()=" + function.arity() + " in " + debugString();
  1307             for (int i = 0; i < arguments.length; i++)
  1308                 assert(typesMatch(function.parameterType(i), arguments[i])) : "types don't match: function.parameterType(" + i + ")=" + function.parameterType(i) + ", arguments[" + i + "]=" + arguments[i] + " in " + debugString();
  1309         }
  1310         Name(int index, char type) {
  1311             this(index, type, null, null);
  1312         }
  1313         Name(char type) {
  1314             this(-1, type);
  1315         }
  1316 
  1317         char type() { return type; }
  1318         int index() { return index; }
  1319         boolean initIndex(int i) {
  1320             if (index != i) {
  1321                 if (index != -1)  return false;
  1322                 index = (short)i;
  1323             }
  1324             return true;
  1325         }
  1326 
  1327 
  1328         void resolve() {
  1329             if (function != null)
  1330                 function.resolve();
  1331         }
  1332 
  1333         Name newIndex(int i) {
  1334             if (initIndex(i))  return this;
  1335             return cloneWithIndex(i);
  1336         }
  1337         Name cloneWithIndex(int i) {
  1338             Object[] newArguments = (arguments == null) ? null : arguments.clone();
  1339             return new Name(i, type, function, newArguments);
  1340         }
  1341         Name replaceName(Name oldName, Name newName) {  // FIXME: use replaceNames uniformly
  1342             if (oldName == newName)  return this;
  1343             @SuppressWarnings("LocalVariableHidesMemberVariable")
  1344             Object[] arguments = this.arguments;
  1345             if (arguments == null)  return this;
  1346             boolean replaced = false;
  1347             for (int j = 0; j < arguments.length; j++) {
  1348                 if (arguments[j] == oldName) {
  1349                     if (!replaced) {
  1350                         replaced = true;
  1351                         arguments = arguments.clone();
  1352                     }
  1353                     arguments[j] = newName;
  1354                 }
  1355             }
  1356             if (!replaced)  return this;
  1357             return new Name(function, arguments);
  1358         }
  1359         Name replaceNames(Name[] oldNames, Name[] newNames, int start, int end) {
  1360             @SuppressWarnings("LocalVariableHidesMemberVariable")
  1361             Object[] arguments = this.arguments;
  1362             boolean replaced = false;
  1363         eachArg:
  1364             for (int j = 0; j < arguments.length; j++) {
  1365                 if (arguments[j] instanceof Name) {
  1366                     Name n = (Name) arguments[j];
  1367                     int check = n.index;
  1368                     // harmless check to see if the thing is already in newNames:
  1369                     if (check >= 0 && check < newNames.length && n == newNames[check])
  1370                         continue eachArg;
  1371                     // n might not have the correct index: n != oldNames[n.index].
  1372                     for (int i = start; i < end; i++) {
  1373                         if (n == oldNames[i]) {
  1374                             if (n == newNames[i])
  1375                                 continue eachArg;
  1376                             if (!replaced) {
  1377                                 replaced = true;
  1378                                 arguments = arguments.clone();
  1379                             }
  1380                             arguments[j] = newNames[i];
  1381                             continue eachArg;
  1382                         }
  1383                     }
  1384                 }
  1385             }
  1386             if (!replaced)  return this;
  1387             return new Name(function, arguments);
  1388         }
  1389         void internArguments() {
  1390             @SuppressWarnings("LocalVariableHidesMemberVariable")
  1391             Object[] arguments = this.arguments;
  1392             for (int j = 0; j < arguments.length; j++) {
  1393                 if (arguments[j] instanceof Name) {
  1394                     Name n = (Name) arguments[j];
  1395                     if (n.isParam() && n.index < INTERNED_ARGUMENT_LIMIT)
  1396                         arguments[j] = internArgument(n);
  1397                 }
  1398             }
  1399         }
  1400         boolean isParam() {
  1401             return function == null;
  1402         }
  1403         boolean isConstantZero() {
  1404             return !isParam() && arguments.length == 0 && function.equals(constantZero(0, type).function);
  1405         }
  1406 
  1407         public String toString() {
  1408             return (isParam()?"a":"t")+(index >= 0 ? index : System.identityHashCode(this))+":"+type;
  1409         }
  1410         public String debugString() {
  1411             String s = toString();
  1412             return (function == null) ? s : s + "=" + exprString();
  1413         }
  1414         public String exprString() {
  1415             if (function == null)  return "null";
  1416             StringBuilder buf = new StringBuilder(function.toString());
  1417             buf.append("(");
  1418             String cma = "";
  1419             for (Object a : arguments) {
  1420                 buf.append(cma); cma = ",";
  1421                 if (a instanceof Name || a instanceof Integer)
  1422                     buf.append(a);
  1423                 else
  1424                     buf.append("(").append(a).append(")");
  1425             }
  1426             buf.append(")");
  1427             return buf.toString();
  1428         }
  1429 
  1430         private static boolean typesMatch(char parameterType, Object object) {
  1431             if (object instanceof Name) {
  1432                 return ((Name)object).type == parameterType;
  1433             }
  1434             switch (parameterType) {
  1435                 case 'I':  return object instanceof Integer;
  1436                 case 'J':  return object instanceof Long;
  1437                 case 'F':  return object instanceof Float;
  1438                 case 'D':  return object instanceof Double;
  1439             }
  1440             assert(parameterType == 'L');
  1441             return true;
  1442         }
  1443 
  1444         /**
  1445          * Does this Name precede the given binding node in some canonical order?
  1446          * This predicate is used to order data bindings (via insertion sort)
  1447          * with some stability.
  1448          */
  1449         boolean isSiblingBindingBefore(Name binding) {
  1450             assert(!binding.isParam());
  1451             if (isParam())  return true;
  1452             if (function.equals(binding.function) &&
  1453                 arguments.length == binding.arguments.length) {
  1454                 boolean sawInt = false;
  1455                 for (int i = 0; i < arguments.length; i++) {
  1456                     Object a1 = arguments[i];
  1457                     Object a2 = binding.arguments[i];
  1458                     if (!a1.equals(a2)) {
  1459                         if (a1 instanceof Integer && a2 instanceof Integer) {
  1460                             if (sawInt)  continue;
  1461                             sawInt = true;
  1462                             if ((int)a1 < (int)a2)  continue;  // still might be true
  1463                         }
  1464                         return false;
  1465                     }
  1466                 }
  1467                 return sawInt;
  1468             }
  1469             return false;
  1470         }
  1471 
  1472         public boolean equals(Name that) {
  1473             if (this == that)  return true;
  1474             if (isParam())
  1475                 // each parameter is a unique atom
  1476                 return false;  // this != that
  1477             return
  1478                 //this.index == that.index &&
  1479                 this.type == that.type &&
  1480                 this.function.equals(that.function) &&
  1481                 Arrays.equals(this.arguments, that.arguments);
  1482         }
  1483         @Override
  1484         public boolean equals(Object x) {
  1485             return x instanceof Name && equals((Name)x);
  1486         }
  1487         @Override
  1488         public int hashCode() {
  1489             if (isParam())
  1490                 return index | (type << 8);
  1491             return function.hashCode() ^ Arrays.hashCode(arguments);
  1492         }
  1493     }
  1494 
  1495     static Name argument(int which, char type) {
  1496         int tn = ALL_TYPES.indexOf(type);
  1497         if (tn < 0 || which >= INTERNED_ARGUMENT_LIMIT)
  1498             return new Name(which, type);
  1499         return INTERNED_ARGUMENTS[tn][which];
  1500     }
  1501     static Name internArgument(Name n) {
  1502         assert(n.isParam()) : "not param: " + n;
  1503         assert(n.index < INTERNED_ARGUMENT_LIMIT);
  1504         return argument(n.index, n.type);
  1505     }
  1506     static Name[] arguments(int extra, String types) {
  1507         int length = types.length();
  1508         Name[] names = new Name[length + extra];
  1509         for (int i = 0; i < length; i++)
  1510             names[i] = argument(i, types.charAt(i));
  1511         return names;
  1512     }
  1513     static Name[] arguments(int extra, char... types) {
  1514         int length = types.length;
  1515         Name[] names = new Name[length + extra];
  1516         for (int i = 0; i < length; i++)
  1517             names[i] = argument(i, types[i]);
  1518         return names;
  1519     }
  1520     static Name[] arguments(int extra, List<Class<?>> types) {
  1521         int length = types.size();
  1522         Name[] names = new Name[length + extra];
  1523         for (int i = 0; i < length; i++)
  1524             names[i] = argument(i, basicType(types.get(i)));
  1525         return names;
  1526     }
  1527     static Name[] arguments(int extra, Class<?>... types) {
  1528         int length = types.length;
  1529         Name[] names = new Name[length + extra];
  1530         for (int i = 0; i < length; i++)
  1531             names[i] = argument(i, basicType(types[i]));
  1532         return names;
  1533     }
  1534     static Name[] arguments(int extra, MethodType types) {
  1535         int length = types.parameterCount();
  1536         Name[] names = new Name[length + extra];
  1537         for (int i = 0; i < length; i++)
  1538             names[i] = argument(i, basicType(types.parameterType(i)));
  1539         return names;
  1540     }
  1541     static final String ALL_TYPES = "LIJFD";  // omit V, not an argument type
  1542     static final int INTERNED_ARGUMENT_LIMIT = 10;
  1543     private static final Name[][] INTERNED_ARGUMENTS
  1544             = new Name[ALL_TYPES.length()][INTERNED_ARGUMENT_LIMIT];
  1545     static {
  1546         for (int tn = 0; tn < ALL_TYPES.length(); tn++) {
  1547             for (int i = 0; i < INTERNED_ARGUMENTS[tn].length; i++) {
  1548                 char type = ALL_TYPES.charAt(tn);
  1549                 INTERNED_ARGUMENTS[tn][i] = new Name(i, type);
  1550             }
  1551         }
  1552     }
  1553 
  1554     private static final MemberName.Factory IMPL_NAMES = MemberName.getFactory();
  1555 
  1556     static Name constantZero(int which, char type) {
  1557         return CONSTANT_ZERO[ALL_TYPES.indexOf(type)].newIndex(which);
  1558     }
  1559     private static final Name[] CONSTANT_ZERO
  1560             = new Name[ALL_TYPES.length()];
  1561     static {
  1562         for (int tn = 0; tn < ALL_TYPES.length(); tn++) {
  1563             char bt = ALL_TYPES.charAt(tn);
  1564             Wrapper wrap = Wrapper.forBasicType(bt);
  1565             MemberName zmem = new MemberName(LambdaForm.class, "zero"+bt, MethodType.methodType(wrap.primitiveType()), REF_invokeStatic);
  1566             try {
  1567                 zmem = IMPL_NAMES.resolveOrFail(REF_invokeStatic, zmem, null, NoSuchMethodException.class);
  1568             } catch (IllegalAccessException|NoSuchMethodException ex) {
  1569                 throw newInternalError(ex);
  1570             }
  1571             NamedFunction zcon = new NamedFunction(zmem);
  1572             Name n = new Name(zcon).newIndex(0);
  1573             assert(n.type == ALL_TYPES.charAt(tn));
  1574             CONSTANT_ZERO[tn] = n;
  1575             assert(n.isConstantZero());
  1576         }
  1577     }
  1578 
  1579     // Avoid appealing to ValueConversions at bootstrap time:
  1580     private static int zeroI() { return 0; }
  1581     private static long zeroJ() { return 0; }
  1582     private static float zeroF() { return 0; }
  1583     private static double zeroD() { return 0; }
  1584     private static Object zeroL() { return null; }
  1585 
  1586     // Put this last, so that previous static inits can run before.
  1587     static {
  1588         if (USE_PREDEFINED_INTERPRET_METHODS)
  1589             PREPARED_FORMS.putAll(computeInitialPreparedForms());
  1590     }
  1591 
  1592     /**
  1593      * Internal marker for byte-compiled LambdaForms.
  1594      */
  1595     /*non-public*/
  1596     @Target(ElementType.METHOD)
  1597     @Retention(RetentionPolicy.RUNTIME)
  1598     @interface Compiled {
  1599     }
  1600 
  1601     /**
  1602      * Internal marker for LambdaForm interpreter frames.
  1603      */
  1604     /*non-public*/
  1605     @Target(ElementType.METHOD)
  1606     @Retention(RetentionPolicy.RUNTIME)
  1607     @interface Hidden {
  1608     }
  1609 
  1610 
  1611 /*
  1612     // Smoke-test for the invokers used in this file.
  1613     static void testMethodHandleLinkers() throws Throwable {
  1614         MemberName.Factory lookup = MemberName.getFactory();
  1615         MemberName asList_MN = new MemberName(Arrays.class, "asList",
  1616                                               MethodType.methodType(List.class, Object[].class),
  1617                                               REF_invokeStatic);
  1618         //MethodHandleNatives.resolve(asList_MN, null);
  1619         asList_MN = lookup.resolveOrFail(asList_MN, REF_invokeStatic, null, NoSuchMethodException.class);
  1620         System.out.println("about to call "+asList_MN);
  1621         Object[] abc = { "a", "bc" };
  1622         List<?> lst = (List<?>) MethodHandle.linkToStatic(abc, asList_MN);
  1623         System.out.println("lst="+lst);
  1624         MemberName toString_MN = new MemberName(Object.class.getMethod("toString"));
  1625         String s1 = (String) MethodHandle.linkToVirtual(lst, toString_MN);
  1626         toString_MN = new MemberName(Object.class.getMethod("toString"), true);
  1627         String s2 = (String) MethodHandle.linkToSpecial(lst, toString_MN);
  1628         System.out.println("[s1,s2,lst]="+Arrays.asList(s1, s2, lst.toString()));
  1629         MemberName toArray_MN = new MemberName(List.class.getMethod("toArray"));
  1630         Object[] arr = (Object[]) MethodHandle.linkToInterface(lst, toArray_MN);
  1631         System.out.println("toArray="+Arrays.toString(arr));
  1632     }
  1633     static { try { testMethodHandleLinkers(); } catch (Throwable ex) { throw new RuntimeException(ex); } }
  1634     // Requires these definitions in MethodHandle:
  1635     static final native Object linkToStatic(Object x1, MemberName mn) throws Throwable;
  1636     static final native Object linkToVirtual(Object x1, MemberName mn) throws Throwable;
  1637     static final native Object linkToSpecial(Object x1, MemberName mn) throws Throwable;
  1638     static final native Object linkToInterface(Object x1, MemberName mn) throws Throwable;
  1639  */
  1640 
  1641     static { NamedFunction.initializeInvokers(); }
  1642 
  1643     // The following hack is necessary in order to suppress TRACE_INTERPRETER
  1644     // during execution of the static initializes of this class.
  1645     // Turning on TRACE_INTERPRETER too early will cause
  1646     // stack overflows and other misbehavior during attempts to trace events
  1647     // that occur during LambdaForm.<clinit>.
  1648     // Therefore, do not move this line higher in this file, and do not remove.
  1649     private static final boolean TRACE_INTERPRETER = MethodHandleStatics.TRACE_INTERPRETER;
  1650 }