1 /*
   2  * Copyright (c) 2008, 2015, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 package java.lang.invoke;
  27 
  28 import jdk.internal.vm.annotation.Stable;
  29 import jdk.internal.org.objectweb.asm.ClassWriter;
  30 import jdk.internal.org.objectweb.asm.FieldVisitor;
  31 import jdk.internal.org.objectweb.asm.MethodVisitor;
  32 import sun.invoke.util.ValueConversions;
  33 import sun.invoke.util.Wrapper;
  34 
  35 import java.lang.invoke.LambdaForm.NamedFunction;
  36 import java.lang.invoke.MethodHandles.Lookup;
  37 import java.lang.reflect.Field;
  38 import java.util.Arrays;
  39 import java.util.concurrent.ConcurrentHashMap;
  40 import java.util.concurrent.ConcurrentMap;
  41 import java.util.function.Function;
  42 
  43 import static java.lang.invoke.LambdaForm.BasicType;
  44 import static java.lang.invoke.LambdaForm.BasicType.*;
  45 import static java.lang.invoke.MethodHandleStatics.*;
  46 import static jdk.internal.org.objectweb.asm.Opcodes.*;
  47 
  48 /**
  49  * The flavor of method handle which emulates an invoke instruction
  50  * on a predetermined argument.  The JVM dispatches to the correct method
  51  * when the handle is created, not when it is invoked.
  52  *
  53  * All bound arguments are encapsulated in dedicated species.
  54  */
  55 /*non-public*/ abstract class BoundMethodHandle extends MethodHandle {
  56 
  57     /*non-public*/ BoundMethodHandle(MethodType type, LambdaForm form) {
  58         super(type, form);
  59         assert(speciesData() == speciesData(form));
  60     }
  61 
  62     //
  63     // BMH API and internals
  64     //
  65 
  66     static BoundMethodHandle bindSingle(MethodType type, LambdaForm form, BasicType xtype, Object x) {
  67         // for some type signatures, there exist pre-defined concrete BMH classes
  68         try {
  69             switch (xtype) {
  70             case L_TYPE:
  71                 return bindSingle(type, form, x);  // Use known fast path.
  72             case I_TYPE:
  73                 return (BoundMethodHandle) SpeciesData.EMPTY.extendWith(I_TYPE).constructor().invokeBasic(type, form, ValueConversions.widenSubword(x));
  74             case J_TYPE:
  75                 return (BoundMethodHandle) SpeciesData.EMPTY.extendWith(J_TYPE).constructor().invokeBasic(type, form, (long) x);
  76             case F_TYPE:
  77                 return (BoundMethodHandle) SpeciesData.EMPTY.extendWith(F_TYPE).constructor().invokeBasic(type, form, (float) x);
  78             case D_TYPE:
  79                 return (BoundMethodHandle) SpeciesData.EMPTY.extendWith(D_TYPE).constructor().invokeBasic(type, form, (double) x);
  80             default : throw newInternalError("unexpected xtype: " + xtype);
  81             }
  82         } catch (Throwable t) {
  83             throw newInternalError(t);
  84         }
  85     }
  86 
  87     /*non-public*/
  88     LambdaFormEditor editor() {
  89         return form.editor();
  90     }
  91 
  92     static BoundMethodHandle bindSingle(MethodType type, LambdaForm form, Object x) {
  93         return Species_L.make(type, form, x);
  94     }
  95 
  96     @Override // there is a default binder in the super class, for 'L' types only
  97     /*non-public*/
  98     BoundMethodHandle bindArgumentL(int pos, Object value) {
  99         return editor().bindArgumentL(this, pos, value);
 100     }
 101     /*non-public*/
 102     BoundMethodHandle bindArgumentI(int pos, int value) {
 103         return editor().bindArgumentI(this, pos, value);
 104     }
 105     /*non-public*/
 106     BoundMethodHandle bindArgumentJ(int pos, long value) {
 107         return editor().bindArgumentJ(this, pos, value);
 108     }
 109     /*non-public*/
 110     BoundMethodHandle bindArgumentF(int pos, float value) {
 111         return editor().bindArgumentF(this, pos, value);
 112     }
 113     /*non-public*/
 114     BoundMethodHandle bindArgumentD(int pos, double value) {
 115         return editor().bindArgumentD(this, pos, value);
 116     }
 117 
 118     @Override
 119     BoundMethodHandle rebind() {
 120         if (!tooComplex()) {
 121             return this;
 122         }
 123         return makeReinvoker(this);
 124     }
 125 
 126     private boolean tooComplex() {
 127         return (fieldCount() > FIELD_COUNT_THRESHOLD ||
 128                 form.expressionCount() > FORM_EXPRESSION_THRESHOLD);
 129     }
 130     private static final int FIELD_COUNT_THRESHOLD = 12;      // largest convenient BMH field count
 131     private static final int FORM_EXPRESSION_THRESHOLD = 24;  // largest convenient BMH expression count
 132 
 133     /**
 134      * A reinvoker MH has this form:
 135      * {@code lambda (bmh, arg*) { thismh = bmh[0]; invokeBasic(thismh, arg*) }}
 136      */
 137     static BoundMethodHandle makeReinvoker(MethodHandle target) {
 138         LambdaForm form = DelegatingMethodHandle.makeReinvokerForm(
 139                 target, MethodTypeForm.LF_REBIND,
 140                 Species_L.SPECIES_DATA, Species_L.SPECIES_DATA.getterFunction(0));
 141         return Species_L.make(target.type(), form, target);
 142     }
 143 
 144     /**
 145      * Return the {@link SpeciesData} instance representing this BMH species. All subclasses must provide a
 146      * static field containing this value, and they must accordingly implement this method.
 147      */
 148     /*non-public*/ abstract SpeciesData speciesData();
 149 
 150     /*non-public*/ static SpeciesData speciesData(LambdaForm form) {
 151         Object c = form.names[0].constraint;
 152         if (c instanceof SpeciesData)
 153             return (SpeciesData) c;
 154         // if there is no BMH constraint, then use the null constraint
 155         return SpeciesData.EMPTY;
 156     }
 157 
 158     /**
 159      * Return the number of fields in this BMH.  Equivalent to speciesData().fieldCount().
 160      */
 161     /*non-public*/ abstract int fieldCount();
 162 
 163     @Override
 164     Object internalProperties() {
 165         return "\n& BMH="+internalValues();
 166     }
 167 
 168     @Override
 169     final Object internalValues() {
 170         Object[] boundValues = new Object[speciesData().fieldCount()];
 171         for (int i = 0; i < boundValues.length; ++i) {
 172             boundValues[i] = arg(i);
 173         }
 174         return Arrays.asList(boundValues);
 175     }
 176 
 177     /*non-public*/ final Object arg(int i) {
 178         try {
 179             switch (speciesData().fieldType(i)) {
 180             case L_TYPE: return          speciesData().getters[i].invokeBasic(this);
 181             case I_TYPE: return (int)    speciesData().getters[i].invokeBasic(this);
 182             case J_TYPE: return (long)   speciesData().getters[i].invokeBasic(this);
 183             case F_TYPE: return (float)  speciesData().getters[i].invokeBasic(this);
 184             case D_TYPE: return (double) speciesData().getters[i].invokeBasic(this);
 185             }
 186         } catch (Throwable ex) {
 187             throw newInternalError(ex);
 188         }
 189         throw new InternalError("unexpected type: " + speciesData().typeChars+"."+i);
 190     }
 191 
 192     //
 193     // cloning API
 194     //
 195 
 196     /*non-public*/ abstract BoundMethodHandle copyWith(MethodType mt, LambdaForm lf);
 197     /*non-public*/ abstract BoundMethodHandle copyWithExtendL(MethodType mt, LambdaForm lf, Object narg);
 198     /*non-public*/ abstract BoundMethodHandle copyWithExtendI(MethodType mt, LambdaForm lf, int    narg);
 199     /*non-public*/ abstract BoundMethodHandle copyWithExtendJ(MethodType mt, LambdaForm lf, long   narg);
 200     /*non-public*/ abstract BoundMethodHandle copyWithExtendF(MethodType mt, LambdaForm lf, float  narg);
 201     /*non-public*/ abstract BoundMethodHandle copyWithExtendD(MethodType mt, LambdaForm lf, double narg);
 202 
 203     //
 204     // concrete BMH classes required to close bootstrap loops
 205     //
 206 
 207     private  // make it private to force users to access the enclosing class first
 208     static final class Species_L extends BoundMethodHandle {
 209         final Object argL0;
 210         private Species_L(MethodType mt, LambdaForm lf, Object argL0) {
 211             super(mt, lf);
 212             this.argL0 = argL0;
 213         }
 214         @Override
 215         /*non-public*/ SpeciesData speciesData() {
 216             return SPECIES_DATA;
 217         }
 218         @Override
 219         /*non-public*/ int fieldCount() {
 220             return 1;
 221         }
 222         /*non-public*/ static final SpeciesData SPECIES_DATA = new SpeciesData("L", Species_L.class);
 223         /*non-public*/ static BoundMethodHandle make(MethodType mt, LambdaForm lf, Object argL0) {
 224             return new Species_L(mt, lf, argL0);
 225         }
 226         @Override
 227         /*non-public*/ final BoundMethodHandle copyWith(MethodType mt, LambdaForm lf) {
 228             return new Species_L(mt, lf, argL0);
 229         }
 230         @Override
 231         /*non-public*/ final BoundMethodHandle copyWithExtendL(MethodType mt, LambdaForm lf, Object narg) {
 232             try {
 233                 return (BoundMethodHandle) SPECIES_DATA.extendWith(L_TYPE).constructor().invokeBasic(mt, lf, argL0, narg);
 234             } catch (Throwable ex) {
 235                 throw uncaughtException(ex);
 236             }
 237         }
 238         @Override
 239         /*non-public*/ final BoundMethodHandle copyWithExtendI(MethodType mt, LambdaForm lf, int narg) {
 240             try {
 241                 return (BoundMethodHandle) SPECIES_DATA.extendWith(I_TYPE).constructor().invokeBasic(mt, lf, argL0, narg);
 242             } catch (Throwable ex) {
 243                 throw uncaughtException(ex);
 244             }
 245         }
 246         @Override
 247         /*non-public*/ final BoundMethodHandle copyWithExtendJ(MethodType mt, LambdaForm lf, long narg) {
 248             try {
 249                 return (BoundMethodHandle) SPECIES_DATA.extendWith(J_TYPE).constructor().invokeBasic(mt, lf, argL0, narg);
 250             } catch (Throwable ex) {
 251                 throw uncaughtException(ex);
 252             }
 253         }
 254         @Override
 255         /*non-public*/ final BoundMethodHandle copyWithExtendF(MethodType mt, LambdaForm lf, float narg) {
 256             try {
 257                 return (BoundMethodHandle) SPECIES_DATA.extendWith(F_TYPE).constructor().invokeBasic(mt, lf, argL0, narg);
 258             } catch (Throwable ex) {
 259                 throw uncaughtException(ex);
 260             }
 261         }
 262         @Override
 263         /*non-public*/ final BoundMethodHandle copyWithExtendD(MethodType mt, LambdaForm lf, double narg) {
 264             try {
 265                 return (BoundMethodHandle) SPECIES_DATA.extendWith(D_TYPE).constructor().invokeBasic(mt, lf, argL0, narg);
 266             } catch (Throwable ex) {
 267                 throw uncaughtException(ex);
 268             }
 269         }
 270     }
 271 
 272     //
 273     // BMH species meta-data
 274     //
 275 
 276     /**
 277      * Meta-data wrapper for concrete BMH types.
 278      * Each BMH type corresponds to a given sequence of basic field types (LIJFD).
 279      * The fields are immutable; their values are fully specified at object construction.
 280      * Each BMH type supplies an array of getter functions which may be used in lambda forms.
 281      * A BMH is constructed by cloning a shorter BMH and adding one or more new field values.
 282      * The shortest possible BMH has zero fields; its class is SimpleMethodHandle.
 283      * BMH species are not interrelated by subtyping, even though it would appear that
 284      * a shorter BMH could serve as a supertype of a longer one which extends it.
 285      */
 286     static class SpeciesData {
 287         private final String                             typeChars;
 288         private final BasicType[]                        typeCodes;
 289         private final Class<? extends BoundMethodHandle> clazz;
 290         // Bootstrapping requires circular relations MH -> BMH -> SpeciesData -> MH
 291         // Therefore, we need a non-final link in the chain.  Use array elements.
 292         @Stable private final MethodHandle[]             constructor;
 293         @Stable private final MethodHandle[]             getters;
 294         @Stable private final NamedFunction[]            nominalGetters;
 295         @Stable private final SpeciesData[]              extensions;
 296 
 297         /*non-public*/ int fieldCount() {
 298             return typeCodes.length;
 299         }
 300         /*non-public*/ BasicType fieldType(int i) {
 301             return typeCodes[i];
 302         }
 303         /*non-public*/ char fieldTypeChar(int i) {
 304             return typeChars.charAt(i);
 305         }
 306         Object fieldSignature() {
 307             return typeChars;
 308         }
 309         public Class<? extends BoundMethodHandle> fieldHolder() {
 310             return clazz;
 311         }
 312         public String toString() {
 313             return "SpeciesData<"+fieldSignature()+">";
 314         }
 315 
 316         /**
 317          * Return a {@link LambdaForm.Name} containing a {@link LambdaForm.NamedFunction} that
 318          * represents a MH bound to a generic invoker, which in turn forwards to the corresponding
 319          * getter.
 320          */
 321         NamedFunction getterFunction(int i) {
 322             NamedFunction nf = nominalGetters[i];
 323             assert(nf.memberDeclaringClassOrNull() == fieldHolder());
 324             assert(nf.returnType() == fieldType(i));
 325             return nf;
 326         }
 327 
 328         NamedFunction[] getterFunctions() {
 329             return nominalGetters;
 330         }
 331 
 332         MethodHandle[] getterHandles() { return getters; }
 333 
 334         MethodHandle constructor() {
 335             return constructor[0];
 336         }
 337 
 338         static final SpeciesData EMPTY = new SpeciesData("", BoundMethodHandle.class);
 339 
 340         SpeciesData(String types, Class<? extends BoundMethodHandle> clazz) {
 341             this.typeChars = types;
 342             this.typeCodes = basicTypes(types);
 343             this.clazz = clazz;
 344             if (!INIT_DONE) {
 345                 this.constructor = new MethodHandle[1];  // only one ctor
 346                 this.getters = new MethodHandle[types.length()];
 347                 this.nominalGetters = new NamedFunction[types.length()];
 348             } else {
 349                 this.constructor = Factory.makeCtors(clazz, types, null);
 350                 this.getters = Factory.makeGetters(clazz, types, null);
 351                 this.nominalGetters = Factory.makeNominalGetters(types, null, this.getters);
 352             }
 353             this.extensions = new SpeciesData[ARG_TYPE_LIMIT];
 354         }
 355 
 356         private void initForBootstrap() {
 357             assert(!INIT_DONE);
 358             if (constructor() == null) {
 359                 String types = typeChars;
 360                 CACHE.put(types, this);
 361                 Factory.makeCtors(clazz, types, this.constructor);
 362                 Factory.makeGetters(clazz, types, this.getters);
 363                 Factory.makeNominalGetters(types, this.nominalGetters, this.getters);
 364             }
 365         }
 366 
 367         private static final ConcurrentMap<String, SpeciesData> CACHE = new ConcurrentHashMap<>();
 368         private static final boolean INIT_DONE;  // set after <clinit> finishes...
 369 
 370         SpeciesData extendWith(byte type) {
 371             return extendWith(BasicType.basicType(type));
 372         }
 373 
 374         SpeciesData extendWith(BasicType type) {
 375             int ord = type.ordinal();
 376             SpeciesData d = extensions[ord];
 377             if (d != null)  return d;
 378             extensions[ord] = d = get(typeChars+type.basicTypeChar());
 379             return d;
 380         }
 381 
 382         private static SpeciesData get(String types) {
 383             return CACHE.computeIfAbsent(types, new Function<String, SpeciesData>() {
 384                 @Override
 385                 public SpeciesData apply(String types) {
 386                     Class<? extends BoundMethodHandle> bmhcl = Factory.getConcreteBMHClass(types);
 387                     // SpeciesData instantiation may throw VirtualMachineError because of
 388                     // code cache overflow...
 389                     SpeciesData speciesData = new SpeciesData(types, bmhcl);
 390                     // CHM.computeIfAbsent ensures only one SpeciesData will be set
 391                     // successfully on the concrete BMH class if ever
 392                     Factory.setSpeciesDataToConcreteBMHClass(bmhcl, speciesData);
 393                     // the concrete BMH class is published via SpeciesData instance
 394                     // returned here only after it's SPECIES_DATA field is set
 395                     return speciesData;
 396                 }
 397             });
 398         }
 399 
 400         /**
 401          * This is to be called when assertions are enabled. It checks whether SpeciesData for all of the statically
 402          * defined species subclasses of BoundMethodHandle has been added to the SpeciesData cache. See below in the
 403          * static initializer for
 404          */
 405         static boolean speciesDataCachePopulated() {
 406             Class<BoundMethodHandle> rootCls = BoundMethodHandle.class;
 407             try {
 408                 for (Class<?> c : rootCls.getDeclaredClasses()) {
 409                     if (rootCls.isAssignableFrom(c)) {
 410                         final Class<? extends BoundMethodHandle> cbmh = c.asSubclass(BoundMethodHandle.class);
 411                         SpeciesData d = Factory.getSpeciesDataFromConcreteBMHClass(cbmh);
 412                         assert(d != null) : cbmh.getName();
 413                         assert(d.clazz == cbmh);
 414                         assert(CACHE.get(d.typeChars) == d);
 415                     }
 416                 }
 417             } catch (Throwable e) {
 418                 throw newInternalError(e);
 419             }
 420             return true;
 421         }
 422 
 423         static {
 424             // Pre-fill the BMH species-data cache with EMPTY and all BMH's inner subclasses.
 425             EMPTY.initForBootstrap();
 426             Species_L.SPECIES_DATA.initForBootstrap();
 427             // check that all static SpeciesData instances have been initialized
 428             assert speciesDataCachePopulated();
 429             // Note:  Do not simplify this, because INIT_DONE must not be
 430             // a compile-time constant during bootstrapping.
 431             INIT_DONE = Boolean.TRUE;
 432         }
 433     }
 434 
 435     static SpeciesData getSpeciesData(String types) {
 436         return SpeciesData.get(types);
 437     }
 438 
 439     /**
 440      * Generation of concrete BMH classes.
 441      *
 442      * A concrete BMH species is fit for binding a number of values adhering to a
 443      * given type pattern. Reference types are erased.
 444      *
 445      * BMH species are cached by type pattern.
 446      *
 447      * A BMH species has a number of fields with the concrete (possibly erased) types of
 448      * bound values. Setters are provided as an API in BMH. Getters are exposed as MHs,
 449      * which can be included as names in lambda forms.
 450      */
 451     static class Factory {
 452 
 453         static final String JLO_SIG  = "Ljava/lang/Object;";
 454         static final String JLS_SIG  = "Ljava/lang/String;";
 455         static final String JLC_SIG  = "Ljava/lang/Class;";
 456         static final String MH       = "java/lang/invoke/MethodHandle";
 457         static final String MH_SIG   = "L"+MH+";";
 458         static final String BMH      = "java/lang/invoke/BoundMethodHandle";
 459         static final String BMH_SIG  = "L"+BMH+";";
 460         static final String SPECIES_DATA     = "java/lang/invoke/BoundMethodHandle$SpeciesData";
 461         static final String SPECIES_DATA_SIG = "L"+SPECIES_DATA+";";
 462         static final String STABLE_SIG       = "Ljdk/internal/vm/annotation/Stable;";
 463 
 464         static final String SPECIES_PREFIX_NAME = "Species_";
 465         static final String SPECIES_PREFIX_PATH = BMH + "$" + SPECIES_PREFIX_NAME;
 466 
 467         static final String BMHSPECIES_DATA_EWI_SIG = "(B)" + SPECIES_DATA_SIG;
 468         static final String BMHSPECIES_DATA_GFC_SIG = "(" + JLS_SIG + JLC_SIG + ")" + SPECIES_DATA_SIG;
 469         static final String MYSPECIES_DATA_SIG = "()" + SPECIES_DATA_SIG;
 470         static final String VOID_SIG   = "()V";
 471         static final String INT_SIG    = "()I";
 472 
 473         static final String SIG_INCIPIT = "(Ljava/lang/invoke/MethodType;Ljava/lang/invoke/LambdaForm;";
 474 
 475         static final String[] E_THROWABLE = new String[] { "java/lang/Throwable" };
 476 
 477         static final ConcurrentMap<String, Class<? extends BoundMethodHandle>> CLASS_CACHE = new ConcurrentHashMap<>();
 478 
 479         /**
 480          * Get a concrete subclass of BMH for a given combination of bound types.
 481          *
 482          * @param types the type signature, wherein reference types are erased to 'L'
 483          * @return the concrete BMH class
 484          */
 485         static Class<? extends BoundMethodHandle> getConcreteBMHClass(String types) {
 486             // CHM.computeIfAbsent ensures generateConcreteBMHClass is called
 487             // only once per key.
 488             return CLASS_CACHE.computeIfAbsent(types, SPECIES_LOOKUP);
 489         }
 490 
 491         static final SpeciesLookup SPECIES_LOOKUP = new SpeciesLookup();
 492 
 493         /**
 494          * @implNote this Function class is intentionally made a named inner
 495          * class to act as a hook for generating BMHs ahead-of-time.
 496          */
 497         static class SpeciesLookup implements Function<String, Class<? extends BoundMethodHandle>> {
 498             @Override
 499             public Class<? extends BoundMethodHandle> apply(String types) {
 500                 return generateConcreteBMHClass(types);
 501             }
 502         }
 503 
 504         /**
 505          * Generate a concrete subclass of BMH for a given combination of bound types.
 506          *
 507          * A concrete BMH species adheres to the following schema:
 508          *
 509          * <pre>
 510          * class Species_[[types]] extends BoundMethodHandle {
 511          *     [[fields]]
 512          *     final SpeciesData speciesData() { return SpeciesData.get("[[types]]"); }
 513          * }
 514          * </pre>
 515          *
 516          * The {@code [[types]]} signature is precisely the string that is passed to this
 517          * method.
 518          *
 519          * The {@code [[fields]]} section consists of one field definition per character in
 520          * the type signature, adhering to the naming schema described in the definition of
 521          * {@link #makeFieldName}.
 522          *
 523          * For example, a concrete BMH species for two reference and one integral bound values
 524          * would have the following shape:
 525          *
 526          * <pre>
 527          * class BoundMethodHandle { ... private static
 528          * final class Species_LLI extends BoundMethodHandle {
 529          *     final Object argL0;
 530          *     final Object argL1;
 531          *     final int argI2;
 532          *     private Species_LLI(MethodType mt, LambdaForm lf, Object argL0, Object argL1, int argI2) {
 533          *         super(mt, lf);
 534          *         this.argL0 = argL0;
 535          *         this.argL1 = argL1;
 536          *         this.argI2 = argI2;
 537          *     }
 538          *     final SpeciesData speciesData() { return SPECIES_DATA; }
 539          *     final int fieldCount() { return 3; }
 540          *     @Stable static SpeciesData SPECIES_DATA; // injected afterwards
 541          *     static BoundMethodHandle make(MethodType mt, LambdaForm lf, Object argL0, Object argL1, int argI2) {
 542          *         return new Species_LLI(mt, lf, argL0, argL1, argI2);
 543          *     }
 544          *     final BoundMethodHandle copyWith(MethodType mt, LambdaForm lf) {
 545          *         return new Species_LLI(mt, lf, argL0, argL1, argI2);
 546          *     }
 547          *     final BoundMethodHandle copyWithExtendL(MethodType mt, LambdaForm lf, Object narg) {
 548          *         return SPECIES_DATA.extendWith(L_TYPE).constructor().invokeBasic(mt, lf, argL0, argL1, argI2, narg);
 549          *     }
 550          *     final BoundMethodHandle copyWithExtendI(MethodType mt, LambdaForm lf, int narg) {
 551          *         return SPECIES_DATA.extendWith(I_TYPE).constructor().invokeBasic(mt, lf, argL0, argL1, argI2, narg);
 552          *     }
 553          *     final BoundMethodHandle copyWithExtendJ(MethodType mt, LambdaForm lf, long narg) {
 554          *         return SPECIES_DATA.extendWith(J_TYPE).constructor().invokeBasic(mt, lf, argL0, argL1, argI2, narg);
 555          *     }
 556          *     final BoundMethodHandle copyWithExtendF(MethodType mt, LambdaForm lf, float narg) {
 557          *         return SPECIES_DATA.extendWith(F_TYPE).constructor().invokeBasic(mt, lf, argL0, argL1, argI2, narg);
 558          *     }
 559          *     public final BoundMethodHandle copyWithExtendD(MethodType mt, LambdaForm lf, double narg) {
 560          *         return SPECIES_DATA.extendWith(D_TYPE).constructor().invokeBasic(mt, lf, argL0, argL1, argI2, narg);
 561          *     }
 562          * }
 563          * </pre>
 564          *
 565          * @param types the type signature, wherein reference types are erased to 'L'
 566          * @return the generated concrete BMH class
 567          */
 568         static Class<? extends BoundMethodHandle> generateConcreteBMHClass(String types) {
 569             String shortTypes = LambdaForm.shortenSignature(types);
 570             final String className  = SPECIES_PREFIX_PATH + shortTypes;
 571             final String sourceFile = SPECIES_PREFIX_NAME + shortTypes;
 572 
 573             byte[] classFile = generateConcreteBMHClassBytes(className, sourceFile, types);
 574 
 575             // load class
 576             InvokerBytecodeGenerator.maybeDump(className, classFile);
 577             Class<? extends BoundMethodHandle> bmhClass =
 578                 //UNSAFE.defineAnonymousClass(BoundMethodHandle.class, classFile, null).asSubclass(BoundMethodHandle.class);
 579                 UNSAFE.defineClass(className, classFile, 0, classFile.length,
 580                                    BoundMethodHandle.class.getClassLoader(), null)
 581                     .asSubclass(BoundMethodHandle.class);
 582 
 583             return bmhClass;
 584         }
 585 
 586         static byte[] generateConcreteBMHClassBytes(final String className, final String sourceFile, final String types) {
 587             final ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS + ClassWriter.COMPUTE_FRAMES);
 588             final int NOT_ACC_PUBLIC = 0;  // not ACC_PUBLIC
 589             cw.visit(V1_6, NOT_ACC_PUBLIC + ACC_FINAL + ACC_SUPER, className, null, BMH, null);
 590             cw.visitSource(sourceFile, null);
 591             // emit static types and SPECIES_DATA fields
 592             FieldVisitor fw = cw.visitField(NOT_ACC_PUBLIC + ACC_STATIC, "SPECIES_DATA", SPECIES_DATA_SIG, null, null);
 593             fw.visitAnnotation(STABLE_SIG, true);
 594             fw.visitEnd();
 595             // emit bound argument fields
 596             for (int i = 0; i < types.length(); ++i) {
 597                 final char t = types.charAt(i);
 598                 final String fieldName = makeFieldName(types, i);
 599                 final String fieldDesc = t == 'L' ? JLO_SIG : String.valueOf(t);
 600                 cw.visitField(ACC_FINAL, fieldName, fieldDesc, null, null).visitEnd();
 601             }
 602             MethodVisitor mv;
 603             // emit constructor
 604             mv = cw.visitMethod(ACC_PRIVATE, "<init>", makeSignature(types, true), null, null);
 605             mv.visitCode();
 606             mv.visitVarInsn(ALOAD, 0); // this
 607             mv.visitVarInsn(ALOAD, 1); // type
 608             mv.visitVarInsn(ALOAD, 2); // form
 609             mv.visitMethodInsn(INVOKESPECIAL, BMH, "<init>", makeSignature("", true), false);
 610             for (int i = 0, j = 0; i < types.length(); ++i, ++j) {
 611                 // i counts the arguments, j counts corresponding argument slots
 612                 char t = types.charAt(i);
 613                 mv.visitVarInsn(ALOAD, 0);
 614                 mv.visitVarInsn(typeLoadOp(t), j + 3); // parameters start at 3
 615                 mv.visitFieldInsn(PUTFIELD, className, makeFieldName(types, i), typeSig(t));
 616                 if (t == 'J' || t == 'D') {
 617                     ++j; // adjust argument register access
 618                 }
 619             }
 620             mv.visitInsn(RETURN);
 621             mv.visitMaxs(0, 0);
 622             mv.visitEnd();
 623             // emit implementation of speciesData()
 624             mv = cw.visitMethod(NOT_ACC_PUBLIC + ACC_FINAL, "speciesData", MYSPECIES_DATA_SIG, null, null);
 625             mv.visitCode();
 626             mv.visitFieldInsn(GETSTATIC, className, "SPECIES_DATA", SPECIES_DATA_SIG);
 627             mv.visitInsn(ARETURN);
 628             mv.visitMaxs(0, 0);
 629             mv.visitEnd();
 630             // emit implementation of fieldCount()
 631             mv = cw.visitMethod(NOT_ACC_PUBLIC + ACC_FINAL, "fieldCount", INT_SIG, null, null);
 632             mv.visitCode();
 633             int fc = types.length();
 634             if (fc <= (ICONST_5 - ICONST_0)) {
 635                 mv.visitInsn(ICONST_0 + fc);
 636             } else {
 637                 mv.visitIntInsn(SIPUSH, fc);
 638             }
 639             mv.visitInsn(IRETURN);
 640             mv.visitMaxs(0, 0);
 641             mv.visitEnd();
 642             // emit make()  ...factory method wrapping constructor
 643             mv = cw.visitMethod(NOT_ACC_PUBLIC + ACC_STATIC, "make", makeSignature(types, false), null, null);
 644             mv.visitCode();
 645             // make instance
 646             mv.visitTypeInsn(NEW, className);
 647             mv.visitInsn(DUP);
 648             // load mt, lf
 649             mv.visitVarInsn(ALOAD, 0);  // type
 650             mv.visitVarInsn(ALOAD, 1);  // form
 651             // load factory method arguments
 652             for (int i = 0, j = 0; i < types.length(); ++i, ++j) {
 653                 // i counts the arguments, j counts corresponding argument slots
 654                 char t = types.charAt(i);
 655                 mv.visitVarInsn(typeLoadOp(t), j + 2); // parameters start at 3
 656                 if (t == 'J' || t == 'D') {
 657                     ++j; // adjust argument register access
 658                 }
 659             }
 660             // finally, invoke the constructor and return
 661             mv.visitMethodInsn(INVOKESPECIAL, className, "<init>", makeSignature(types, true), false);
 662             mv.visitInsn(ARETURN);
 663             mv.visitMaxs(0, 0);
 664             mv.visitEnd();
 665             // emit copyWith()
 666             mv = cw.visitMethod(NOT_ACC_PUBLIC + ACC_FINAL, "copyWith", makeSignature("", false), null, null);
 667             mv.visitCode();
 668             // make instance
 669             mv.visitTypeInsn(NEW, className);
 670             mv.visitInsn(DUP);
 671             // load mt, lf
 672             mv.visitVarInsn(ALOAD, 1);
 673             mv.visitVarInsn(ALOAD, 2);
 674             // put fields on the stack
 675             emitPushFields(types, className, mv);
 676             // finally, invoke the constructor and return
 677             mv.visitMethodInsn(INVOKESPECIAL, className, "<init>", makeSignature(types, true), false);
 678             mv.visitInsn(ARETURN);
 679             mv.visitMaxs(0, 0);
 680             mv.visitEnd();
 681             // for each type, emit copyWithExtendT()
 682             for (BasicType type : BasicType.ARG_TYPES) {
 683                 int ord = type.ordinal();
 684                 char btChar = type.basicTypeChar();
 685                 mv = cw.visitMethod(NOT_ACC_PUBLIC + ACC_FINAL, "copyWithExtend" + btChar, makeSignature(String.valueOf(btChar), false), null, E_THROWABLE);
 686                 mv.visitCode();
 687                 // return SPECIES_DATA.extendWith(t).constructor().invokeBasic(mt, lf, argL0, ..., narg)
 688                 // obtain constructor
 689                 mv.visitFieldInsn(GETSTATIC, className, "SPECIES_DATA", SPECIES_DATA_SIG);
 690                 int iconstInsn = ICONST_0 + ord;
 691                 assert(iconstInsn <= ICONST_5);
 692                 mv.visitInsn(iconstInsn);
 693                 mv.visitMethodInsn(INVOKEVIRTUAL, SPECIES_DATA, "extendWith", BMHSPECIES_DATA_EWI_SIG, false);
 694                 mv.visitMethodInsn(INVOKEVIRTUAL, SPECIES_DATA, "constructor", "()" + MH_SIG, false);
 695                 // load mt, lf
 696                 mv.visitVarInsn(ALOAD, 1);
 697                 mv.visitVarInsn(ALOAD, 2);
 698                 // put fields on the stack
 699                 emitPushFields(types, className, mv);
 700                 // put narg on stack
 701                 mv.visitVarInsn(typeLoadOp(btChar), 3);
 702                 // finally, invoke the constructor and return
 703                 mv.visitMethodInsn(INVOKEVIRTUAL, MH, "invokeBasic", makeSignature(types + btChar, false), false);
 704                 mv.visitInsn(ARETURN);
 705                 mv.visitMaxs(0, 0);
 706                 mv.visitEnd();
 707             }
 708             cw.visitEnd();
 709             return cw.toByteArray();
 710         }
 711 
 712         private static int typeLoadOp(char t) {
 713             switch (t) {
 714             case 'L': return ALOAD;
 715             case 'I': return ILOAD;
 716             case 'J': return LLOAD;
 717             case 'F': return FLOAD;
 718             case 'D': return DLOAD;
 719             default : throw newInternalError("unrecognized type " + t);
 720             }
 721         }
 722 
 723         private static void emitPushFields(String types, String className, MethodVisitor mv) {
 724             for (int i = 0; i < types.length(); ++i) {
 725                 char tc = types.charAt(i);
 726                 mv.visitVarInsn(ALOAD, 0);
 727                 mv.visitFieldInsn(GETFIELD, className, makeFieldName(types, i), typeSig(tc));
 728             }
 729         }
 730 
 731         static String typeSig(char t) {
 732             return t == 'L' ? JLO_SIG : String.valueOf(t);
 733         }
 734 
 735         //
 736         // Getter MH generation.
 737         //
 738 
 739         private static MethodHandle makeGetter(Class<?> cbmhClass, String types, int index) {
 740             String fieldName = makeFieldName(types, index);
 741             Class<?> fieldType = Wrapper.forBasicType(types.charAt(index)).primitiveType();
 742             try {
 743                 return LOOKUP.findGetter(cbmhClass, fieldName, fieldType);
 744             } catch (NoSuchFieldException | IllegalAccessException e) {
 745                 throw newInternalError(e);
 746             }
 747         }
 748 
 749         static MethodHandle[] makeGetters(Class<?> cbmhClass, String types, MethodHandle[] mhs) {
 750             if (mhs == null)  mhs = new MethodHandle[types.length()];
 751             for (int i = 0; i < mhs.length; ++i) {
 752                 mhs[i] = makeGetter(cbmhClass, types, i);
 753                 assert(mhs[i].internalMemberName().getDeclaringClass() == cbmhClass);
 754             }
 755             return mhs;
 756         }
 757 
 758         static MethodHandle[] makeCtors(Class<? extends BoundMethodHandle> cbmh, String types, MethodHandle mhs[]) {
 759             if (mhs == null)  mhs = new MethodHandle[1];
 760             if (types.equals(""))  return mhs;  // hack for empty BMH species
 761             mhs[0] = makeCbmhCtor(cbmh, types);
 762             return mhs;
 763         }
 764 
 765         static NamedFunction[] makeNominalGetters(String types, NamedFunction[] nfs, MethodHandle[] getters) {
 766             if (nfs == null)  nfs = new NamedFunction[types.length()];
 767             for (int i = 0; i < nfs.length; ++i) {
 768                 nfs[i] = new NamedFunction(getters[i]);
 769             }
 770             return nfs;
 771         }
 772 
 773         //
 774         // Auxiliary methods.
 775         //
 776 
 777         static SpeciesData getSpeciesDataFromConcreteBMHClass(Class<? extends BoundMethodHandle> cbmh) {
 778             try {
 779                 Field F_SPECIES_DATA = cbmh.getDeclaredField("SPECIES_DATA");
 780                 return (SpeciesData) F_SPECIES_DATA.get(null);
 781             } catch (ReflectiveOperationException ex) {
 782                 throw newInternalError(ex);
 783             }
 784         }
 785 
 786         static void setSpeciesDataToConcreteBMHClass(Class<? extends BoundMethodHandle> cbmh, SpeciesData speciesData) {
 787             try {
 788                 Field F_SPECIES_DATA = cbmh.getDeclaredField("SPECIES_DATA");
 789                 // ## FIXME: annotation parser can't create proxy classes until module system is fully initialzed
 790                 // assert F_SPECIES_DATA.getDeclaredAnnotation(Stable.class) != null;
 791                 F_SPECIES_DATA.set(null, speciesData);
 792             } catch (ReflectiveOperationException ex) {
 793                 throw newInternalError(ex);
 794             }
 795         }
 796 
 797         /**
 798          * Field names in concrete BMHs adhere to this pattern:
 799          * arg + type + index
 800          * where type is a single character (L, I, J, F, D).
 801          */
 802         private static String makeFieldName(String types, int index) {
 803             assert index >= 0 && index < types.length();
 804             return "arg" + types.charAt(index) + index;
 805         }
 806 
 807         private static String makeSignature(String types, boolean ctor) {
 808             StringBuilder buf = new StringBuilder(SIG_INCIPIT);
 809             for (char c : types.toCharArray()) {
 810                 buf.append(typeSig(c));
 811             }
 812             return buf.append(')').append(ctor ? "V" : BMH_SIG).toString();
 813         }
 814 
 815         static MethodHandle makeCbmhCtor(Class<? extends BoundMethodHandle> cbmh, String types) {
 816             try {
 817                 return LOOKUP.findStatic(cbmh, "make", MethodType.fromDescriptor(makeSignature(types, false), null));
 818             } catch (NoSuchMethodException | IllegalAccessException | IllegalArgumentException | TypeNotPresentException e) {
 819                 throw newInternalError(e);
 820             }
 821         }
 822     }
 823 
 824     private static final Lookup LOOKUP = Lookup.IMPL_LOOKUP;
 825 
 826     /**
 827      * All subclasses must provide such a value describing their type signature.
 828      */
 829     static final SpeciesData SPECIES_DATA = SpeciesData.EMPTY;
 830 
 831     private static final SpeciesData[] SPECIES_DATA_CACHE = new SpeciesData[5];
 832     private static SpeciesData checkCache(int size, String types) {
 833         int idx = size - 1;
 834         SpeciesData data = SPECIES_DATA_CACHE[idx];
 835         if (data != null)  return data;
 836         SPECIES_DATA_CACHE[idx] = data = getSpeciesData(types);
 837         return data;
 838     }
 839     static SpeciesData speciesData_L()     { return checkCache(1, "L"); }
 840     static SpeciesData speciesData_LL()    { return checkCache(2, "LL"); }
 841     static SpeciesData speciesData_LLL()   { return checkCache(3, "LLL"); }
 842     static SpeciesData speciesData_LLLL()  { return checkCache(4, "LLLL"); }
 843     static SpeciesData speciesData_LLLLL() { return checkCache(5, "LLLLL"); }
 844 }