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