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.Map;
  41 import java.util.concurrent.ConcurrentHashMap;
  42 import java.util.concurrent.ConcurrentMap;
  43 import java.util.function.Function;
  44 
  45 import static java.lang.invoke.LambdaForm.BasicType;
  46 import static java.lang.invoke.LambdaForm.BasicType.*;
  47 import static java.lang.invoke.MethodHandleStatics.*;
  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         static final String SPECIES_CLASS_PREFIX = SPECIES_PREFIX_PATH.replace('/', '.');
 469 
 470         static final String BMHSPECIES_DATA_EWI_SIG = "(B)" + SPECIES_DATA_SIG;
 471         static final String BMHSPECIES_DATA_GFC_SIG = "(" + JLS_SIG + JLC_SIG + ")" + SPECIES_DATA_SIG;
 472         static final String MYSPECIES_DATA_SIG = "()" + SPECIES_DATA_SIG;
 473         static final String VOID_SIG   = "()V";
 474         static final String INT_SIG    = "()I";
 475 
 476         static final String SIG_INCIPIT = "(Ljava/lang/invoke/MethodType;Ljava/lang/invoke/LambdaForm;";
 477 
 478         static final String[] E_THROWABLE = new String[] { "java/lang/Throwable" };
 479 
 480         static final ConcurrentMap<String, Class<? extends BoundMethodHandle>> CLASS_CACHE = new ConcurrentHashMap<>();
 481 
 482         /**
 483          * Get a concrete subclass of BMH for a given combination of bound types.
 484          *
 485          * @param types the type signature, wherein reference types are erased to 'L'
 486          * @return the concrete BMH class
 487          */
 488         static Class<? extends BoundMethodHandle> getConcreteBMHClass(String types) {
 489             // CHM.computeIfAbsent ensures generateConcreteBMHClass is called
 490             // only once per key.
 491             return CLASS_CACHE.computeIfAbsent(
 492                 types, new Function<String, Class<? extends BoundMethodHandle>>() {
 493                     @Override
 494                     public Class<? extends BoundMethodHandle> apply(String types) {
 495                         String shortTypes = LambdaForm.shortenSignature(types);
 496                         String className = SPECIES_CLASS_PREFIX + shortTypes;
 497                         Class<?> c = BootLoader.loadClassOrNull(className);
 498                         if (c != null) {
 499                             return c.asSubclass(BoundMethodHandle.class);
 500                         } else {
 501                             // Not pregenerated, generate the class
 502                             return generateConcreteBMHClass(shortTypes, types);
 503                         }
 504                     }
 505                 });
 506         }
 507 
 508         /**
 509          * Generate a concrete subclass of BMH for a given combination of bound types.
 510          *
 511          * A concrete BMH species adheres to the following schema:
 512          *
 513          * <pre>
 514          * class Species_[[types]] extends BoundMethodHandle {
 515          *     [[fields]]
 516          *     final SpeciesData speciesData() { return SpeciesData.get("[[types]]"); }
 517          * }
 518          * </pre>
 519          *
 520          * The {@code [[types]]} signature is precisely the string that is passed to this
 521          * method.
 522          *
 523          * The {@code [[fields]]} section consists of one field definition per character in
 524          * the type signature, adhering to the naming schema described in the definition of
 525          * {@link #makeFieldName}.
 526          *
 527          * For example, a concrete BMH species for two reference and one integral bound values
 528          * would have the following shape:
 529          *
 530          * <pre>
 531          * class BoundMethodHandle { ... private static
 532          * final class Species_LLI extends BoundMethodHandle {
 533          *     final Object argL0;
 534          *     final Object argL1;
 535          *     final int argI2;
 536          *     private Species_LLI(MethodType mt, LambdaForm lf, Object argL0, Object argL1, int argI2) {
 537          *         super(mt, lf);
 538          *         this.argL0 = argL0;
 539          *         this.argL1 = argL1;
 540          *         this.argI2 = argI2;
 541          *     }
 542          *     final SpeciesData speciesData() { return SPECIES_DATA; }
 543          *     final int fieldCount() { return 3; }
 544          *     @Stable static SpeciesData SPECIES_DATA; // injected afterwards
 545          *     static BoundMethodHandle make(MethodType mt, LambdaForm lf, Object argL0, Object argL1, int argI2) {
 546          *         return new Species_LLI(mt, lf, argL0, argL1, argI2);
 547          *     }
 548          *     final BoundMethodHandle copyWith(MethodType mt, LambdaForm lf) {
 549          *         return new Species_LLI(mt, lf, argL0, argL1, argI2);
 550          *     }
 551          *     final BoundMethodHandle copyWithExtendL(MethodType mt, LambdaForm lf, Object narg) {
 552          *         return SPECIES_DATA.extendWith(L_TYPE).constructor().invokeBasic(mt, lf, argL0, argL1, argI2, narg);
 553          *     }
 554          *     final BoundMethodHandle copyWithExtendI(MethodType mt, LambdaForm lf, int narg) {
 555          *         return SPECIES_DATA.extendWith(I_TYPE).constructor().invokeBasic(mt, lf, argL0, argL1, argI2, narg);
 556          *     }
 557          *     final BoundMethodHandle copyWithExtendJ(MethodType mt, LambdaForm lf, long narg) {
 558          *         return SPECIES_DATA.extendWith(J_TYPE).constructor().invokeBasic(mt, lf, argL0, argL1, argI2, narg);
 559          *     }
 560          *     final BoundMethodHandle copyWithExtendF(MethodType mt, LambdaForm lf, float narg) {
 561          *         return SPECIES_DATA.extendWith(F_TYPE).constructor().invokeBasic(mt, lf, argL0, argL1, argI2, narg);
 562          *     }
 563          *     public final BoundMethodHandle copyWithExtendD(MethodType mt, LambdaForm lf, double narg) {
 564          *         return SPECIES_DATA.extendWith(D_TYPE).constructor().invokeBasic(mt, lf, argL0, argL1, argI2, narg);
 565          *     }
 566          * }
 567          * </pre>
 568          *
 569          * @param types the type signature, wherein reference types are erased to 'L'
 570          * @return the generated concrete BMH class
 571          */
 572         static Class<? extends BoundMethodHandle> generateConcreteBMHClass(String shortTypes,
 573                 String types) {
 574             final String className  = speciesInternalClassName(shortTypes);
 575             byte[] classFile = generateConcreteBMHClassBytes(shortTypes, types, className);
 576 
 577             // load class
 578             InvokerBytecodeGenerator.maybeDump(className, classFile);
 579             Class<? extends BoundMethodHandle> bmhClass =
 580                 UNSAFE.defineClass(className, classFile, 0, classFile.length,
 581                                    BoundMethodHandle.class.getClassLoader(), null)
 582                     .asSubclass(BoundMethodHandle.class);
 583 
 584             return bmhClass;
 585         }
 586 
 587         /**
 588          * @implNote this method is used by GenerateBMHClassesPlugin to enable
 589          * ahead-of-time generation of BMH classes at link time. It does
 590          * added validation since this string may be user provided.
 591          */
 592         static Map.Entry<String, byte[]> generateConcreteBMHClassBytes(
 593                 final String types) {
 594             for (char c : types.toCharArray()) {
 595                 if ("LIJFD".indexOf(c) < 0) {
 596                     throw new IllegalArgumentException("All characters must "
 597                             + "correspond to a basic field type: LIJFD");
 598                 }
 599             }
 600             String shortTypes = LambdaForm.shortenSignature(types);
 601             final String className  = speciesInternalClassName(shortTypes);
 602             return Map.entry(className,
 603                     generateConcreteBMHClassBytes(shortTypes, types, className));
 604         }
 605 
 606         private static String speciesInternalClassName(String shortTypes) {
 607             return SPECIES_PREFIX_PATH + shortTypes;
 608         }
 609 
 610         static byte[] generateConcreteBMHClassBytes(final String shortTypes,
 611                 final String types, final String className) {
 612             final String sourceFile = SPECIES_PREFIX_NAME + shortTypes;
 613 
 614             final ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS + ClassWriter.COMPUTE_FRAMES);
 615             final int NOT_ACC_PUBLIC = 0;  // not ACC_PUBLIC
 616             cw.visit(V1_6, NOT_ACC_PUBLIC + ACC_FINAL + ACC_SUPER, className, null, BMH, null);
 617             cw.visitSource(sourceFile, null);
 618 
 619             // emit static types and SPECIES_DATA fields
 620             FieldVisitor fw = cw.visitField(NOT_ACC_PUBLIC + ACC_STATIC, "SPECIES_DATA", SPECIES_DATA_SIG, null, null);
 621             fw.visitAnnotation(STABLE_SIG, true);
 622             fw.visitEnd();
 623 
 624             // emit bound argument fields
 625             for (int i = 0; i < types.length(); ++i) {
 626                 final char t = types.charAt(i);
 627                 final String fieldName = makeFieldName(types, i);
 628                 final String fieldDesc = t == 'L' ? JLO_SIG : String.valueOf(t);
 629                 cw.visitField(ACC_FINAL, fieldName, fieldDesc, null, null).visitEnd();
 630             }
 631 
 632             MethodVisitor mv;
 633 
 634             // emit constructor
 635             mv = cw.visitMethod(ACC_PRIVATE, "<init>", makeSignature(types, true), null, null);
 636             mv.visitCode();
 637             mv.visitVarInsn(ALOAD, 0); // this
 638             mv.visitVarInsn(ALOAD, 1); // type
 639             mv.visitVarInsn(ALOAD, 2); // form
 640 
 641             mv.visitMethodInsn(INVOKESPECIAL, BMH, "<init>", makeSignature("", true), false);
 642 
 643             for (int i = 0, j = 0; i < types.length(); ++i, ++j) {
 644                 // i counts the arguments, j counts corresponding argument slots
 645                 char t = types.charAt(i);
 646                 mv.visitVarInsn(ALOAD, 0);
 647                 mv.visitVarInsn(typeLoadOp(t), j + 3); // parameters start at 3
 648                 mv.visitFieldInsn(PUTFIELD, className, makeFieldName(types, i), typeSig(t));
 649                 if (t == 'J' || t == 'D') {
 650                     ++j; // adjust argument register access
 651                 }
 652             }
 653 
 654             mv.visitInsn(RETURN);
 655             mv.visitMaxs(0, 0);
 656             mv.visitEnd();
 657 
 658             // emit implementation of speciesData()
 659             mv = cw.visitMethod(NOT_ACC_PUBLIC + ACC_FINAL, "speciesData", MYSPECIES_DATA_SIG, null, null);
 660             mv.visitCode();
 661             mv.visitFieldInsn(GETSTATIC, className, "SPECIES_DATA", SPECIES_DATA_SIG);
 662             mv.visitInsn(ARETURN);
 663             mv.visitMaxs(0, 0);
 664             mv.visitEnd();
 665 
 666             // emit implementation of fieldCount()
 667             mv = cw.visitMethod(NOT_ACC_PUBLIC + ACC_FINAL, "fieldCount", INT_SIG, null, null);
 668             mv.visitCode();
 669             int fc = types.length();
 670             if (fc <= (ICONST_5 - ICONST_0)) {
 671                 mv.visitInsn(ICONST_0 + fc);
 672             } else {
 673                 mv.visitIntInsn(SIPUSH, fc);
 674             }
 675             mv.visitInsn(IRETURN);
 676             mv.visitMaxs(0, 0);
 677             mv.visitEnd();
 678             // emit make()  ...factory method wrapping constructor
 679             mv = cw.visitMethod(NOT_ACC_PUBLIC + ACC_STATIC, "make", makeSignature(types, false), null, null);
 680             mv.visitCode();
 681             // make instance
 682             mv.visitTypeInsn(NEW, className);
 683             mv.visitInsn(DUP);
 684             // load mt, lf
 685             mv.visitVarInsn(ALOAD, 0);  // type
 686             mv.visitVarInsn(ALOAD, 1);  // form
 687             // load factory method arguments
 688             for (int i = 0, j = 0; i < types.length(); ++i, ++j) {
 689                 // i counts the arguments, j counts corresponding argument slots
 690                 char t = types.charAt(i);
 691                 mv.visitVarInsn(typeLoadOp(t), j + 2); // parameters start at 3
 692                 if (t == 'J' || t == 'D') {
 693                     ++j; // adjust argument register access
 694                 }
 695             }
 696 
 697             // finally, invoke the constructor and return
 698             mv.visitMethodInsn(INVOKESPECIAL, className, "<init>", makeSignature(types, true), false);
 699             mv.visitInsn(ARETURN);
 700             mv.visitMaxs(0, 0);
 701             mv.visitEnd();
 702 
 703             // emit copyWith()
 704             mv = cw.visitMethod(NOT_ACC_PUBLIC + ACC_FINAL, "copyWith", makeSignature("", false), null, null);
 705             mv.visitCode();
 706             // make instance
 707             mv.visitTypeInsn(NEW, className);
 708             mv.visitInsn(DUP);
 709             // load mt, lf
 710             mv.visitVarInsn(ALOAD, 1);
 711             mv.visitVarInsn(ALOAD, 2);
 712             // put fields on the stack
 713             emitPushFields(types, className, mv);
 714             // finally, invoke the constructor and return
 715             mv.visitMethodInsn(INVOKESPECIAL, className, "<init>", makeSignature(types, true), false);
 716             mv.visitInsn(ARETURN);
 717             mv.visitMaxs(0, 0);
 718             mv.visitEnd();
 719 
 720             // for each type, emit copyWithExtendT()
 721             for (BasicType type : BasicType.ARG_TYPES) {
 722                 int ord = type.ordinal();
 723                 char btChar = type.basicTypeChar();
 724                 mv = cw.visitMethod(NOT_ACC_PUBLIC + ACC_FINAL, "copyWithExtend" + btChar, makeSignature(String.valueOf(btChar), false), null, E_THROWABLE);
 725                 mv.visitCode();
 726                 // return SPECIES_DATA.extendWith(t).constructor().invokeBasic(mt, lf, argL0, ..., narg)
 727                 // obtain constructor
 728                 mv.visitFieldInsn(GETSTATIC, className, "SPECIES_DATA", SPECIES_DATA_SIG);
 729                 int iconstInsn = ICONST_0 + ord;
 730                 assert(iconstInsn <= ICONST_5);
 731                 mv.visitInsn(iconstInsn);
 732                 mv.visitMethodInsn(INVOKEVIRTUAL, SPECIES_DATA, "extendWith", BMHSPECIES_DATA_EWI_SIG, false);
 733                 mv.visitMethodInsn(INVOKEVIRTUAL, SPECIES_DATA, "constructor", "()" + MH_SIG, false);
 734                 // load mt, lf
 735                 mv.visitVarInsn(ALOAD, 1);
 736                 mv.visitVarInsn(ALOAD, 2);
 737                 // put fields on the stack
 738                 emitPushFields(types, className, mv);
 739                 // put narg on stack
 740                 mv.visitVarInsn(typeLoadOp(btChar), 3);
 741                 // finally, invoke the constructor and return
 742                 mv.visitMethodInsn(INVOKEVIRTUAL, MH, "invokeBasic", makeSignature(types + btChar, false), false);
 743                 mv.visitInsn(ARETURN);
 744                 mv.visitMaxs(0, 0);
 745                 mv.visitEnd();
 746             }
 747 
 748             cw.visitEnd();
 749 
 750             return cw.toByteArray();
 751         }
 752 
 753         private static int typeLoadOp(char t) {
 754             switch (t) {
 755             case 'L': return ALOAD;
 756             case 'I': return ILOAD;
 757             case 'J': return LLOAD;
 758             case 'F': return FLOAD;
 759             case 'D': return DLOAD;
 760             default : throw newInternalError("unrecognized type " + t);
 761             }
 762         }
 763 
 764         private static void emitPushFields(String types, String className, MethodVisitor mv) {
 765             for (int i = 0; i < types.length(); ++i) {
 766                 char tc = types.charAt(i);
 767                 mv.visitVarInsn(ALOAD, 0);
 768                 mv.visitFieldInsn(GETFIELD, className, makeFieldName(types, i), typeSig(tc));
 769             }
 770         }
 771 
 772         static String typeSig(char t) {
 773             return t == 'L' ? JLO_SIG : String.valueOf(t);
 774         }
 775 
 776         //
 777         // Getter MH generation.
 778         //
 779 
 780         private static MethodHandle makeGetter(Class<?> cbmhClass, String types, int index) {
 781             String fieldName = makeFieldName(types, index);
 782             Class<?> fieldType = Wrapper.forBasicType(types.charAt(index)).primitiveType();
 783             try {
 784                 return LOOKUP.findGetter(cbmhClass, fieldName, fieldType);
 785             } catch (NoSuchFieldException | IllegalAccessException e) {
 786                 throw newInternalError(e);
 787             }
 788         }
 789 
 790         static MethodHandle[] makeGetters(Class<?> cbmhClass, String types, MethodHandle[] mhs) {
 791             if (mhs == null)  mhs = new MethodHandle[types.length()];
 792             for (int i = 0; i < mhs.length; ++i) {
 793                 mhs[i] = makeGetter(cbmhClass, types, i);
 794                 assert(mhs[i].internalMemberName().getDeclaringClass() == cbmhClass);
 795             }
 796             return mhs;
 797         }
 798 
 799         static MethodHandle[] makeCtors(Class<? extends BoundMethodHandle> cbmh, String types, MethodHandle mhs[]) {
 800             if (mhs == null)  mhs = new MethodHandle[1];
 801             if (types.equals(""))  return mhs;  // hack for empty BMH species
 802             mhs[0] = makeCbmhCtor(cbmh, types);
 803             return mhs;
 804         }
 805 
 806         static NamedFunction[] makeNominalGetters(String types, NamedFunction[] nfs, MethodHandle[] getters) {
 807             if (nfs == null)  nfs = new NamedFunction[types.length()];
 808             for (int i = 0; i < nfs.length; ++i) {
 809                 nfs[i] = new NamedFunction(getters[i]);
 810             }
 811             return nfs;
 812         }
 813 
 814         //
 815         // Auxiliary methods.
 816         //
 817 
 818         static SpeciesData getSpeciesDataFromConcreteBMHClass(Class<? extends BoundMethodHandle> cbmh) {
 819             try {
 820                 Field F_SPECIES_DATA = cbmh.getDeclaredField("SPECIES_DATA");
 821                 return (SpeciesData) F_SPECIES_DATA.get(null);
 822             } catch (ReflectiveOperationException ex) {
 823                 throw newInternalError(ex);
 824             }
 825         }
 826 
 827         static void setSpeciesDataToConcreteBMHClass(Class<? extends BoundMethodHandle> cbmh, SpeciesData speciesData) {
 828             try {
 829                 Field F_SPECIES_DATA = cbmh.getDeclaredField("SPECIES_DATA");
 830                 // ## FIXME: annotation parser can't create proxy classes until module system is fully initialzed
 831                 // assert F_SPECIES_DATA.getDeclaredAnnotation(Stable.class) != null;
 832                 F_SPECIES_DATA.set(null, speciesData);
 833             } catch (ReflectiveOperationException ex) {
 834                 throw newInternalError(ex);
 835             }
 836         }
 837 
 838         /**
 839          * Field names in concrete BMHs adhere to this pattern:
 840          * arg + type + index
 841          * where type is a single character (L, I, J, F, D).
 842          */
 843         private static String makeFieldName(String types, int index) {
 844             assert index >= 0 && index < types.length();
 845             return "arg" + types.charAt(index) + index;
 846         }
 847 
 848         private static String makeSignature(String types, boolean ctor) {
 849             StringBuilder buf = new StringBuilder(SIG_INCIPIT);
 850             for (char c : types.toCharArray()) {
 851                 buf.append(typeSig(c));
 852             }
 853             return buf.append(')').append(ctor ? "V" : BMH_SIG).toString();
 854         }
 855 
 856         static MethodHandle makeCbmhCtor(Class<? extends BoundMethodHandle> cbmh, String types) {
 857             try {
 858                 return LOOKUP.findStatic(cbmh, "make", MethodType.fromDescriptor(makeSignature(types, false), null));
 859             } catch (NoSuchMethodException | IllegalAccessException | IllegalArgumentException | TypeNotPresentException e) {
 860                 throw newInternalError(e);
 861             }
 862         }
 863     }
 864 
 865     private static final Lookup LOOKUP = Lookup.IMPL_LOOKUP;
 866 
 867     /**
 868      * All subclasses must provide such a value describing their type signature.
 869      */
 870     static final SpeciesData SPECIES_DATA = SpeciesData.EMPTY;
 871 
 872     private static final SpeciesData[] SPECIES_DATA_CACHE = new SpeciesData[5];
 873     private static SpeciesData checkCache(int size, String types) {
 874         int idx = size - 1;
 875         SpeciesData data = SPECIES_DATA_CACHE[idx];
 876         if (data != null)  return data;
 877         SPECIES_DATA_CACHE[idx] = data = getSpeciesData(types);
 878         return data;
 879     }
 880     static SpeciesData speciesData_L()     { return checkCache(1, "L"); }
 881     static SpeciesData speciesData_LL()    { return checkCache(2, "LL"); }
 882     static SpeciesData speciesData_LLL()   { return checkCache(3, "LLL"); }
 883     static SpeciesData speciesData_LLLL()  { return checkCache(4, "LLLL"); }
 884     static SpeciesData speciesData_LLLLL() { return checkCache(5, "LLLLL"); }
 885 }