rt/emul/compact/src/main/java/java/lang/invoke/BoundMethodHandle.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Sat, 09 Aug 2014 11:11:13 +0200
branchjdk8-b132
changeset 1646 c880a8a8803b
child 1653 bd151459ee4f
permissions -rw-r--r--
Batch of classes necessary to implement invoke dynamic interfaces. Taken from JDK8 build 132
jaroslav@1646
     1
/*
jaroslav@1646
     2
 * Copyright (c) 2008, 2013, Oracle and/or its affiliates. All rights reserved.
jaroslav@1646
     3
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
jaroslav@1646
     4
 *
jaroslav@1646
     5
 * This code is free software; you can redistribute it and/or modify it
jaroslav@1646
     6
 * under the terms of the GNU General Public License version 2 only, as
jaroslav@1646
     7
 * published by the Free Software Foundation.  Oracle designates this
jaroslav@1646
     8
 * particular file as subject to the "Classpath" exception as provided
jaroslav@1646
     9
 * by Oracle in the LICENSE file that accompanied this code.
jaroslav@1646
    10
 *
jaroslav@1646
    11
 * This code is distributed in the hope that it will be useful, but WITHOUT
jaroslav@1646
    12
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
jaroslav@1646
    13
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
jaroslav@1646
    14
 * version 2 for more details (a copy is included in the LICENSE file that
jaroslav@1646
    15
 * accompanied this code).
jaroslav@1646
    16
 *
jaroslav@1646
    17
 * You should have received a copy of the GNU General Public License version
jaroslav@1646
    18
 * 2 along with this work; if not, write to the Free Software Foundation,
jaroslav@1646
    19
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
jaroslav@1646
    20
 *
jaroslav@1646
    21
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
jaroslav@1646
    22
 * or visit www.oracle.com if you need additional information or have any
jaroslav@1646
    23
 * questions.
jaroslav@1646
    24
 */
jaroslav@1646
    25
jaroslav@1646
    26
package java.lang.invoke;
jaroslav@1646
    27
jaroslav@1646
    28
import static jdk.internal.org.objectweb.asm.Opcodes.*;
jaroslav@1646
    29
import static java.lang.invoke.LambdaForm.basicTypes;
jaroslav@1646
    30
import static java.lang.invoke.MethodHandleNatives.Constants.REF_invokeStatic;
jaroslav@1646
    31
import static java.lang.invoke.MethodHandleStatics.*;
jaroslav@1646
    32
jaroslav@1646
    33
import java.lang.invoke.LambdaForm.Name;
jaroslav@1646
    34
import java.lang.invoke.LambdaForm.NamedFunction;
jaroslav@1646
    35
import java.lang.invoke.MethodHandles.Lookup;
jaroslav@1646
    36
import java.lang.reflect.Field;
jaroslav@1646
    37
import java.util.Arrays;
jaroslav@1646
    38
import java.util.HashMap;
jaroslav@1646
    39
jaroslav@1646
    40
import sun.invoke.util.ValueConversions;
jaroslav@1646
    41
import sun.invoke.util.Wrapper;
jaroslav@1646
    42
jaroslav@1646
    43
import jdk.internal.org.objectweb.asm.ClassWriter;
jaroslav@1646
    44
import jdk.internal.org.objectweb.asm.MethodVisitor;
jaroslav@1646
    45
import jdk.internal.org.objectweb.asm.Type;
jaroslav@1646
    46
jaroslav@1646
    47
/**
jaroslav@1646
    48
 * The flavor of method handle which emulates an invoke instruction
jaroslav@1646
    49
 * on a predetermined argument.  The JVM dispatches to the correct method
jaroslav@1646
    50
 * when the handle is created, not when it is invoked.
jaroslav@1646
    51
 *
jaroslav@1646
    52
 * All bound arguments are encapsulated in dedicated species.
jaroslav@1646
    53
 */
jaroslav@1646
    54
/* non-public */ abstract class BoundMethodHandle extends MethodHandle {
jaroslav@1646
    55
jaroslav@1646
    56
    /* non-public */ BoundMethodHandle(MethodType type, LambdaForm form) {
jaroslav@1646
    57
        super(type, form);
jaroslav@1646
    58
    }
jaroslav@1646
    59
jaroslav@1646
    60
    //
jaroslav@1646
    61
    // BMH API and internals
jaroslav@1646
    62
    //
jaroslav@1646
    63
jaroslav@1646
    64
    static MethodHandle bindSingle(MethodType type, LambdaForm form, char xtype, Object x) {
jaroslav@1646
    65
        // for some type signatures, there exist pre-defined concrete BMH classes
jaroslav@1646
    66
        try {
jaroslav@1646
    67
            switch (xtype) {
jaroslav@1646
    68
            case 'L':
jaroslav@1646
    69
                if (true)  return bindSingle(type, form, x);  // Use known fast path.
jaroslav@1646
    70
                return (BoundMethodHandle) SpeciesData.EMPTY.extendWithType('L').constructor[0].invokeBasic(type, form, x);
jaroslav@1646
    71
            case 'I':
jaroslav@1646
    72
                return (BoundMethodHandle) SpeciesData.EMPTY.extendWithType('I').constructor[0].invokeBasic(type, form, ValueConversions.widenSubword(x));
jaroslav@1646
    73
            case 'J':
jaroslav@1646
    74
                return (BoundMethodHandle) SpeciesData.EMPTY.extendWithType('J').constructor[0].invokeBasic(type, form, (long) x);
jaroslav@1646
    75
            case 'F':
jaroslav@1646
    76
                return (BoundMethodHandle) SpeciesData.EMPTY.extendWithType('F').constructor[0].invokeBasic(type, form, (float) x);
jaroslav@1646
    77
            case 'D':
jaroslav@1646
    78
                return (BoundMethodHandle) SpeciesData.EMPTY.extendWithType('D').constructor[0].invokeBasic(type, form, (double) x);
jaroslav@1646
    79
            default : throw new InternalError("unexpected xtype: " + xtype);
jaroslav@1646
    80
            }
jaroslav@1646
    81
        } catch (Throwable t) {
jaroslav@1646
    82
            throw newInternalError(t);
jaroslav@1646
    83
        }
jaroslav@1646
    84
    }
jaroslav@1646
    85
jaroslav@1646
    86
    static MethodHandle bindSingle(MethodType type, LambdaForm form, Object x) {
jaroslav@1646
    87
            return new Species_L(type, form, x);
jaroslav@1646
    88
    }
jaroslav@1646
    89
jaroslav@1646
    90
    MethodHandle cloneExtend(MethodType type, LambdaForm form, char xtype, Object x) {
jaroslav@1646
    91
        try {
jaroslav@1646
    92
            switch (xtype) {
jaroslav@1646
    93
            case 'L': return cloneExtendL(type, form, x);
jaroslav@1646
    94
            case 'I': return cloneExtendI(type, form, ValueConversions.widenSubword(x));
jaroslav@1646
    95
            case 'J': return cloneExtendJ(type, form, (long) x);
jaroslav@1646
    96
            case 'F': return cloneExtendF(type, form, (float) x);
jaroslav@1646
    97
            case 'D': return cloneExtendD(type, form, (double) x);
jaroslav@1646
    98
            }
jaroslav@1646
    99
        } catch (Throwable t) {
jaroslav@1646
   100
            throw newInternalError(t);
jaroslav@1646
   101
        }
jaroslav@1646
   102
        throw new InternalError("unexpected type: " + xtype);
jaroslav@1646
   103
    }
jaroslav@1646
   104
jaroslav@1646
   105
    @Override
jaroslav@1646
   106
    MethodHandle bindArgument(int pos, char basicType, Object value) {
jaroslav@1646
   107
        MethodType type = type().dropParameterTypes(pos, pos+1);
jaroslav@1646
   108
        LambdaForm form = internalForm().bind(1+pos, speciesData());
jaroslav@1646
   109
        return cloneExtend(type, form, basicType, value);
jaroslav@1646
   110
    }
jaroslav@1646
   111
jaroslav@1646
   112
    @Override
jaroslav@1646
   113
    MethodHandle dropArguments(MethodType srcType, int pos, int drops) {
jaroslav@1646
   114
        LambdaForm form = internalForm().addArguments(pos, srcType.parameterList().subList(pos, pos+drops));
jaroslav@1646
   115
        try {
jaroslav@1646
   116
             return clone(srcType, form);
jaroslav@1646
   117
         } catch (Throwable t) {
jaroslav@1646
   118
             throw newInternalError(t);
jaroslav@1646
   119
         }
jaroslav@1646
   120
    }
jaroslav@1646
   121
jaroslav@1646
   122
    @Override
jaroslav@1646
   123
    MethodHandle permuteArguments(MethodType newType, int[] reorder) {
jaroslav@1646
   124
        try {
jaroslav@1646
   125
             return clone(newType, form.permuteArguments(1, reorder, basicTypes(newType.parameterList())));
jaroslav@1646
   126
         } catch (Throwable t) {
jaroslav@1646
   127
             throw newInternalError(t);
jaroslav@1646
   128
         }
jaroslav@1646
   129
    }
jaroslav@1646
   130
jaroslav@1646
   131
    static final String EXTENSION_TYPES = "LIJFD";
jaroslav@1646
   132
    static final byte INDEX_L = 0, INDEX_I = 1, INDEX_J = 2, INDEX_F = 3, INDEX_D = 4;
jaroslav@1646
   133
    static byte extensionIndex(char type) {
jaroslav@1646
   134
        int i = EXTENSION_TYPES.indexOf(type);
jaroslav@1646
   135
        if (i < 0)  throw new InternalError();
jaroslav@1646
   136
        return (byte) i;
jaroslav@1646
   137
    }
jaroslav@1646
   138
jaroslav@1646
   139
    /**
jaroslav@1646
   140
     * Return the {@link SpeciesData} instance representing this BMH species. All subclasses must provide a
jaroslav@1646
   141
     * static field containing this value, and they must accordingly implement this method.
jaroslav@1646
   142
     */
jaroslav@1646
   143
    protected abstract SpeciesData speciesData();
jaroslav@1646
   144
jaroslav@1646
   145
    @Override
jaroslav@1646
   146
    final Object internalProperties() {
jaroslav@1646
   147
        return "/BMH="+internalValues();
jaroslav@1646
   148
    }
jaroslav@1646
   149
jaroslav@1646
   150
    @Override
jaroslav@1646
   151
    final Object internalValues() {
jaroslav@1646
   152
        Object[] boundValues = new Object[speciesData().fieldCount()];
jaroslav@1646
   153
        for (int i = 0; i < boundValues.length; ++i) {
jaroslav@1646
   154
            boundValues[i] = arg(i);
jaroslav@1646
   155
        }
jaroslav@1646
   156
        return Arrays.asList(boundValues);
jaroslav@1646
   157
    }
jaroslav@1646
   158
jaroslav@1646
   159
    public final Object arg(int i) {
jaroslav@1646
   160
        try {
jaroslav@1646
   161
            switch (speciesData().fieldType(i)) {
jaroslav@1646
   162
            case 'L': return argL(i);
jaroslav@1646
   163
            case 'I': return argI(i);
jaroslav@1646
   164
            case 'F': return argF(i);
jaroslav@1646
   165
            case 'D': return argD(i);
jaroslav@1646
   166
            case 'J': return argJ(i);
jaroslav@1646
   167
            }
jaroslav@1646
   168
        } catch (Throwable ex) {
jaroslav@1646
   169
            throw newInternalError(ex);
jaroslav@1646
   170
        }
jaroslav@1646
   171
        throw new InternalError("unexpected type: " + speciesData().types+"."+i);
jaroslav@1646
   172
    }
jaroslav@1646
   173
    public final Object argL(int i) throws Throwable { return          speciesData().getters[i].invokeBasic(this); }
jaroslav@1646
   174
    public final int    argI(int i) throws Throwable { return (int)    speciesData().getters[i].invokeBasic(this); }
jaroslav@1646
   175
    public final float  argF(int i) throws Throwable { return (float)  speciesData().getters[i].invokeBasic(this); }
jaroslav@1646
   176
    public final double argD(int i) throws Throwable { return (double) speciesData().getters[i].invokeBasic(this); }
jaroslav@1646
   177
    public final long   argJ(int i) throws Throwable { return (long)   speciesData().getters[i].invokeBasic(this); }
jaroslav@1646
   178
jaroslav@1646
   179
    //
jaroslav@1646
   180
    // cloning API
jaroslav@1646
   181
    //
jaroslav@1646
   182
jaroslav@1646
   183
    public abstract BoundMethodHandle clone(MethodType mt, LambdaForm lf) throws Throwable;
jaroslav@1646
   184
    public abstract BoundMethodHandle cloneExtendL(MethodType mt, LambdaForm lf, Object narg) throws Throwable;
jaroslav@1646
   185
    public abstract BoundMethodHandle cloneExtendI(MethodType mt, LambdaForm lf, int    narg) throws Throwable;
jaroslav@1646
   186
    public abstract BoundMethodHandle cloneExtendJ(MethodType mt, LambdaForm lf, long   narg) throws Throwable;
jaroslav@1646
   187
    public abstract BoundMethodHandle cloneExtendF(MethodType mt, LambdaForm lf, float  narg) throws Throwable;
jaroslav@1646
   188
    public abstract BoundMethodHandle cloneExtendD(MethodType mt, LambdaForm lf, double narg) throws Throwable;
jaroslav@1646
   189
jaroslav@1646
   190
    // The following is a grossly irregular hack:
jaroslav@1646
   191
    @Override MethodHandle reinvokerTarget() {
jaroslav@1646
   192
        try {
jaroslav@1646
   193
            return (MethodHandle) argL(0);
jaroslav@1646
   194
        } catch (Throwable ex) {
jaroslav@1646
   195
            throw newInternalError(ex);
jaroslav@1646
   196
        }
jaroslav@1646
   197
    }
jaroslav@1646
   198
jaroslav@1646
   199
    //
jaroslav@1646
   200
    // concrete BMH classes required to close bootstrap loops
jaroslav@1646
   201
    //
jaroslav@1646
   202
jaroslav@1646
   203
    private  // make it private to force users to access the enclosing class first
jaroslav@1646
   204
    static final class Species_L extends BoundMethodHandle {
jaroslav@1646
   205
        final Object argL0;
jaroslav@1646
   206
        public Species_L(MethodType mt, LambdaForm lf, Object argL0) {
jaroslav@1646
   207
            super(mt, lf);
jaroslav@1646
   208
            this.argL0 = argL0;
jaroslav@1646
   209
        }
jaroslav@1646
   210
        // The following is a grossly irregular hack:
jaroslav@1646
   211
        @Override MethodHandle reinvokerTarget() { return (MethodHandle) argL0; }
jaroslav@1646
   212
        @Override
jaroslav@1646
   213
        public SpeciesData speciesData() {
jaroslav@1646
   214
            return SPECIES_DATA;
jaroslav@1646
   215
        }
jaroslav@1646
   216
        public static final SpeciesData SPECIES_DATA = SpeciesData.getForClass("L", Species_L.class);
jaroslav@1646
   217
        @Override
jaroslav@1646
   218
        public final BoundMethodHandle clone(MethodType mt, LambdaForm lf) throws Throwable {
jaroslav@1646
   219
            return new Species_L(mt, lf, argL0);
jaroslav@1646
   220
        }
jaroslav@1646
   221
        @Override
jaroslav@1646
   222
        public final BoundMethodHandle cloneExtendL(MethodType mt, LambdaForm lf, Object narg) throws Throwable {
jaroslav@1646
   223
            return (BoundMethodHandle) SPECIES_DATA.extendWithIndex(INDEX_L).constructor[0].invokeBasic(mt, lf, argL0, narg);
jaroslav@1646
   224
        }
jaroslav@1646
   225
        @Override
jaroslav@1646
   226
        public final BoundMethodHandle cloneExtendI(MethodType mt, LambdaForm lf, int narg) throws Throwable {
jaroslav@1646
   227
            return (BoundMethodHandle) SPECIES_DATA.extendWithIndex(INDEX_I).constructor[0].invokeBasic(mt, lf, argL0, narg);
jaroslav@1646
   228
        }
jaroslav@1646
   229
        @Override
jaroslav@1646
   230
        public final BoundMethodHandle cloneExtendJ(MethodType mt, LambdaForm lf, long narg) throws Throwable {
jaroslav@1646
   231
            return (BoundMethodHandle) SPECIES_DATA.extendWithIndex(INDEX_J).constructor[0].invokeBasic(mt, lf, argL0, narg);
jaroslav@1646
   232
        }
jaroslav@1646
   233
        @Override
jaroslav@1646
   234
        public final BoundMethodHandle cloneExtendF(MethodType mt, LambdaForm lf, float narg) throws Throwable {
jaroslav@1646
   235
            return (BoundMethodHandle) SPECIES_DATA.extendWithIndex(INDEX_F).constructor[0].invokeBasic(mt, lf, argL0, narg);
jaroslav@1646
   236
        }
jaroslav@1646
   237
        @Override
jaroslav@1646
   238
        public final BoundMethodHandle cloneExtendD(MethodType mt, LambdaForm lf, double narg) throws Throwable {
jaroslav@1646
   239
            return (BoundMethodHandle) SPECIES_DATA.extendWithIndex(INDEX_D).constructor[0].invokeBasic(mt, lf, argL0, narg);
jaroslav@1646
   240
        }
jaroslav@1646
   241
    }
jaroslav@1646
   242
jaroslav@1646
   243
/*
jaroslav@1646
   244
    static final class Species_LL extends BoundMethodHandle {
jaroslav@1646
   245
        final Object argL0;
jaroslav@1646
   246
        final Object argL1;
jaroslav@1646
   247
        public Species_LL(MethodType mt, LambdaForm lf, Object argL0, Object argL1) {
jaroslav@1646
   248
            super(mt, lf);
jaroslav@1646
   249
            this.argL0 = argL0;
jaroslav@1646
   250
            this.argL1 = argL1;
jaroslav@1646
   251
        }
jaroslav@1646
   252
        @Override
jaroslav@1646
   253
        public SpeciesData speciesData() {
jaroslav@1646
   254
            return SPECIES_DATA;
jaroslav@1646
   255
        }
jaroslav@1646
   256
        public static final SpeciesData SPECIES_DATA = SpeciesData.getForClass("LL", Species_LL.class);
jaroslav@1646
   257
        @Override
jaroslav@1646
   258
        public final BoundMethodHandle clone(MethodType mt, LambdaForm lf) throws Throwable {
jaroslav@1646
   259
            return new Species_LL(mt, lf, argL0, argL1);
jaroslav@1646
   260
        }
jaroslav@1646
   261
        @Override
jaroslav@1646
   262
        public final BoundMethodHandle cloneExtendL(MethodType mt, LambdaForm lf, Object narg) throws Throwable {
jaroslav@1646
   263
            return (BoundMethodHandle) SPECIES_DATA.extendWithIndex(INDEX_L).constructor[0].invokeBasic(mt, lf, argL0, argL1, narg);
jaroslav@1646
   264
        }
jaroslav@1646
   265
        @Override
jaroslav@1646
   266
        public final BoundMethodHandle cloneExtendI(MethodType mt, LambdaForm lf, int narg) throws Throwable {
jaroslav@1646
   267
            return (BoundMethodHandle) SPECIES_DATA.extendWithIndex(INDEX_I).constructor[0].invokeBasic(mt, lf, argL0, argL1, narg);
jaroslav@1646
   268
        }
jaroslav@1646
   269
        @Override
jaroslav@1646
   270
        public final BoundMethodHandle cloneExtendJ(MethodType mt, LambdaForm lf, long narg) throws Throwable {
jaroslav@1646
   271
            return (BoundMethodHandle) SPECIES_DATA.extendWithIndex(INDEX_J).constructor[0].invokeBasic(mt, lf, argL0, argL1, narg);
jaroslav@1646
   272
        }
jaroslav@1646
   273
        @Override
jaroslav@1646
   274
        public final BoundMethodHandle cloneExtendF(MethodType mt, LambdaForm lf, float narg) throws Throwable {
jaroslav@1646
   275
            return (BoundMethodHandle) SPECIES_DATA.extendWithIndex(INDEX_F).constructor[0].invokeBasic(mt, lf, argL0, argL1, narg);
jaroslav@1646
   276
        }
jaroslav@1646
   277
        @Override
jaroslav@1646
   278
        public final BoundMethodHandle cloneExtendD(MethodType mt, LambdaForm lf, double narg) throws Throwable {
jaroslav@1646
   279
            return (BoundMethodHandle) SPECIES_DATA.extendWithIndex(INDEX_D).constructor[0].invokeBasic(mt, lf, argL0, argL1, narg);
jaroslav@1646
   280
        }
jaroslav@1646
   281
    }
jaroslav@1646
   282
jaroslav@1646
   283
    static final class Species_JL extends BoundMethodHandle {
jaroslav@1646
   284
        final long argJ0;
jaroslav@1646
   285
        final Object argL1;
jaroslav@1646
   286
        public Species_JL(MethodType mt, LambdaForm lf, long argJ0, Object argL1) {
jaroslav@1646
   287
            super(mt, lf);
jaroslav@1646
   288
            this.argJ0 = argJ0;
jaroslav@1646
   289
            this.argL1 = argL1;
jaroslav@1646
   290
        }
jaroslav@1646
   291
        @Override
jaroslav@1646
   292
        public SpeciesData speciesData() {
jaroslav@1646
   293
            return SPECIES_DATA;
jaroslav@1646
   294
        }
jaroslav@1646
   295
        public static final SpeciesData SPECIES_DATA = SpeciesData.getForClass("JL", Species_JL.class);
jaroslav@1646
   296
        @Override public final long   argJ0() { return argJ0; }
jaroslav@1646
   297
        @Override public final Object argL1() { return argL1; }
jaroslav@1646
   298
        @Override
jaroslav@1646
   299
        public final BoundMethodHandle clone(MethodType mt, LambdaForm lf) throws Throwable {
jaroslav@1646
   300
            return new Species_JL(mt, lf, argJ0, argL1);
jaroslav@1646
   301
        }
jaroslav@1646
   302
        @Override
jaroslav@1646
   303
        public final BoundMethodHandle cloneExtendL(MethodType mt, LambdaForm lf, Object narg) throws Throwable {
jaroslav@1646
   304
            return (BoundMethodHandle) SPECIES_DATA.extendWithIndex(INDEX_L).constructor[0].invokeBasic(mt, lf, argJ0, argL1, narg);
jaroslav@1646
   305
        }
jaroslav@1646
   306
        @Override
jaroslav@1646
   307
        public final BoundMethodHandle cloneExtendI(MethodType mt, LambdaForm lf, int narg) throws Throwable {
jaroslav@1646
   308
            return (BoundMethodHandle) SPECIES_DATA.extendWithIndex(INDEX_I).constructor[0].invokeBasic(mt, lf, argJ0, argL1, narg);
jaroslav@1646
   309
        }
jaroslav@1646
   310
        @Override
jaroslav@1646
   311
        public final BoundMethodHandle cloneExtendJ(MethodType mt, LambdaForm lf, long narg) throws Throwable {
jaroslav@1646
   312
            return (BoundMethodHandle) SPECIES_DATA.extendWithIndex(INDEX_J).constructor[0].invokeBasic(mt, lf, argJ0, argL1, narg);
jaroslav@1646
   313
        }
jaroslav@1646
   314
        @Override
jaroslav@1646
   315
        public final BoundMethodHandle cloneExtendF(MethodType mt, LambdaForm lf, float narg) throws Throwable {
jaroslav@1646
   316
            return (BoundMethodHandle) SPECIES_DATA.extendWithIndex(INDEX_F).constructor[0].invokeBasic(mt, lf, argJ0, argL1, narg);
jaroslav@1646
   317
        }
jaroslav@1646
   318
        @Override
jaroslav@1646
   319
        public final BoundMethodHandle cloneExtendD(MethodType mt, LambdaForm lf, double narg) throws Throwable {
jaroslav@1646
   320
            return (BoundMethodHandle) SPECIES_DATA.extendWithIndex(INDEX_D).constructor[0].invokeBasic(mt, lf, argJ0, argL1, narg);
jaroslav@1646
   321
        }
jaroslav@1646
   322
    }
jaroslav@1646
   323
*/
jaroslav@1646
   324
jaroslav@1646
   325
    //
jaroslav@1646
   326
    // BMH species meta-data
jaroslav@1646
   327
    //
jaroslav@1646
   328
jaroslav@1646
   329
    /**
jaroslav@1646
   330
     * Meta-data wrapper for concrete BMH classes.
jaroslav@1646
   331
     */
jaroslav@1646
   332
    static class SpeciesData {
jaroslav@1646
   333
        final String                             types;
jaroslav@1646
   334
        final Class<? extends BoundMethodHandle> clazz;
jaroslav@1646
   335
        // Bootstrapping requires circular relations MH -> BMH -> SpeciesData -> MH
jaroslav@1646
   336
        // Therefore, we need a non-final link in the chain.  Use array elements.
jaroslav@1646
   337
        final MethodHandle[]                     constructor;
jaroslav@1646
   338
        final MethodHandle[]                     getters;
jaroslav@1646
   339
        final SpeciesData[]                      extensions;
jaroslav@1646
   340
jaroslav@1646
   341
        public int fieldCount() {
jaroslav@1646
   342
            return types.length();
jaroslav@1646
   343
        }
jaroslav@1646
   344
        public char fieldType(int i) {
jaroslav@1646
   345
            return types.charAt(i);
jaroslav@1646
   346
        }
jaroslav@1646
   347
jaroslav@1646
   348
        public String toString() {
jaroslav@1646
   349
            return "SpeciesData["+(isPlaceholder() ? "<placeholder>" : clazz.getSimpleName())+":"+types+"]";
jaroslav@1646
   350
        }
jaroslav@1646
   351
jaroslav@1646
   352
        /**
jaroslav@1646
   353
         * Return a {@link LambdaForm.Name} containing a {@link LambdaForm.NamedFunction} that
jaroslav@1646
   354
         * represents a MH bound to a generic invoker, which in turn forwards to the corresponding
jaroslav@1646
   355
         * getter.
jaroslav@1646
   356
         */
jaroslav@1646
   357
        Name getterName(Name mhName, int i) {
jaroslav@1646
   358
            MethodHandle mh = getters[i];
jaroslav@1646
   359
            assert(mh != null) : this+"."+i;
jaroslav@1646
   360
            return new Name(mh, mhName);
jaroslav@1646
   361
        }
jaroslav@1646
   362
jaroslav@1646
   363
        NamedFunction getterFunction(int i) {
jaroslav@1646
   364
            return new NamedFunction(getters[i]);
jaroslav@1646
   365
        }
jaroslav@1646
   366
jaroslav@1646
   367
        static final SpeciesData EMPTY = new SpeciesData("", BoundMethodHandle.class);
jaroslav@1646
   368
jaroslav@1646
   369
        private SpeciesData(String types, Class<? extends BoundMethodHandle> clazz) {
jaroslav@1646
   370
            this.types = types;
jaroslav@1646
   371
            this.clazz = clazz;
jaroslav@1646
   372
            if (!INIT_DONE) {
jaroslav@1646
   373
                this.constructor = new MethodHandle[1];
jaroslav@1646
   374
                this.getters = new MethodHandle[types.length()];
jaroslav@1646
   375
            } else {
jaroslav@1646
   376
                this.constructor = Factory.makeCtors(clazz, types, null);
jaroslav@1646
   377
                this.getters = Factory.makeGetters(clazz, types, null);
jaroslav@1646
   378
            }
jaroslav@1646
   379
            this.extensions = new SpeciesData[EXTENSION_TYPES.length()];
jaroslav@1646
   380
        }
jaroslav@1646
   381
jaroslav@1646
   382
        private void initForBootstrap() {
jaroslav@1646
   383
            assert(!INIT_DONE);
jaroslav@1646
   384
            if (constructor[0] == null) {
jaroslav@1646
   385
                Factory.makeCtors(clazz, types, this.constructor);
jaroslav@1646
   386
                Factory.makeGetters(clazz, types, this.getters);
jaroslav@1646
   387
            }
jaroslav@1646
   388
        }
jaroslav@1646
   389
jaroslav@1646
   390
        private SpeciesData(String types) {
jaroslav@1646
   391
            // Placeholder only.
jaroslav@1646
   392
            this.types = types;
jaroslav@1646
   393
            this.clazz = null;
jaroslav@1646
   394
            this.constructor = null;
jaroslav@1646
   395
            this.getters = null;
jaroslav@1646
   396
            this.extensions = null;
jaroslav@1646
   397
        }
jaroslav@1646
   398
        private boolean isPlaceholder() { return clazz == null; }
jaroslav@1646
   399
jaroslav@1646
   400
        private static final HashMap<String, SpeciesData> CACHE = new HashMap<>();
jaroslav@1646
   401
        static { CACHE.put("", EMPTY); }  // make bootstrap predictable
jaroslav@1646
   402
        private static final boolean INIT_DONE;  // set after <clinit> finishes...
jaroslav@1646
   403
jaroslav@1646
   404
        SpeciesData extendWithType(char type) {
jaroslav@1646
   405
            int i = extensionIndex(type);
jaroslav@1646
   406
            SpeciesData d = extensions[i];
jaroslav@1646
   407
            if (d != null)  return d;
jaroslav@1646
   408
            extensions[i] = d = get(types+type);
jaroslav@1646
   409
            return d;
jaroslav@1646
   410
        }
jaroslav@1646
   411
jaroslav@1646
   412
        SpeciesData extendWithIndex(byte index) {
jaroslav@1646
   413
            SpeciesData d = extensions[index];
jaroslav@1646
   414
            if (d != null)  return d;
jaroslav@1646
   415
            extensions[index] = d = get(types+EXTENSION_TYPES.charAt(index));
jaroslav@1646
   416
            return d;
jaroslav@1646
   417
        }
jaroslav@1646
   418
jaroslav@1646
   419
        private static SpeciesData get(String types) {
jaroslav@1646
   420
            // Acquire cache lock for query.
jaroslav@1646
   421
            SpeciesData d = lookupCache(types);
jaroslav@1646
   422
            if (!d.isPlaceholder())
jaroslav@1646
   423
                return d;
jaroslav@1646
   424
            synchronized (d) {
jaroslav@1646
   425
                // Use synch. on the placeholder to prevent multiple instantiation of one species.
jaroslav@1646
   426
                // Creating this class forces a recursive call to getForClass.
jaroslav@1646
   427
                if (lookupCache(types).isPlaceholder())
jaroslav@1646
   428
                    Factory.generateConcreteBMHClass(types);
jaroslav@1646
   429
            }
jaroslav@1646
   430
            // Reacquire cache lock.
jaroslav@1646
   431
            d = lookupCache(types);
jaroslav@1646
   432
            // Class loading must have upgraded the cache.
jaroslav@1646
   433
            assert(d != null && !d.isPlaceholder());
jaroslav@1646
   434
            return d;
jaroslav@1646
   435
        }
jaroslav@1646
   436
        static SpeciesData getForClass(String types, Class<? extends BoundMethodHandle> clazz) {
jaroslav@1646
   437
            // clazz is a new class which is initializing its SPECIES_DATA field
jaroslav@1646
   438
            return updateCache(types, new SpeciesData(types, clazz));
jaroslav@1646
   439
        }
jaroslav@1646
   440
        private static synchronized SpeciesData lookupCache(String types) {
jaroslav@1646
   441
            SpeciesData d = CACHE.get(types);
jaroslav@1646
   442
            if (d != null)  return d;
jaroslav@1646
   443
            d = new SpeciesData(types);
jaroslav@1646
   444
            assert(d.isPlaceholder());
jaroslav@1646
   445
            CACHE.put(types, d);
jaroslav@1646
   446
            return d;
jaroslav@1646
   447
        }
jaroslav@1646
   448
        private static synchronized SpeciesData updateCache(String types, SpeciesData d) {
jaroslav@1646
   449
            SpeciesData d2;
jaroslav@1646
   450
            assert((d2 = CACHE.get(types)) == null || d2.isPlaceholder());
jaroslav@1646
   451
            assert(!d.isPlaceholder());
jaroslav@1646
   452
            CACHE.put(types, d);
jaroslav@1646
   453
            return d;
jaroslav@1646
   454
        }
jaroslav@1646
   455
jaroslav@1646
   456
        static {
jaroslav@1646
   457
            // pre-fill the BMH speciesdata cache with BMH's inner classes
jaroslav@1646
   458
            final Class<BoundMethodHandle> rootCls = BoundMethodHandle.class;
jaroslav@1646
   459
            SpeciesData d0 = BoundMethodHandle.SPECIES_DATA;  // trigger class init
jaroslav@1646
   460
            assert(d0 == null || d0 == lookupCache("")) : d0;
jaroslav@1646
   461
            try {
jaroslav@1646
   462
                for (Class<?> c : rootCls.getDeclaredClasses()) {
jaroslav@1646
   463
                    if (rootCls.isAssignableFrom(c)) {
jaroslav@1646
   464
                        final Class<? extends BoundMethodHandle> cbmh = c.asSubclass(BoundMethodHandle.class);
jaroslav@1646
   465
                        SpeciesData d = Factory.speciesDataFromConcreteBMHClass(cbmh);
jaroslav@1646
   466
                        assert(d != null) : cbmh.getName();
jaroslav@1646
   467
                        assert(d.clazz == cbmh);
jaroslav@1646
   468
                        assert(d == lookupCache(d.types));
jaroslav@1646
   469
                    }
jaroslav@1646
   470
                }
jaroslav@1646
   471
            } catch (Throwable e) {
jaroslav@1646
   472
                throw newInternalError(e);
jaroslav@1646
   473
            }
jaroslav@1646
   474
jaroslav@1646
   475
            for (SpeciesData d : CACHE.values()) {
jaroslav@1646
   476
                d.initForBootstrap();
jaroslav@1646
   477
            }
jaroslav@1646
   478
            // Note:  Do not simplify this, because INIT_DONE must not be
jaroslav@1646
   479
            // a compile-time constant during bootstrapping.
jaroslav@1646
   480
            INIT_DONE = Boolean.TRUE;
jaroslav@1646
   481
        }
jaroslav@1646
   482
    }
jaroslav@1646
   483
jaroslav@1646
   484
    static SpeciesData getSpeciesData(String types) {
jaroslav@1646
   485
        return SpeciesData.get(types);
jaroslav@1646
   486
    }
jaroslav@1646
   487
jaroslav@1646
   488
    /**
jaroslav@1646
   489
     * Generation of concrete BMH classes.
jaroslav@1646
   490
     *
jaroslav@1646
   491
     * A concrete BMH species is fit for binding a number of values adhering to a
jaroslav@1646
   492
     * given type pattern. Reference types are erased.
jaroslav@1646
   493
     *
jaroslav@1646
   494
     * BMH species are cached by type pattern.
jaroslav@1646
   495
     *
jaroslav@1646
   496
     * A BMH species has a number of fields with the concrete (possibly erased) types of
jaroslav@1646
   497
     * bound values. Setters are provided as an API in BMH. Getters are exposed as MHs,
jaroslav@1646
   498
     * which can be included as names in lambda forms.
jaroslav@1646
   499
     */
jaroslav@1646
   500
    static class Factory {
jaroslav@1646
   501
jaroslav@1646
   502
        static final String JLO_SIG  = "Ljava/lang/Object;";
jaroslav@1646
   503
        static final String JLS_SIG  = "Ljava/lang/String;";
jaroslav@1646
   504
        static final String JLC_SIG  = "Ljava/lang/Class;";
jaroslav@1646
   505
        static final String MH       = "java/lang/invoke/MethodHandle";
jaroslav@1646
   506
        static final String MH_SIG   = "L"+MH+";";
jaroslav@1646
   507
        static final String BMH      = "java/lang/invoke/BoundMethodHandle";
jaroslav@1646
   508
        static final String BMH_SIG  = "L"+BMH+";";
jaroslav@1646
   509
        static final String SPECIES_DATA     = "java/lang/invoke/BoundMethodHandle$SpeciesData";
jaroslav@1646
   510
        static final String SPECIES_DATA_SIG = "L"+SPECIES_DATA+";";
jaroslav@1646
   511
jaroslav@1646
   512
        static final String SPECIES_PREFIX_NAME = "Species_";
jaroslav@1646
   513
        static final String SPECIES_PREFIX_PATH = BMH + "$" + SPECIES_PREFIX_NAME;
jaroslav@1646
   514
jaroslav@1646
   515
        static final String BMHSPECIES_DATA_EWI_SIG = "(B)" + SPECIES_DATA_SIG;
jaroslav@1646
   516
        static final String BMHSPECIES_DATA_GFC_SIG = "(" + JLS_SIG + JLC_SIG + ")" + SPECIES_DATA_SIG;
jaroslav@1646
   517
        static final String MYSPECIES_DATA_SIG = "()" + SPECIES_DATA_SIG;
jaroslav@1646
   518
        static final String VOID_SIG   = "()V";
jaroslav@1646
   519
jaroslav@1646
   520
        static final String SIG_INCIPIT = "(Ljava/lang/invoke/MethodType;Ljava/lang/invoke/LambdaForm;";
jaroslav@1646
   521
jaroslav@1646
   522
        static final Class<?>[] TYPES = new Class<?>[] { Object.class, int.class, long.class, float.class, double.class };
jaroslav@1646
   523
jaroslav@1646
   524
        static final String[] E_THROWABLE = new String[] { "java/lang/Throwable" };
jaroslav@1646
   525
jaroslav@1646
   526
        /**
jaroslav@1646
   527
         * Generate a concrete subclass of BMH for a given combination of bound types.
jaroslav@1646
   528
         *
jaroslav@1646
   529
         * A concrete BMH species adheres to the following schema:
jaroslav@1646
   530
         *
jaroslav@1646
   531
         * <pre>
jaroslav@1646
   532
         * class Species_[[types]] extends BoundMethodHandle {
jaroslav@1646
   533
         *     [[fields]]
jaroslav@1646
   534
         *     final SpeciesData speciesData() { return SpeciesData.get("[[types]]"); }
jaroslav@1646
   535
         * }
jaroslav@1646
   536
         * </pre>
jaroslav@1646
   537
         *
jaroslav@1646
   538
         * The {@code [[types]]} signature is precisely the string that is passed to this
jaroslav@1646
   539
         * method.
jaroslav@1646
   540
         *
jaroslav@1646
   541
         * The {@code [[fields]]} section consists of one field definition per character in
jaroslav@1646
   542
         * the type signature, adhering to the naming schema described in the definition of
jaroslav@1646
   543
         * {@link #makeFieldName}.
jaroslav@1646
   544
         *
jaroslav@1646
   545
         * For example, a concrete BMH species for two reference and one integral bound values
jaroslav@1646
   546
         * would have the following shape:
jaroslav@1646
   547
         *
jaroslav@1646
   548
         * <pre>
jaroslav@1646
   549
         * class BoundMethodHandle { ... private static
jaroslav@1646
   550
         * final class Species_LLI extends BoundMethodHandle {
jaroslav@1646
   551
         *     final Object argL0;
jaroslav@1646
   552
         *     final Object argL1;
jaroslav@1646
   553
         *     final int argI2;
jaroslav@1646
   554
         *     public Species_LLI(MethodType mt, LambdaForm lf, Object argL0, Object argL1, int argI2) {
jaroslav@1646
   555
         *         super(mt, lf);
jaroslav@1646
   556
         *         this.argL0 = argL0;
jaroslav@1646
   557
         *         this.argL1 = argL1;
jaroslav@1646
   558
         *         this.argI2 = argI2;
jaroslav@1646
   559
         *     }
jaroslav@1646
   560
         *     public final SpeciesData speciesData() { return SPECIES_DATA; }
jaroslav@1646
   561
         *     public static final SpeciesData SPECIES_DATA = SpeciesData.getForClass("LLI", Species_LLI.class);
jaroslav@1646
   562
         *     public final BoundMethodHandle clone(MethodType mt, LambdaForm lf) {
jaroslav@1646
   563
         *         return SPECIES_DATA.constructor[0].invokeBasic(mt, lf, argL0, argL1, argI2);
jaroslav@1646
   564
         *     }
jaroslav@1646
   565
         *     public final BoundMethodHandle cloneExtendL(MethodType mt, LambdaForm lf, Object narg) {
jaroslav@1646
   566
         *         return SPECIES_DATA.extendWithIndex(INDEX_L).constructor[0].invokeBasic(mt, lf, argL0, argL1, argI2, narg);
jaroslav@1646
   567
         *     }
jaroslav@1646
   568
         *     public final BoundMethodHandle cloneExtendI(MethodType mt, LambdaForm lf, int narg) {
jaroslav@1646
   569
         *         return SPECIES_DATA.extendWithIndex(INDEX_I).constructor[0].invokeBasic(mt, lf, argL0, argL1, argI2, narg);
jaroslav@1646
   570
         *     }
jaroslav@1646
   571
         *     public final BoundMethodHandle cloneExtendJ(MethodType mt, LambdaForm lf, long narg) {
jaroslav@1646
   572
         *         return SPECIES_DATA.extendWithIndex(INDEX_J).constructor[0].invokeBasic(mt, lf, argL0, argL1, argI2, narg);
jaroslav@1646
   573
         *     }
jaroslav@1646
   574
         *     public final BoundMethodHandle cloneExtendF(MethodType mt, LambdaForm lf, float narg) {
jaroslav@1646
   575
         *         return SPECIES_DATA.extendWithIndex(INDEX_F).constructor[0].invokeBasic(mt, lf, argL0, argL1, argI2, narg);
jaroslav@1646
   576
         *     }
jaroslav@1646
   577
         *     public final BoundMethodHandle cloneExtendD(MethodType mt, LambdaForm lf, double narg) {
jaroslav@1646
   578
         *         return SPECIES_DATA.extendWithIndex(INDEX_D).constructor[0].invokeBasic(mt, lf, argL0, argL1, argI2, narg);
jaroslav@1646
   579
         *     }
jaroslav@1646
   580
         * }
jaroslav@1646
   581
         * </pre>
jaroslav@1646
   582
         *
jaroslav@1646
   583
         * @param types the type signature, wherein reference types are erased to 'L'
jaroslav@1646
   584
         * @return the generated concrete BMH class
jaroslav@1646
   585
         */
jaroslav@1646
   586
        static Class<? extends BoundMethodHandle> generateConcreteBMHClass(String types) {
jaroslav@1646
   587
            final ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS + ClassWriter.COMPUTE_FRAMES);
jaroslav@1646
   588
jaroslav@1646
   589
            final String className  = SPECIES_PREFIX_PATH + types;
jaroslav@1646
   590
            final String sourceFile = SPECIES_PREFIX_NAME + types;
jaroslav@1646
   591
            cw.visit(V1_6, ACC_PUBLIC + ACC_FINAL + ACC_SUPER, className, null, BMH, null);
jaroslav@1646
   592
            cw.visitSource(sourceFile, null);
jaroslav@1646
   593
jaroslav@1646
   594
            // emit static types and SPECIES_DATA fields
jaroslav@1646
   595
            cw.visitField(ACC_PUBLIC + ACC_STATIC, "SPECIES_DATA", SPECIES_DATA_SIG, null, null).visitEnd();
jaroslav@1646
   596
jaroslav@1646
   597
            // emit bound argument fields
jaroslav@1646
   598
            for (int i = 0; i < types.length(); ++i) {
jaroslav@1646
   599
                final char t = types.charAt(i);
jaroslav@1646
   600
                final String fieldName = makeFieldName(types, i);
jaroslav@1646
   601
                final String fieldDesc = t == 'L' ? JLO_SIG : String.valueOf(t);
jaroslav@1646
   602
                cw.visitField(ACC_FINAL, fieldName, fieldDesc, null, null).visitEnd();
jaroslav@1646
   603
            }
jaroslav@1646
   604
jaroslav@1646
   605
            MethodVisitor mv;
jaroslav@1646
   606
jaroslav@1646
   607
            // emit constructor
jaroslav@1646
   608
            mv = cw.visitMethod(ACC_PUBLIC, "<init>", makeSignature(types, true), null, null);
jaroslav@1646
   609
            mv.visitCode();
jaroslav@1646
   610
            mv.visitVarInsn(ALOAD, 0);
jaroslav@1646
   611
            mv.visitVarInsn(ALOAD, 1);
jaroslav@1646
   612
            mv.visitVarInsn(ALOAD, 2);
jaroslav@1646
   613
jaroslav@1646
   614
            mv.visitMethodInsn(INVOKESPECIAL, BMH, "<init>", makeSignature("", true));
jaroslav@1646
   615
jaroslav@1646
   616
            for (int i = 0, j = 0; i < types.length(); ++i, ++j) {
jaroslav@1646
   617
                // i counts the arguments, j counts corresponding argument slots
jaroslav@1646
   618
                char t = types.charAt(i);
jaroslav@1646
   619
                mv.visitVarInsn(ALOAD, 0);
jaroslav@1646
   620
                mv.visitVarInsn(typeLoadOp(t), j + 3); // parameters start at 3
jaroslav@1646
   621
                mv.visitFieldInsn(PUTFIELD, className, makeFieldName(types, i), typeSig(t));
jaroslav@1646
   622
                if (t == 'J' || t == 'D') {
jaroslav@1646
   623
                    ++j; // adjust argument register access
jaroslav@1646
   624
                }
jaroslav@1646
   625
            }
jaroslav@1646
   626
jaroslav@1646
   627
            mv.visitInsn(RETURN);
jaroslav@1646
   628
            mv.visitMaxs(0, 0);
jaroslav@1646
   629
            mv.visitEnd();
jaroslav@1646
   630
jaroslav@1646
   631
            // emit implementation of reinvokerTarget()
jaroslav@1646
   632
            mv = cw.visitMethod(ACC_PUBLIC + ACC_FINAL, "reinvokerTarget", "()" + MH_SIG, null, null);
jaroslav@1646
   633
            mv.visitCode();
jaroslav@1646
   634
            mv.visitVarInsn(ALOAD, 0);
jaroslav@1646
   635
            mv.visitFieldInsn(GETFIELD, className, "argL0", JLO_SIG);
jaroslav@1646
   636
            mv.visitTypeInsn(CHECKCAST, MH);
jaroslav@1646
   637
            mv.visitInsn(ARETURN);
jaroslav@1646
   638
            mv.visitMaxs(0, 0);
jaroslav@1646
   639
            mv.visitEnd();
jaroslav@1646
   640
jaroslav@1646
   641
            // emit implementation of speciesData()
jaroslav@1646
   642
            mv = cw.visitMethod(ACC_PUBLIC + ACC_FINAL, "speciesData", MYSPECIES_DATA_SIG, null, null);
jaroslav@1646
   643
            mv.visitCode();
jaroslav@1646
   644
            mv.visitFieldInsn(GETSTATIC, className, "SPECIES_DATA", SPECIES_DATA_SIG);
jaroslav@1646
   645
            mv.visitInsn(ARETURN);
jaroslav@1646
   646
            mv.visitMaxs(0, 0);
jaroslav@1646
   647
            mv.visitEnd();
jaroslav@1646
   648
jaroslav@1646
   649
            // emit clone()
jaroslav@1646
   650
            mv = cw.visitMethod(ACC_PUBLIC + ACC_FINAL, "clone", makeSignature("", false), null, E_THROWABLE);
jaroslav@1646
   651
            mv.visitCode();
jaroslav@1646
   652
            // return speciesData().constructor[0].invokeBasic(mt, lf, argL0, ...)
jaroslav@1646
   653
            // obtain constructor
jaroslav@1646
   654
            mv.visitVarInsn(ALOAD, 0);
jaroslav@1646
   655
            mv.visitFieldInsn(GETSTATIC, className, "SPECIES_DATA", SPECIES_DATA_SIG);
jaroslav@1646
   656
            mv.visitFieldInsn(GETFIELD, SPECIES_DATA, "constructor", "[" + MH_SIG);
jaroslav@1646
   657
            mv.visitInsn(ICONST_0);
jaroslav@1646
   658
            mv.visitInsn(AALOAD);
jaroslav@1646
   659
            // load mt, lf
jaroslav@1646
   660
            mv.visitVarInsn(ALOAD, 1);
jaroslav@1646
   661
            mv.visitVarInsn(ALOAD, 2);
jaroslav@1646
   662
            // put fields on the stack
jaroslav@1646
   663
            emitPushFields(types, className, mv);
jaroslav@1646
   664
            // finally, invoke the constructor and return
jaroslav@1646
   665
            mv.visitMethodInsn(INVOKEVIRTUAL, MH, "invokeBasic", makeSignature(types, false));
jaroslav@1646
   666
            mv.visitInsn(ARETURN);
jaroslav@1646
   667
            mv.visitMaxs(0, 0);
jaroslav@1646
   668
            mv.visitEnd();
jaroslav@1646
   669
jaroslav@1646
   670
            // for each type, emit cloneExtendT()
jaroslav@1646
   671
            for (Class<?> c : TYPES) {
jaroslav@1646
   672
                char t = Wrapper.basicTypeChar(c);
jaroslav@1646
   673
                mv = cw.visitMethod(ACC_PUBLIC + ACC_FINAL, "cloneExtend" + t, makeSignature(String.valueOf(t), false), null, E_THROWABLE);
jaroslav@1646
   674
                mv.visitCode();
jaroslav@1646
   675
                // return SPECIES_DATA.extendWithIndex(extensionIndex(t)).constructor[0].invokeBasic(mt, lf, argL0, ..., narg)
jaroslav@1646
   676
                // obtain constructor
jaroslav@1646
   677
                mv.visitFieldInsn(GETSTATIC, className, "SPECIES_DATA", SPECIES_DATA_SIG);
jaroslav@1646
   678
                int iconstInsn = ICONST_0 + extensionIndex(t);
jaroslav@1646
   679
                assert(iconstInsn <= ICONST_5);
jaroslav@1646
   680
                mv.visitInsn(iconstInsn);
jaroslav@1646
   681
                mv.visitMethodInsn(INVOKEVIRTUAL, SPECIES_DATA, "extendWithIndex", BMHSPECIES_DATA_EWI_SIG);
jaroslav@1646
   682
                mv.visitFieldInsn(GETFIELD, SPECIES_DATA, "constructor", "[" + MH_SIG);
jaroslav@1646
   683
                mv.visitInsn(ICONST_0);
jaroslav@1646
   684
                mv.visitInsn(AALOAD);
jaroslav@1646
   685
                // load mt, lf
jaroslav@1646
   686
                mv.visitVarInsn(ALOAD, 1);
jaroslav@1646
   687
                mv.visitVarInsn(ALOAD, 2);
jaroslav@1646
   688
                // put fields on the stack
jaroslav@1646
   689
                emitPushFields(types, className, mv);
jaroslav@1646
   690
                // put narg on stack
jaroslav@1646
   691
                mv.visitVarInsn(typeLoadOp(t), 3);
jaroslav@1646
   692
                // finally, invoke the constructor and return
jaroslav@1646
   693
                mv.visitMethodInsn(INVOKEVIRTUAL, MH, "invokeBasic", makeSignature(types + t, false));
jaroslav@1646
   694
                mv.visitInsn(ARETURN);
jaroslav@1646
   695
                mv.visitMaxs(0, 0);
jaroslav@1646
   696
                mv.visitEnd();
jaroslav@1646
   697
            }
jaroslav@1646
   698
jaroslav@1646
   699
            // emit class initializer
jaroslav@1646
   700
            mv = cw.visitMethod(ACC_PUBLIC | ACC_STATIC, "<clinit>", VOID_SIG, null, null);
jaroslav@1646
   701
            mv.visitCode();
jaroslav@1646
   702
            mv.visitLdcInsn(types);
jaroslav@1646
   703
            mv.visitLdcInsn(Type.getObjectType(className));
jaroslav@1646
   704
            mv.visitMethodInsn(INVOKESTATIC, SPECIES_DATA, "getForClass", BMHSPECIES_DATA_GFC_SIG);
jaroslav@1646
   705
            mv.visitFieldInsn(PUTSTATIC, className, "SPECIES_DATA", SPECIES_DATA_SIG);
jaroslav@1646
   706
            mv.visitInsn(RETURN);
jaroslav@1646
   707
            mv.visitMaxs(0, 0);
jaroslav@1646
   708
            mv.visitEnd();
jaroslav@1646
   709
jaroslav@1646
   710
            cw.visitEnd();
jaroslav@1646
   711
jaroslav@1646
   712
            // load class
jaroslav@1646
   713
            final byte[] classFile = cw.toByteArray();
jaroslav@1646
   714
            InvokerBytecodeGenerator.maybeDump(className, classFile);
jaroslav@1646
   715
            Class<? extends BoundMethodHandle> bmhClass =
jaroslav@1646
   716
                //UNSAFE.defineAnonymousClass(BoundMethodHandle.class, classFile, null).asSubclass(BoundMethodHandle.class);
jaroslav@1646
   717
                UNSAFE.defineClass(className, classFile, 0, classFile.length,
jaroslav@1646
   718
                                   BoundMethodHandle.class.getClassLoader(), null)
jaroslav@1646
   719
                    .asSubclass(BoundMethodHandle.class);
jaroslav@1646
   720
            UNSAFE.ensureClassInitialized(bmhClass);
jaroslav@1646
   721
jaroslav@1646
   722
            return bmhClass;
jaroslav@1646
   723
        }
jaroslav@1646
   724
jaroslav@1646
   725
        private static int typeLoadOp(char t) {
jaroslav@1646
   726
            switch (t) {
jaroslav@1646
   727
            case 'L': return ALOAD;
jaroslav@1646
   728
            case 'I': return ILOAD;
jaroslav@1646
   729
            case 'J': return LLOAD;
jaroslav@1646
   730
            case 'F': return FLOAD;
jaroslav@1646
   731
            case 'D': return DLOAD;
jaroslav@1646
   732
            default : throw new InternalError("unrecognized type " + t);
jaroslav@1646
   733
            }
jaroslav@1646
   734
        }
jaroslav@1646
   735
jaroslav@1646
   736
        private static void emitPushFields(String types, String className, MethodVisitor mv) {
jaroslav@1646
   737
            for (int i = 0; i < types.length(); ++i) {
jaroslav@1646
   738
                char tc = types.charAt(i);
jaroslav@1646
   739
                mv.visitVarInsn(ALOAD, 0);
jaroslav@1646
   740
                mv.visitFieldInsn(GETFIELD, className, makeFieldName(types, i), typeSig(tc));
jaroslav@1646
   741
            }
jaroslav@1646
   742
        }
jaroslav@1646
   743
jaroslav@1646
   744
        static String typeSig(char t) {
jaroslav@1646
   745
            return t == 'L' ? JLO_SIG : String.valueOf(t);
jaroslav@1646
   746
        }
jaroslav@1646
   747
jaroslav@1646
   748
        //
jaroslav@1646
   749
        // Getter MH generation.
jaroslav@1646
   750
        //
jaroslav@1646
   751
jaroslav@1646
   752
        private static MethodHandle makeGetter(Class<?> cbmhClass, String types, int index) {
jaroslav@1646
   753
            String fieldName = makeFieldName(types, index);
jaroslav@1646
   754
            Class<?> fieldType = Wrapper.forBasicType(types.charAt(index)).primitiveType();
jaroslav@1646
   755
            try {
jaroslav@1646
   756
                return LOOKUP.findGetter(cbmhClass, fieldName, fieldType);
jaroslav@1646
   757
            } catch (NoSuchFieldException | IllegalAccessException e) {
jaroslav@1646
   758
                throw newInternalError(e);
jaroslav@1646
   759
            }
jaroslav@1646
   760
        }
jaroslav@1646
   761
jaroslav@1646
   762
        static MethodHandle[] makeGetters(Class<?> cbmhClass, String types, MethodHandle[] mhs) {
jaroslav@1646
   763
            if (mhs == null)  mhs = new MethodHandle[types.length()];
jaroslav@1646
   764
            for (int i = 0; i < mhs.length; ++i) {
jaroslav@1646
   765
                mhs[i] = makeGetter(cbmhClass, types, i);
jaroslav@1646
   766
                assert(mhs[i].internalMemberName().getDeclaringClass() == cbmhClass);
jaroslav@1646
   767
            }
jaroslav@1646
   768
            return mhs;
jaroslav@1646
   769
        }
jaroslav@1646
   770
jaroslav@1646
   771
        static MethodHandle[] makeCtors(Class<? extends BoundMethodHandle> cbmh, String types, MethodHandle mhs[]) {
jaroslav@1646
   772
            if (mhs == null)  mhs = new MethodHandle[1];
jaroslav@1646
   773
            mhs[0] = makeCbmhCtor(cbmh, types);
jaroslav@1646
   774
            return mhs;
jaroslav@1646
   775
        }
jaroslav@1646
   776
jaroslav@1646
   777
        //
jaroslav@1646
   778
        // Auxiliary methods.
jaroslav@1646
   779
        //
jaroslav@1646
   780
jaroslav@1646
   781
        static SpeciesData speciesDataFromConcreteBMHClass(Class<? extends BoundMethodHandle> cbmh) {
jaroslav@1646
   782
            try {
jaroslav@1646
   783
                Field F_SPECIES_DATA = cbmh.getDeclaredField("SPECIES_DATA");
jaroslav@1646
   784
                return (SpeciesData) F_SPECIES_DATA.get(null);
jaroslav@1646
   785
            } catch (ReflectiveOperationException ex) {
jaroslav@1646
   786
                throw newInternalError(ex);
jaroslav@1646
   787
            }
jaroslav@1646
   788
        }
jaroslav@1646
   789
jaroslav@1646
   790
        /**
jaroslav@1646
   791
         * Field names in concrete BMHs adhere to this pattern:
jaroslav@1646
   792
         * arg + type + index
jaroslav@1646
   793
         * where type is a single character (L, I, J, F, D).
jaroslav@1646
   794
         */
jaroslav@1646
   795
        private static String makeFieldName(String types, int index) {
jaroslav@1646
   796
            assert index >= 0 && index < types.length();
jaroslav@1646
   797
            return "arg" + types.charAt(index) + index;
jaroslav@1646
   798
        }
jaroslav@1646
   799
jaroslav@1646
   800
        private static String makeSignature(String types, boolean ctor) {
jaroslav@1646
   801
            StringBuilder buf = new StringBuilder(SIG_INCIPIT);
jaroslav@1646
   802
            for (char c : types.toCharArray()) {
jaroslav@1646
   803
                buf.append(typeSig(c));
jaroslav@1646
   804
            }
jaroslav@1646
   805
            return buf.append(')').append(ctor ? "V" : BMH_SIG).toString();
jaroslav@1646
   806
        }
jaroslav@1646
   807
jaroslav@1646
   808
        static MethodHandle makeCbmhCtor(Class<? extends BoundMethodHandle> cbmh, String types) {
jaroslav@1646
   809
            try {
jaroslav@1646
   810
                return linkConstructor(LOOKUP.findConstructor(cbmh, MethodType.fromMethodDescriptorString(makeSignature(types, true), null)));
jaroslav@1646
   811
            } catch (NoSuchMethodException | IllegalAccessException | IllegalArgumentException | TypeNotPresentException e) {
jaroslav@1646
   812
                throw newInternalError(e);
jaroslav@1646
   813
            }
jaroslav@1646
   814
        }
jaroslav@1646
   815
jaroslav@1646
   816
        /**
jaroslav@1646
   817
         * Wrap a constructor call in a {@link LambdaForm}.
jaroslav@1646
   818
         *
jaroslav@1646
   819
         * If constructors ({@code <init>} methods) are called in LFs, problems might arise if the LFs
jaroslav@1646
   820
         * are turned into bytecode, because the call to the allocator is routed through an MH, and the
jaroslav@1646
   821
         * verifier cannot find a {@code NEW} instruction preceding the {@code INVOKESPECIAL} to
jaroslav@1646
   822
         * {@code <init>}. To avoid this, we add an indirection by invoking {@code <init>} through
jaroslav@1646
   823
         * {@link MethodHandle#linkToSpecial}.
jaroslav@1646
   824
         *
jaroslav@1646
   825
         * The last {@link LambdaForm.Name Name} in the argument's form is expected to be the {@code void}
jaroslav@1646
   826
         * result of the {@code <init>} invocation. This entry is replaced.
jaroslav@1646
   827
         */
jaroslav@1646
   828
        private static MethodHandle linkConstructor(MethodHandle cmh) {
jaroslav@1646
   829
            final LambdaForm lf = cmh.form;
jaroslav@1646
   830
            final int initNameIndex = lf.names.length - 1;
jaroslav@1646
   831
            final Name initName = lf.names[initNameIndex];
jaroslav@1646
   832
            final MemberName ctorMN = initName.function.member;
jaroslav@1646
   833
            final MethodType ctorMT = ctorMN.getInvocationType();
jaroslav@1646
   834
jaroslav@1646
   835
            // obtain function member (call target)
jaroslav@1646
   836
            // linker method type replaces initial parameter (BMH species) with BMH to avoid naming a species (anonymous class!)
jaroslav@1646
   837
            final MethodType linkerMT = ctorMT.changeParameterType(0, BoundMethodHandle.class).appendParameterTypes(MemberName.class);
jaroslav@1646
   838
            MemberName linkerMN = new MemberName(MethodHandle.class, "linkToSpecial", linkerMT, REF_invokeStatic);
jaroslav@1646
   839
            try {
jaroslav@1646
   840
                linkerMN = MemberName.getFactory().resolveOrFail(REF_invokeStatic, linkerMN, null, NoSuchMethodException.class);
jaroslav@1646
   841
                assert(linkerMN.isStatic());
jaroslav@1646
   842
            } catch (ReflectiveOperationException ex) {
jaroslav@1646
   843
                throw newInternalError(ex);
jaroslav@1646
   844
            }
jaroslav@1646
   845
            // extend arguments array
jaroslav@1646
   846
            Object[] newArgs = Arrays.copyOf(initName.arguments, initName.arguments.length + 1);
jaroslav@1646
   847
            newArgs[newArgs.length - 1] = ctorMN;
jaroslav@1646
   848
            // replace function
jaroslav@1646
   849
            final NamedFunction nf = new NamedFunction(linkerMN);
jaroslav@1646
   850
            final Name linkedCtor = new Name(nf, newArgs);
jaroslav@1646
   851
            linkedCtor.initIndex(initNameIndex);
jaroslav@1646
   852
            lf.names[initNameIndex] = linkedCtor;
jaroslav@1646
   853
            return cmh;
jaroslav@1646
   854
        }
jaroslav@1646
   855
jaroslav@1646
   856
    }
jaroslav@1646
   857
jaroslav@1646
   858
    private static final Lookup LOOKUP = Lookup.IMPL_LOOKUP;
jaroslav@1646
   859
jaroslav@1646
   860
    /**
jaroslav@1646
   861
     * All subclasses must provide such a value describing their type signature.
jaroslav@1646
   862
     */
jaroslav@1646
   863
    static final SpeciesData SPECIES_DATA = SpeciesData.EMPTY;
jaroslav@1646
   864
}