AdapterMethodHandle.java 57.2 KB
Newer Older
1
/*
2
 * Copyright (c) 2008, 2011, Oracle and/or its affiliates. All rights reserved.
3 4 5 6
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * 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 12 13 14 15 16 17 18 19 20
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
21 22 23
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 * or visit www.oracle.com if you need additional information or have any
 * questions.
24 25
 */

26
package java.lang.invoke;
27

28 29
import sun.invoke.util.VerifyType;
import sun.invoke.util.Wrapper;
30
import sun.invoke.util.ValueConversions;
31
import java.util.Arrays;
32 33
import java.util.ArrayList;
import java.util.Collections;
34 35
import static java.lang.invoke.MethodHandleNatives.Constants.*;
import static java.lang.invoke.MethodHandleStatics.*;
36 37 38 39 40

/**
 * This method handle performs simple conversion or checking of a single argument.
 * @author jrose
 */
41
class AdapterMethodHandle extends BoundMethodHandle {
42 43 44 45 46 47 48 49 50 51 52

    //MethodHandle vmtarget;   // next AMH or BMH in chain or final DMH
    //Object       argument;   // parameter to the conversion if needed
    //int          vmargslot;  // which argument slot is affected
    private final int conversion;  // the type of conversion: RETYPE_ONLY, etc.

    // Constructors in this class *must* be package scoped or private.
    private AdapterMethodHandle(MethodHandle target, MethodType newType,
                long conv, Object convArg) {
        super(newType, convArg, newType.parameterSlotDepth(1+convArgPos(conv)));
        this.conversion = convCode(conv);
53 54
        // JVM might update VM-specific bits of conversion (ignore)
        MethodHandleNatives.init(this, target, convArgPos(conv));
55
    }
56
    AdapterMethodHandle(MethodHandle target, MethodType newType,
57 58 59 60
                long conv) {
        this(target, newType, conv, null);
    }

61 62
    int getConversion() { return conversion; }

63 64 65 66
    // TO DO:  When adapting another MH with a null conversion, clone
    // the target and change its type, instead of adding another layer.

    /** Can a JVM-level adapter directly implement the proposed
67
     *  argument conversions, as if by fixed-arity MethodHandle.asType?
68
     */
69
    static boolean canPairwiseConvert(MethodType newType, MethodType oldType, int level) {
70 71 72 73 74
        // same number of args, of course
        int len = newType.parameterCount();
        if (len != oldType.parameterCount())
            return false;

75
        // Check return type.
76 77
        Class<?> exp = newType.returnType();
        Class<?> ret = oldType.returnType();
78 79 80 81 82 83
        if (!VerifyType.isNullConversion(ret, exp)) {
            if (!convOpSupported(OP_COLLECT_ARGS))
                return false;
            if (!canConvertArgument(ret, exp, level))
                return false;
        }
84 85 86 87 88

        // Check args pairwise.
        for (int i = 0; i < len; i++) {
            Class<?> src = newType.parameterType(i); // source type
            Class<?> dst = oldType.parameterType(i); // destination type
89
            if (!canConvertArgument(src, dst, level))
90 91 92 93 94 95 96
                return false;
        }

        return true;
    }

    /** Can a JVM-level adapter directly implement the proposed
97
     *  argument conversion, as if by fixed-arity MethodHandle.asType?
98
     */
99
    static boolean canConvertArgument(Class<?> src, Class<?> dst, int level) {
100 101 102 103
        // ? Retool this logic to use RETYPE_ONLY, CHECK_CAST, etc., as opcodes,
        // so we don't need to repeat so much decision making.
        if (VerifyType.isNullConversion(src, dst)) {
            return true;
104 105 106
        } else if (convOpSupported(OP_COLLECT_ARGS)) {
            // If we can build filters, we can convert anything to anything.
            return true;
107 108 109 110 111 112 113
        } else if (src.isPrimitive()) {
            if (dst.isPrimitive())
                return canPrimCast(src, dst);
            else
                return canBoxArgument(src, dst);
        } else {
            if (dst.isPrimitive())
114
                return canUnboxArgument(src, dst, level);
115 116 117 118 119 120 121 122 123
            else
                return true;  // any two refs can be interconverted
        }
    }

    /**
     * Create a JVM-level adapter method handle to conform the given method
     * handle to the similar newType, using only pairwise argument conversions.
     * For each argument, convert incoming argument to the exact type needed.
124
     * The argument conversions allowed are casting, boxing and unboxing,
125 126 127
     * integral widening or narrowing, and floating point widening or narrowing.
     * @param newType required call type
     * @param target original method handle
128
     * @param level which strength of conversion is allowed
129 130 131 132
     * @return an adapter to the original handle with the desired new type,
     *          or the original target if the types are already identical
     *          or null if the adaptation cannot be made
     */
133
    static MethodHandle makePairwiseConvert(MethodType newType, MethodHandle target, int level) {
134 135 136
        MethodType oldType = target.type();
        if (newType == oldType)  return target;

137
        if (!canPairwiseConvert(newType, oldType, level))
138 139 140 141 142 143 144 145
            return null;
        // (after this point, it is an assertion error to fail to convert)

        // Find last non-trivial conversion (if any).
        int lastConv = newType.parameterCount()-1;
        while (lastConv >= 0) {
            Class<?> src = newType.parameterType(lastConv); // source type
            Class<?> dst = oldType.parameterType(lastConv); // destination type
146
            if (isTrivialConversion(src, dst, level)) {
147 148 149 150 151
                --lastConv;
            } else {
                break;
            }
        }
152 153 154

        Class<?> needReturn = newType.returnType();
        Class<?> haveReturn = oldType.returnType();
155
        boolean retConv = !isTrivialConversion(haveReturn, needReturn, level);
156

157
        // Now build a chain of one or more adapters.
158 159
        MethodHandle adapter = target, adapter2;
        MethodType midType = oldType;
160 161 162
        for (int i = 0; i <= lastConv; i++) {
            Class<?> src = newType.parameterType(i); // source type
            Class<?> dst = midType.parameterType(i); // destination type
163
            if (isTrivialConversion(src, dst, level)) {
164 165 166 167
                // do nothing: difference is trivial
                continue;
            }
            // Work the current type backward toward the desired caller type:
168 169
            midType = midType.changeParameterType(i, src);
            if (i == lastConv) {
170 171
                // When doing the last (or only) real conversion,
                // force all remaining null conversions to happen also.
172 173 174 175
                MethodType lastMidType = newType;
                if (retConv)  lastMidType = lastMidType.changeReturnType(haveReturn);
                assert(VerifyType.isNullConversion(lastMidType, midType));
                midType = lastMidType;
176 177 178 179 180 181
            }

            // Tricky case analysis follows.
            // It parallels canConvertArgument() above.
            if (src.isPrimitive()) {
                if (dst.isPrimitive()) {
182
                    adapter2 = makePrimCast(midType, adapter, i, dst);
183
                } else {
184
                    adapter2 = makeBoxArgument(midType, adapter, i, src);
185 186 187 188 189 190 191 192 193
                }
            } else {
                if (dst.isPrimitive()) {
                    // Caller has boxed a primitive.  Unbox it for the target.
                    // The box type must correspond exactly to the primitive type.
                    // This is simpler than the powerful set of widening
                    // conversions supported by reflect.Method.invoke.
                    // Those conversions require a big nest of if/then/else logic,
                    // which we prefer to make a user responsibility.
194
                    adapter2 = makeUnboxArgument(midType, adapter, i, dst, level);
195 196 197 198 199
                } else {
                    // Simple reference conversion.
                    // Note:  Do not check for a class hierarchy relation
                    // between src and dst.  In all cases a 'null' argument
                    // will pass the cast conversion.
200
                    adapter2 = makeCheckCast(midType, adapter, i, dst);
201 202
                }
            }
203 204 205 206 207 208 209 210
            assert(adapter2 != null) : Arrays.asList(src, dst, midType, adapter, i, target, newType);
            assert(adapter2.type() == midType);
            adapter = adapter2;
        }
        if (retConv) {
            adapter2 = makeReturnConversion(adapter, haveReturn, needReturn);
            assert(adapter2 != null);
            adapter = adapter2;
211 212 213
        }
        if (adapter.type() != newType) {
            // Only trivial conversions remain.
214 215 216
            adapter2 = makeRetypeOnly(newType, adapter);
            assert(adapter2 != null);
            adapter = adapter2;
217
            // Actually, that's because there were no non-trivial ones:
218
            assert(lastConv == -1 || retConv);
219 220 221 222 223
        }
        assert(adapter.type() == newType);
        return adapter;
    }

224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239
    private static boolean isTrivialConversion(Class<?> src, Class<?> dst, int level) {
        if (src == dst || dst == void.class)  return true;
        if (!VerifyType.isNullConversion(src, dst))  return false;
        if (level > 1)  return true;  // explicitCastArguments
        boolean sp = src.isPrimitive();
        boolean dp = dst.isPrimitive();
        if (sp != dp)  return false;
        if (sp) {
            // in addition to being a null conversion, forbid boolean->int etc.
            return Wrapper.forPrimitiveType(dst)
                    .isConvertibleFrom(Wrapper.forPrimitiveType(src));
        } else {
            return dst.isAssignableFrom(src);
        }
    }

240 241 242 243 244 245 246 247 248 249 250 251 252
    private static MethodHandle makeReturnConversion(MethodHandle target, Class<?> haveReturn, Class<?> needReturn) {
        MethodHandle adjustReturn;
        if (haveReturn == void.class) {
            // synthesize a zero value for the given void
            Object zero = Wrapper.forBasicType(needReturn).zero();
            adjustReturn = MethodHandles.constant(needReturn, zero);
        } else {
            MethodType needConversion = MethodType.methodType(needReturn, haveReturn);
            adjustReturn = MethodHandles.identity(needReturn).asType(needConversion);
        }
        return makeCollectArguments(adjustReturn, target, 0, false);
    }

253 254 255 256 257 258 259 260 261 262 263 264
    /**
     * Create a JVM-level adapter method handle to permute the arguments
     * of the given method.
     * @param newType required call type
     * @param target original method handle
     * @param argumentMap for each target argument, position of its source in newType
     * @return an adapter to the original handle with the desired new type,
     *          or the original target if the types are already identical
     *          and the permutation is null
     * @throws IllegalArgumentException if the adaptation cannot be made
     *          directly by a JVM-level adapter, without help from Java code
     */
265
    static MethodHandle makePermutation(MethodType newType, MethodHandle target,
266 267 268 269 270 271 272 273 274 275 276 277 278 279
                int[] argumentMap) {
        MethodType oldType = target.type();
        boolean nullPermutation = true;
        for (int i = 0; i < argumentMap.length; i++) {
            int pos = argumentMap[i];
            if (pos != i)
                nullPermutation = false;
            if (pos < 0 || pos >= newType.parameterCount()) {
                argumentMap = new int[0]; break;
            }
        }
        if (argumentMap.length != oldType.parameterCount())
            throw newIllegalArgumentException("bad permutation: "+Arrays.toString(argumentMap));
        if (nullPermutation) {
280
            MethodHandle res = makePairwiseConvert(newType, target, 0);
281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347
            // well, that was easy
            if (res == null)
                throw newIllegalArgumentException("cannot convert pairwise: "+newType);
            return res;
        }

        // Check return type.  (Not much can be done with it.)
        Class<?> exp = newType.returnType();
        Class<?> ret = oldType.returnType();
        if (!VerifyType.isNullConversion(ret, exp))
            throw newIllegalArgumentException("bad return conversion for "+newType);

        // See if the argument types match up.
        for (int i = 0; i < argumentMap.length; i++) {
            int j = argumentMap[i];
            Class<?> src = newType.parameterType(j);
            Class<?> dst = oldType.parameterType(i);
            if (!VerifyType.isNullConversion(src, dst))
                throw newIllegalArgumentException("bad argument #"+j+" conversion for "+newType);
        }

        // Now figure out a nice mix of SWAP, ROT, DUP, and DROP adapters.
        // A workable greedy algorithm is as follows:
        // Drop unused outgoing arguments (right to left: shallowest first).
        // Duplicate doubly-used outgoing arguments (left to right: deepest first).
        // Then the remaining problem is a true argument permutation.
        // Marshal the outgoing arguments as required from left to right.
        // That is, find the deepest outgoing stack position that does not yet
        // have the correct argument value, and correct at least that position
        // by swapping or rotating in the misplaced value (from a shallower place).
        // If the misplaced value is followed by one or more consecutive values
        // (also misplaced)  issue a rotation which brings as many as possible
        // into position.  Otherwise make progress with either a swap or a
        // rotation.  Prefer the swap as cheaper, but do not use it if it
        // breaks a slot pair.  Prefer the rotation over the swap if it would
        // preserve more consecutive values shallower than the target position.
        // When more than one rotation will work (because the required value
        // is already adjacent to the target position), then use a rotation
        // which moves the old value in the target position adjacent to
        // one of its consecutive values.  Also, prefer shorter rotation
        // spans, since they use fewer memory cycles for shuffling.

        throw new UnsupportedOperationException("NYI");
    }

    private static byte basicType(Class<?> type) {
        if (type == null)  return T_VOID;
        switch (Wrapper.forBasicType(type)) {
            case BOOLEAN:  return T_BOOLEAN;
            case CHAR:     return T_CHAR;
            case FLOAT:    return T_FLOAT;
            case DOUBLE:   return T_DOUBLE;
            case BYTE:     return T_BYTE;
            case SHORT:    return T_SHORT;
            case INT:      return T_INT;
            case LONG:     return T_LONG;
            case OBJECT:   return T_OBJECT;
            case VOID:     return T_VOID;
        }
        return 99; // T_ILLEGAL or some such
    }

    /** Number of stack slots for the given type.
     *  Two for T_DOUBLE and T_FLOAT, one for the rest.
     */
    private static int type2size(int type) {
        assert(type >= T_BOOLEAN && type <= T_OBJECT);
348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363
        return (type == T_LONG || type == T_DOUBLE) ? 2 : 1;
    }
    private static int type2size(Class<?> type) {
        return type2size(basicType(type));
    }

    /** The given stackMove is the number of slots pushed.
     * It might be negative.  Scale it (multiply) by the
     * VM's notion of how an address changes with a push,
     * to get the raw SP change for stackMove.
     * Then shift and mask it into the correct field.
     */
    private static long insertStackMove(int stackMove) {
        // following variable must be long to avoid sign extension after '<<'
        long spChange = stackMove * MethodHandleNatives.JVM_STACK_MOVE_UNIT;
        return (spChange & CONV_STACK_MOVE_MASK) << CONV_STACK_MOVE_SHIFT;
364 365
    }

366 367 368 369 370 371 372 373 374 375 376 377 378 379
    static int extractStackMove(int convOp) {
        int spChange = convOp >> CONV_STACK_MOVE_SHIFT;
        return spChange / MethodHandleNatives.JVM_STACK_MOVE_UNIT;
    }

    static int extractStackMove(MethodHandle target) {
        if (target instanceof AdapterMethodHandle) {
            AdapterMethodHandle amh = (AdapterMethodHandle) target;
            return extractStackMove(amh.getConversion());
        } else {
            return 0;
        }
    }

380 381
    /** Construct an adapter conversion descriptor for a single-argument conversion. */
    private static long makeConv(int convOp, int argnum, int src, int dest) {
382 383 384
        assert(src  == (src  & CONV_TYPE_MASK));
        assert(dest == (dest & CONV_TYPE_MASK));
        assert(convOp >= OP_CHECK_CAST && convOp <= OP_PRIM_TO_REF || convOp == OP_COLLECT_ARGS);
385
        int stackMove = type2size(dest) - type2size(src);
386 387 388 389
        return ((long) argnum << 32 |
                (long) convOp << CONV_OP_SHIFT |
                (int)  src    << CONV_SRC_TYPE_SHIFT |
                (int)  dest   << CONV_DEST_TYPE_SHIFT |
390
                insertStackMove(stackMove)
391 392
                );
    }
393 394 395
    private static long makeDupConv(int convOp, int argnum, int stackMove) {
        // simple argument motion, requiring one slot to specify
        assert(convOp == OP_DUP_ARGS || convOp == OP_DROP_ARGS);
396 397 398 399 400
        byte src = 0, dest = 0;
        return ((long) argnum << 32 |
                (long) convOp << CONV_OP_SHIFT |
                (int)  src    << CONV_SRC_TYPE_SHIFT |
                (int)  dest   << CONV_DEST_TYPE_SHIFT |
401 402 403
                insertStackMove(stackMove)
                );
    }
404
    private static long makeSwapConv(int convOp, int srcArg, byte srcType, int destSlot, byte destType) {
405 406
        // more complex argument motion, requiring two slots to specify
        assert(convOp == OP_SWAP_ARGS || convOp == OP_ROT_ARGS);
407 408
        return ((long) srcArg << 32 |
                (long) convOp << CONV_OP_SHIFT |
409 410
                (int)  srcType << CONV_SRC_TYPE_SHIFT |
                (int)  destType << CONV_DEST_TYPE_SHIFT |
411
                (int)  destSlot << CONV_VMINFO_SHIFT
412 413
                );
    }
414 415 416 417 418 419 420 421 422 423 424 425
    private static long makeSpreadConv(int convOp, int argnum, int src, int dest, int stackMove) {
        // spreading or collecting, at a particular slot location
        assert(convOp == OP_SPREAD_ARGS || convOp == OP_COLLECT_ARGS || convOp == OP_FOLD_ARGS);
        // src  = spread ? T_OBJECT (for array)  : common type of collected args (else void)
        // dest = spread ? element type of array : result type of collector (can be void)
        return ((long) argnum << 32 |
                (long) convOp << CONV_OP_SHIFT |
                (int)  src    << CONV_SRC_TYPE_SHIFT |
                (int)  dest   << CONV_DEST_TYPE_SHIFT |
                insertStackMove(stackMove)
                );
    }
426
    static long makeConv(int convOp) {
427 428
        assert(convOp == OP_RETYPE_ONLY || convOp == OP_RETYPE_RAW);
        return ((long)-1 << 32) | (convOp << CONV_OP_SHIFT);   // stackMove, src, dst all zero
429 430 431 432 433 434 435 436 437
    }
    private static int convCode(long conv) {
        return (int)conv;
    }
    private static int convArgPos(long conv) {
        return (int)(conv >>> 32);
    }
    private static boolean convOpSupported(int convOp) {
        assert(convOp >= 0 && convOp <= CONV_OP_LIMIT);
438
        return ((1<<convOp) & MethodHandleNatives.CONV_OP_IMPLEMENTED_MASK) != 0;
439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484
    }

    /** One of OP_RETYPE_ONLY, etc. */
    int conversionOp() { return (conversion & CONV_OP_MASK) >> CONV_OP_SHIFT; }

    /* Return one plus the position of the first non-trivial difference
     * between the given types.  This is not a symmetric operation;
     * we are considering adapting the targetType to adapterType.
     * Trivial differences are those which could be ignored by the JVM
     * without subverting the verifier.  Otherwise, adaptable differences
     * are ones for which we could create an adapter to make the type change.
     * Return zero if there are no differences (other than trivial ones).
     * Return 1+N if N is the only adaptable argument difference.
     * Return the -2-N where N is the first of several adaptable
     * argument differences.
     * Return -1 if there there are differences which are not adaptable.
     */
    private static int diffTypes(MethodType adapterType,
                                 MethodType targetType,
                                 boolean raw) {
        int diff;
        diff = diffReturnTypes(adapterType, targetType, raw);
        if (diff != 0)  return diff;
        int nargs = adapterType.parameterCount();
        if (nargs != targetType.parameterCount())
            return -1;
        diff = diffParamTypes(adapterType, 0, targetType, 0, nargs, raw);
        //System.out.println("diff "+adapterType);
        //System.out.println("  "+diff+" "+targetType);
        return diff;
    }
    private static int diffReturnTypes(MethodType adapterType,
                                       MethodType targetType,
                                       boolean raw) {
        Class<?> src = targetType.returnType();
        Class<?> dst = adapterType.returnType();
        if ((!raw
             ? VerifyType.canPassUnchecked(src, dst)
             : VerifyType.canPassRaw(src, dst)
             ) > 0)
            return 0;  // no significant difference
        if (raw && !src.isPrimitive() && !dst.isPrimitive())
            return 0;  // can force a reference return (very carefully!)
        //if (false)  return 1;  // never adaptable!
        return -1;  // some significant difference
    }
485 486
    private static int diffParamTypes(MethodType adapterType, int astart,
                                      MethodType targetType, int tstart,
487 488 489 490
                                      int nargs, boolean raw) {
        assert(nargs >= 0);
        int res = 0;
        for (int i = 0; i < nargs; i++) {
491 492
            Class<?> src  = adapterType.parameterType(astart+i);
            Class<?> dest = targetType.parameterType(tstart+i);
493 494 495 496 497 498 499 500 501 502 503 504 505 506
            if ((!raw
                 ? VerifyType.canPassUnchecked(src, dest)
                 : VerifyType.canPassRaw(src, dest)
                ) <= 0) {
                // found a difference; is it the only one so far?
                if (res != 0)
                    return -1-res; // return -2-i for prev. i
                res = 1+i;
            }
        }
        return res;
    }

    /** Can a retyping adapter (alone) validly convert the target to newType? */
507
    static boolean canRetypeOnly(MethodType newType, MethodType targetType) {
508
        return canRetype(newType, targetType, false);
509 510 511 512 513 514 515
    }
    /** Can a retyping adapter (alone) convert the target to newType?
     *  It is allowed to widen subword types and void to int, to make bitwise
     *  conversions between float/int and double/long, and to perform unchecked
     *  reference conversions on return.  This last feature requires that the
     *  caller be trusted, and perform explicit cast conversions on return values.
     */
516
    static boolean canRetypeRaw(MethodType newType, MethodType targetType) {
517
        return canRetype(newType, targetType, true);
518
    }
519 520
    static boolean canRetype(MethodType newType, MethodType targetType, boolean raw) {
        if (!convOpSupported(raw ? OP_RETYPE_RAW : OP_RETYPE_ONLY))  return false;
521 522
        int diff = diffTypes(newType, targetType, raw);
        // %%% This assert is too strong.  Factor diff into VerifyType and reconcile.
523
        assert(raw || (diff == 0) == VerifyType.isNullConversion(newType, targetType));
524 525 526 527 528 529 530
        return diff == 0;
    }

    /** Factory method:  Performs no conversions; simply retypes the adapter.
     *  Allows unchecked argument conversions pairwise, if they are safe.
     *  Returns null if not possible.
     */
531 532
    static MethodHandle makeRetypeOnly(MethodType newType, MethodHandle target) {
        return makeRetype(newType, target, false);
533
    }
534 535
    static MethodHandle makeRetypeRaw(MethodType newType, MethodHandle target) {
        return makeRetype(newType, target, true);
536
    }
537
    static MethodHandle makeRetype(MethodType newType, MethodHandle target, boolean raw) {
538 539 540
        MethodType oldType = target.type();
        if (oldType == newType)  return target;
        if (!canRetype(newType, oldType, raw))
541 542
            return null;
        // TO DO:  clone the target guy, whatever he is, with new type.
543
        return new AdapterMethodHandle(target, newType, makeConv(raw ? OP_RETYPE_RAW : OP_RETYPE_ONLY));
544 545
    }

546
    static MethodHandle makeVarargsCollector(MethodHandle target, Class<?> arrayType) {
547 548 549 550
        MethodType type = target.type();
        int last = type.parameterCount() - 1;
        if (type.parameterType(last) != arrayType)
            target = target.asType(type.changeParameterType(last, arrayType));
551
        target = target.asFixedArity();  // make sure this attribute is turned off
552
        return new AsVarargsCollector(target, arrayType);
553 554
    }

555 556 557 558 559 560
    static class AsVarargsCollector extends AdapterMethodHandle {
        final MethodHandle target;
        final Class<?> arrayType;
        MethodHandle cache;

        AsVarargsCollector(MethodHandle target, Class<?> arrayType) {
561
            super(target, target.type(), makeConv(OP_RETYPE_ONLY));
562
            this.target = target;
563 564
            this.arrayType = arrayType;
            this.cache = target.asCollector(arrayType, 0);
565 566
        }

567 568 569 570 571
        @Override
        public boolean isVarargsCollector() {
            return true;
        }

572 573 574 575 576
        @Override
        public MethodHandle asFixedArity() {
            return target;
        }

577
        @Override
578
        public MethodHandle asType(MethodType newType) {
579 580 581 582 583 584 585 586 587 588 589 590 591 592
            MethodType type = this.type();
            int collectArg = type.parameterCount() - 1;
            int newArity = newType.parameterCount();
            if (newArity == collectArg+1 &&
                type.parameterType(collectArg).isAssignableFrom(newType.parameterType(collectArg))) {
                // if arity and trailing parameter are compatible, do normal thing
                return super.asType(newType);
            }
            // check cache
            if (cache.type().parameterCount() == newArity)
                return cache.asType(newType);
            // build and cache a collector
            int arrayLength = newArity - collectArg;
            MethodHandle collector;
593
            try {
594 595 596
                collector = target.asCollector(arrayType, arrayLength);
            } catch (IllegalArgumentException ex) {
                throw new WrongMethodTypeException("cannot build collector");
597
            }
598 599 600
            cache = collector;
            return collector.asType(newType);
        }
601 602
    }

603 604 605
    /** Can a checkcast adapter validly convert the target to newType?
     *  The JVM supports all kind of reference casts, even silly ones.
     */
606
    static boolean canCheckCast(MethodType newType, MethodType targetType,
607 608 609 610 611 612 613 614
                int arg, Class<?> castType) {
        if (!convOpSupported(OP_CHECK_CAST))  return false;
        Class<?> src = newType.parameterType(arg);
        Class<?> dst = targetType.parameterType(arg);
        if (!canCheckCast(src, castType)
                || !VerifyType.isNullConversion(castType, dst))
            return false;
        int diff = diffTypes(newType, targetType, false);
615
        return (diff == arg+1) || (diff == 0);  // arg is sole non-trivial diff
616 617
    }
    /** Can an primitive conversion adapter validly convert src to dst? */
618
    static boolean canCheckCast(Class<?> src, Class<?> dst) {
619 620 621 622 623 624 625 626
        return (!src.isPrimitive() && !dst.isPrimitive());
    }

    /** Factory method:  Forces a cast at the given argument.
     *  The castType is the target of the cast, and can be any type
     *  with a null conversion to the corresponding target parameter.
     *  Return null if this cannot be done.
     */
627
    static MethodHandle makeCheckCast(MethodType newType, MethodHandle target,
628 629 630
                int arg, Class<?> castType) {
        if (!canCheckCast(newType, target.type(), arg, castType))
            return null;
631
        long conv = makeConv(OP_CHECK_CAST, arg, T_OBJECT, T_OBJECT);
632 633 634 635 636 637 638
        return new AdapterMethodHandle(target, newType, conv, castType);
    }

    /** Can an primitive conversion adapter validly convert the target to newType?
     *  The JVM currently supports all conversions except those between
     *  floating and integral types.
     */
639
    static boolean canPrimCast(MethodType newType, MethodType targetType,
640 641 642 643 644 645 646 647 648 649 650
                int arg, Class<?> convType) {
        if (!convOpSupported(OP_PRIM_TO_PRIM))  return false;
        Class<?> src = newType.parameterType(arg);
        Class<?> dst = targetType.parameterType(arg);
        if (!canPrimCast(src, convType)
                || !VerifyType.isNullConversion(convType, dst))
            return false;
        int diff = diffTypes(newType, targetType, false);
        return (diff == arg+1);  // arg is sole non-trivial diff
    }
    /** Can an primitive conversion adapter validly convert src to dst? */
651
    static boolean canPrimCast(Class<?> src, Class<?> dst) {
652 653 654
        if (src == dst || !src.isPrimitive() || !dst.isPrimitive()) {
            return false;
        } else {
655 656 657
            boolean sflt = Wrapper.forPrimitiveType(src).isFloating();
            boolean dflt = Wrapper.forPrimitiveType(dst).isFloating();
            return !(sflt | dflt);  // no float support at present
658 659 660 661 662 663 664 665 666
        }
    }

    /** Factory method:  Truncate the given argument with zero or sign extension,
     *  and/or convert between single and doubleword versions of integer or float.
     *  The convType is the target of the conversion, and can be any type
     *  with a null conversion to the corresponding target parameter.
     *  Return null if this cannot be done.
     */
667
    static MethodHandle makePrimCast(MethodType newType, MethodHandle target,
668
                int arg, Class<?> convType) {
669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691
        Class<?> src = newType.parameterType(arg);
        if (canPrimCast(src, convType))
            return makePrimCastOnly(newType, target, arg, convType);
        Class<?> dst = convType;
        boolean sflt = Wrapper.forPrimitiveType(src).isFloating();
        boolean dflt = Wrapper.forPrimitiveType(dst).isFloating();
        if (sflt | dflt) {
            MethodHandle convMethod;
            if (sflt)
                convMethod = ((src == double.class)
                        ? ValueConversions.convertFromDouble(dst)
                        : ValueConversions.convertFromFloat(dst));
            else
                convMethod = ((dst == double.class)
                        ? ValueConversions.convertToDouble(src)
                        : ValueConversions.convertToFloat(src));
            long conv = makeConv(OP_COLLECT_ARGS, arg, basicType(src), basicType(dst));
            return new AdapterMethodHandle(target, newType, conv, convMethod);
        }
        throw new InternalError("makePrimCast");
    }
    static MethodHandle makePrimCastOnly(MethodType newType, MethodHandle target,
                int arg, Class<?> convType) {
692 693 694
        MethodType oldType = target.type();
        if (!canPrimCast(newType, oldType, arg, convType))
            return null;
695
        Class<?> src = newType.parameterType(arg);
696 697 698 699 700 701 702 703
        long conv = makeConv(OP_PRIM_TO_PRIM, arg, basicType(src), basicType(convType));
        return new AdapterMethodHandle(target, newType, conv);
    }

    /** Can an unboxing conversion validly convert src to dst?
     *  The JVM currently supports all kinds of casting and unboxing.
     *  The convType is the unboxed type; it can be either a primitive or wrapper.
     */
704
    static boolean canUnboxArgument(MethodType newType, MethodType targetType,
705
                int arg, Class<?> convType, int level) {
706 707 708 709 710 711 712 713 714 715 716 717 718
        if (!convOpSupported(OP_REF_TO_PRIM))  return false;
        Class<?> src = newType.parameterType(arg);
        Class<?> dst = targetType.parameterType(arg);
        Class<?> boxType = Wrapper.asWrapperType(convType);
        convType = Wrapper.asPrimitiveType(convType);
        if (!canCheckCast(src, boxType)
                || boxType == convType
                || !VerifyType.isNullConversion(convType, dst))
            return false;
        int diff = diffTypes(newType, targetType, false);
        return (diff == arg+1);  // arg is sole non-trivial diff
    }
    /** Can an primitive unboxing adapter validly convert src to dst? */
719 720 721 722 723 724 725 726 727 728 729 730
    static boolean canUnboxArgument(Class<?> src, Class<?> dst, int level) {
        assert(dst.isPrimitive());
        // if we have JVM support for boxing, we can also do complex unboxing
        if (convOpSupported(OP_PRIM_TO_REF))  return true;
        Wrapper dw = Wrapper.forPrimitiveType(dst);
        // Level 0 means cast and unbox.  This works on any reference.
        if (level == 0)  return !src.isPrimitive();
        assert(level >= 0 && level <= 2);
        // Levels 1 and 2 allow widening and/or narrowing conversions.
        // These are not supported directly by the JVM.
        // But if the input reference is monomorphic, we can do it.
        return dw.wrapperType() == src;
731 732 733 734 735
    }

    /** Factory method:  Unbox the given argument.
     *  Return null if this cannot be done.
     */
736
    static MethodHandle makeUnboxArgument(MethodType newType, MethodHandle target,
737
                int arg, Class<?> convType, int level) {
738 739 740 741 742
        MethodType oldType = target.type();
        Class<?> src = newType.parameterType(arg);
        Class<?> dst = oldType.parameterType(arg);
        Class<?> boxType = Wrapper.asWrapperType(convType);
        Class<?> primType = Wrapper.asPrimitiveType(convType);
743
        if (!canUnboxArgument(newType, oldType, arg, convType, level))
744 745
            return null;
        MethodType castDone = newType;
746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768
        if (!VerifyType.isNullConversion(src, boxType)) {
            // Examples:  Object->int, Number->int, Comparable->int; Byte->int, Character->int
            if (level != 0) {
                // must include additional conversions
                if (src == Object.class || !Wrapper.isWrapperType(src)) {
                    // src must be examined at runtime, to detect Byte, Character, etc.
                    MethodHandle unboxMethod = (level == 1
                                                ? ValueConversions.unbox(dst)
                                                : ValueConversions.unboxCast(dst));
                    long conv = makeConv(OP_COLLECT_ARGS, arg, basicType(src), basicType(dst));
                    return new AdapterMethodHandle(target, newType, conv, unboxMethod);
                }
                // Example: Byte->int
                // Do this by reformulating the problem to Byte->byte.
                Class<?> srcPrim = Wrapper.forWrapperType(src).primitiveType();
                MethodType midType = newType.changeParameterType(arg, srcPrim);
                MethodHandle fixPrim; // makePairwiseConvert(midType, target, 0);
                if (canPrimCast(midType, oldType, arg, dst))
                    fixPrim = makePrimCast(midType, target, arg, dst);
                else
                    fixPrim = target;
                return makeUnboxArgument(newType, fixPrim, arg, srcPrim, 0);
            }
769
            castDone = newType.changeParameterType(arg, boxType);
770
        }
771 772 773 774
        long conv = makeConv(OP_REF_TO_PRIM, arg, T_OBJECT, basicType(primType));
        MethodHandle adapter = new AdapterMethodHandle(target, castDone, conv, boxType);
        if (castDone == newType)
            return adapter;
775
        return makeCheckCast(newType, adapter, arg, boxType);
776 777
    }

778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793
    /** Can a boxing conversion validly convert src to dst? */
    static boolean canBoxArgument(MethodType newType, MethodType targetType,
                int arg, Class<?> convType) {
        if (!convOpSupported(OP_PRIM_TO_REF))  return false;
        Class<?> src = newType.parameterType(arg);
        Class<?> dst = targetType.parameterType(arg);
        Class<?> boxType = Wrapper.asWrapperType(convType);
        convType = Wrapper.asPrimitiveType(convType);
        if (!canCheckCast(boxType, dst)
                || boxType == convType
                || !VerifyType.isNullConversion(src, convType))
            return false;
        int diff = diffTypes(newType, targetType, false);
        return (diff == arg+1);  // arg is sole non-trivial diff
    }

794
    /** Can an primitive boxing adapter validly convert src to dst? */
795
    static boolean canBoxArgument(Class<?> src, Class<?> dst) {
796
        if (!convOpSupported(OP_PRIM_TO_REF))  return false;
797
        return (src.isPrimitive() && !dst.isPrimitive());
798 799
    }

800
    /** Factory method:  Box the given argument.
801 802
     *  Return null if this cannot be done.
     */
803
    static MethodHandle makeBoxArgument(MethodType newType, MethodHandle target,
804
                int arg, Class<?> convType) {
805 806 807 808 809 810 811 812 813 814 815 816 817
        MethodType oldType = target.type();
        Class<?> src = newType.parameterType(arg);
        Class<?> dst = oldType.parameterType(arg);
        Class<?> boxType = Wrapper.asWrapperType(convType);
        Class<?> primType = Wrapper.asPrimitiveType(convType);
        if (!canBoxArgument(newType, oldType, arg, convType)) {
            return null;
        }
        if (!VerifyType.isNullConversion(boxType, dst))
            target = makeCheckCast(oldType.changeParameterType(arg, boxType), target, arg, dst);
        MethodHandle boxerMethod = ValueConversions.box(Wrapper.forPrimitiveType(primType));
        long conv = makeConv(OP_PRIM_TO_REF, arg, basicType(primType), T_OBJECT);
        return new AdapterMethodHandle(target, newType, conv, boxerMethod);
818 819 820
    }

    /** Can an adapter simply drop arguments to convert the target to newType? */
821
    static boolean canDropArguments(MethodType newType, MethodType targetType,
822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847
                int dropArgPos, int dropArgCount) {
        if (dropArgCount == 0)
            return canRetypeOnly(newType, targetType);
        if (!convOpSupported(OP_DROP_ARGS))  return false;
        if (diffReturnTypes(newType, targetType, false) != 0)
            return false;
        int nptypes = newType.parameterCount();
        // parameter types must be the same up to the drop point
        if (dropArgPos != 0 && diffParamTypes(newType, 0, targetType, 0, dropArgPos, false) != 0)
            return false;
        int afterPos = dropArgPos + dropArgCount;
        int afterCount = nptypes - afterPos;
        if (dropArgPos < 0 || dropArgPos >= nptypes ||
            dropArgCount < 1 || afterPos > nptypes ||
            targetType.parameterCount() != nptypes - dropArgCount)
            return false;
        // parameter types after the drop point must also be the same
        if (afterCount != 0 && diffParamTypes(newType, afterPos, targetType, dropArgPos, afterCount, false) != 0)
            return false;
        return true;
    }

    /** Factory method:  Drop selected arguments.
     *  Allow unchecked retyping of remaining arguments, pairwise.
     *  Return null if this is not possible.
     */
848
    static MethodHandle makeDropArguments(MethodType newType, MethodHandle target,
849 850
                int dropArgPos, int dropArgCount) {
        if (dropArgCount == 0)
851
            return makeRetypeOnly(newType, target);
852 853 854 855 856 857 858 859 860 861
        if (!canDropArguments(newType, target.type(), dropArgPos, dropArgCount))
            return null;
        // in  arglist: [0: ...keep1 | dpos: drop... | dpos+dcount: keep2... ]
        // out arglist: [0: ...keep1 |                        dpos: keep2... ]
        int keep2InPos  = dropArgPos + dropArgCount;
        int dropSlot    = newType.parameterSlotDepth(keep2InPos);
        int keep1InSlot = newType.parameterSlotDepth(dropArgPos);
        int slotCount   = keep1InSlot - dropSlot;
        assert(slotCount >= dropArgCount);
        assert(target.type().parameterSlotCount() + slotCount == newType.parameterSlotCount());
862
        long conv = makeDupConv(OP_DROP_ARGS, dropArgPos + dropArgCount - 1, -slotCount);
863 864 865 866
        return new AdapterMethodHandle(target, newType, conv);
    }

    /** Can an adapter duplicate an argument to convert the target to newType? */
867
    static boolean canDupArguments(MethodType newType, MethodType targetType,
868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888
                int dupArgPos, int dupArgCount) {
        if (!convOpSupported(OP_DUP_ARGS))  return false;
        if (diffReturnTypes(newType, targetType, false) != 0)
            return false;
        int nptypes = newType.parameterCount();
        if (dupArgCount < 0 || dupArgPos + dupArgCount > nptypes)
            return false;
        if (targetType.parameterCount() != nptypes + dupArgCount)
            return false;
        // parameter types must be the same up to the duplicated arguments
        if (diffParamTypes(newType, 0, targetType, 0, nptypes, false) != 0)
            return false;
        // duplicated types must be, well, duplicates
        if (diffParamTypes(newType, dupArgPos, targetType, nptypes, dupArgCount, false) != 0)
            return false;
        return true;
    }

    /** Factory method:  Duplicate the selected argument.
     *  Return null if this is not possible.
     */
889
    static MethodHandle makeDupArguments(MethodType newType, MethodHandle target,
890 891
                int dupArgPos, int dupArgCount) {
        if (!canDupArguments(newType, target.type(), dupArgPos, dupArgCount))
892
            return null;
893 894 895 896 897 898 899 900 901
        if (dupArgCount == 0)
            return target;
        // in  arglist: [0: ...keep1 | dpos: dup... | dpos+dcount: keep2... ]
        // out arglist: [0: ...keep1 | dpos: dup... | dpos+dcount: keep2... | dup... ]
        int keep2InPos  = dupArgPos + dupArgCount;
        int dupSlot     = newType.parameterSlotDepth(keep2InPos);
        int keep1InSlot = newType.parameterSlotDepth(dupArgPos);
        int slotCount   = keep1InSlot - dupSlot;
        assert(target.type().parameterSlotCount() - slotCount == newType.parameterSlotCount());
902
        long conv = makeDupConv(OP_DUP_ARGS, dupArgPos + dupArgCount - 1, slotCount);
903 904 905 906
        return new AdapterMethodHandle(target, newType, conv);
    }

    /** Can an adapter swap two arguments to convert the target to newType? */
907
    static boolean canSwapArguments(MethodType newType, MethodType targetType,
908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933
                int swapArg1, int swapArg2) {
        if (!convOpSupported(OP_SWAP_ARGS))  return false;
        if (diffReturnTypes(newType, targetType, false) != 0)
            return false;
        if (swapArg1 >= swapArg2)  return false;  // caller resp
        int nptypes = newType.parameterCount();
        if (targetType.parameterCount() != nptypes)
            return false;
        if (swapArg1 < 0 || swapArg2 >= nptypes)
            return false;
        if (diffParamTypes(newType, 0, targetType, 0, swapArg1, false) != 0)
            return false;
        if (diffParamTypes(newType, swapArg1, targetType, swapArg2, 1, false) != 0)
            return false;
        if (diffParamTypes(newType, swapArg1+1, targetType, swapArg1+1, swapArg2-swapArg1-1, false) != 0)
            return false;
        if (diffParamTypes(newType, swapArg2, targetType, swapArg1, 1, false) != 0)
            return false;
        if (diffParamTypes(newType, swapArg2+1, targetType, swapArg2+1, nptypes-swapArg2-1, false) != 0)
            return false;
        return true;
    }

    /** Factory method:  Swap the selected arguments.
     *  Return null if this is not possible.
     */
934
    static MethodHandle makeSwapArguments(MethodType newType, MethodHandle target,
935 936 937 938
                int swapArg1, int swapArg2) {
        if (swapArg1 == swapArg2)
            return target;
        if (swapArg1 > swapArg2) { int t = swapArg1; swapArg1 = swapArg2; swapArg2 = t; }
939 940 941
        if (type2size(newType.parameterType(swapArg1)) !=
            type2size(newType.parameterType(swapArg2))) {
            // turn a swap into a pair of rotates:
942
            // [x a b c y] rot2(-1,argc=5) => [a b c y x] rot1(+1,argc=4) => target[y a b c x]
943 944 945 946 947 948
            int argc = swapArg2 - swapArg1 + 1;
            final int ROT = 1;
            ArrayList<Class<?>> rot1Params = new ArrayList<Class<?>>(target.type().parameterList());
            Collections.rotate(rot1Params.subList(swapArg1, swapArg1 + argc), -ROT);
            MethodType rot1Type = MethodType.methodType(target.type().returnType(), rot1Params);
            MethodHandle rot1 = makeRotateArguments(rot1Type, target, swapArg1, argc, +ROT);
949
            assert(rot1 != null);
950 951
            if (argc == 2)  return rot1;
            MethodHandle rot2 = makeRotateArguments(newType, rot1, swapArg1, argc-1, -ROT);
952
            assert(rot2 != null);
953 954
            return rot2;
        }
955 956
        if (!canSwapArguments(newType, target.type(), swapArg1, swapArg2))
            return null;
957 958
        Class<?> type1 = newType.parameterType(swapArg1);
        Class<?> type2 = newType.parameterType(swapArg2);
959 960 961
        // in  arglist: [0: ...keep1 | pos1: a1 | pos1+1: keep2... | pos2: a2 | pos2+1: keep3... ]
        // out arglist: [0: ...keep1 | pos1: a2 | pos1+1: keep2... | pos2: a1 | pos2+1: keep3... ]
        int swapSlot2  = newType.parameterSlotDepth(swapArg2 + 1);
962
        long conv = makeSwapConv(OP_SWAP_ARGS, swapArg1, basicType(type1), swapSlot2, basicType(type2));
963 964 965 966 967 968 969 970 971 972 973
        return new AdapterMethodHandle(target, newType, conv);
    }

    static int positiveRotation(int argCount, int rotateBy) {
        assert(argCount > 0);
        if (rotateBy >= 0) {
            if (rotateBy < argCount)
                return rotateBy;
            return rotateBy % argCount;
        } else if (rotateBy >= -argCount) {
            return rotateBy + argCount;
974
        } else {
975
            return (-1-((-1-rotateBy) % argCount)) + argCount;
976
        }
977 978 979 980 981
    }

    final static int MAX_ARG_ROTATION = 1;

    /** Can an adapter rotate arguments to convert the target to newType? */
982
    static boolean canRotateArguments(MethodType newType, MethodType targetType,
983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012
                int firstArg, int argCount, int rotateBy) {
        if (!convOpSupported(OP_ROT_ARGS))  return false;
        rotateBy = positiveRotation(argCount, rotateBy);
        if (rotateBy == 0)  return false;  // no rotation
        if (rotateBy > MAX_ARG_ROTATION && rotateBy < argCount - MAX_ARG_ROTATION)
            return false;  // too many argument positions
        // Rotate incoming args right N to the out args, N in 1..(argCouunt-1).
        if (diffReturnTypes(newType, targetType, false) != 0)
            return false;
        int nptypes = newType.parameterCount();
        if (targetType.parameterCount() != nptypes)
            return false;
        if (firstArg < 0 || firstArg >= nptypes)  return false;
        int argLimit = firstArg + argCount;
        if (argLimit > nptypes)  return false;
        if (diffParamTypes(newType, 0, targetType, 0, firstArg, false) != 0)
            return false;
        int newChunk1 = argCount - rotateBy, newChunk2 = rotateBy;
        // swap new chunk1 with target chunk2
        if (diffParamTypes(newType, firstArg, targetType, argLimit-newChunk1, newChunk1, false) != 0)
            return false;
        // swap new chunk2 with target chunk1
        if (diffParamTypes(newType, firstArg+newChunk1, targetType, firstArg, newChunk2, false) != 0)
            return false;
        return true;
    }

    /** Factory method:  Rotate the selected argument range.
     *  Return null if this is not possible.
     */
1013
    static MethodHandle makeRotateArguments(MethodType newType, MethodHandle target,
1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029
                int firstArg, int argCount, int rotateBy) {
        rotateBy = positiveRotation(argCount, rotateBy);
        if (!canRotateArguments(newType, target.type(), firstArg, argCount, rotateBy))
            return null;
        // Decide whether it should be done as a right or left rotation,
        // on the JVM stack.  Return the number of stack slots to rotate by,
        // positive if right, negative if left.
        int limit = firstArg + argCount;
        int depth0 = newType.parameterSlotDepth(firstArg);
        int depth1 = newType.parameterSlotDepth(limit-rotateBy);
        int depth2 = newType.parameterSlotDepth(limit);
        int chunk1Slots = depth0 - depth1; assert(chunk1Slots > 0);
        int chunk2Slots = depth1 - depth2; assert(chunk2Slots > 0);
        // From here on out, it assumes a single-argument shift.
        assert(MAX_ARG_ROTATION == 1);
        int srcArg, dstArg;
1030
        int dstSlot;
1031 1032
        int moveChunk;
        if (rotateBy == 1) {
1033 1034 1035 1036 1037
            // Rotate right/down N (rotateBy = +N, N small, c2 small):
            // in  arglist: [0: ...keep1 | arg1: c1...  | limit-N: c2 | limit: keep2... ]
            // out arglist: [0: ...keep1 | arg1: c2 | arg1+N: c1...   | limit: keep2... ]
            srcArg = limit-1;
            dstArg = firstArg;
1038 1039 1040
            //dstSlot = depth0 - chunk2Slots;  //chunk2Slots is not relevant
            dstSlot = depth0 + MethodHandleNatives.OP_ROT_ARGS_DOWN_LIMIT_BIAS;
            moveChunk = chunk2Slots;
1041 1042 1043 1044 1045 1046
        } else {
            // Rotate left/up N (rotateBy = -N, N small, c1 small):
            // in  arglist: [0: ...keep1 | arg1: c1 | arg1+N: c2...   | limit: keep2... ]
            // out arglist: [0: ...keep1 | arg1: c2 ... | limit-N: c1 | limit: keep2... ]
            srcArg = firstArg;
            dstArg = limit-1;
1047
            dstSlot = depth2;
1048
            moveChunk = chunk1Slots;
1049
        }
1050 1051 1052 1053
        byte srcType = basicType(newType.parameterType(srcArg));
        byte dstType = basicType(newType.parameterType(dstArg));
        assert(moveChunk == type2size(srcType));
        long conv = makeSwapConv(OP_ROT_ARGS, srcArg, srcType, dstSlot, dstType);
1054
        return new AdapterMethodHandle(target, newType, conv);
1055 1056 1057
    }

    /** Can an adapter spread an argument to convert the target to newType? */
1058
    static boolean canSpreadArguments(MethodType newType, MethodType targetType,
1059 1060 1061 1062 1063 1064 1065 1066 1067
                Class<?> spreadArgType, int spreadArgPos, int spreadArgCount) {
        if (!convOpSupported(OP_SPREAD_ARGS))  return false;
        if (diffReturnTypes(newType, targetType, false) != 0)
            return false;
        int nptypes = newType.parameterCount();
        // parameter types must be the same up to the spread point
        if (spreadArgPos != 0 && diffParamTypes(newType, 0, targetType, 0, spreadArgPos, false) != 0)
            return false;
        int afterPos = spreadArgPos + spreadArgCount;
1068
        int afterCount = nptypes - (spreadArgPos + 1);
1069 1070
        if (spreadArgPos < 0 || spreadArgPos >= nptypes ||
            spreadArgCount < 0 ||
1071
            targetType.parameterCount() != afterPos + afterCount)
1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082
            return false;
        // parameter types after the spread point must also be the same
        if (afterCount != 0 && diffParamTypes(newType, spreadArgPos+1, targetType, afterPos, afterCount, false) != 0)
            return false;
        // match the array element type to the spread arg types
        Class<?> rawSpreadArgType = newType.parameterType(spreadArgPos);
        if (rawSpreadArgType != spreadArgType && !canCheckCast(rawSpreadArgType, spreadArgType))
            return false;
        for (int i = 0; i < spreadArgCount; i++) {
            Class<?> src = VerifyType.spreadArgElementType(spreadArgType, i);
            Class<?> dst = targetType.parameterType(spreadArgPos + i);
1083
            if (src == null || !canConvertArgument(src, dst, 1))
1084 1085 1086 1087 1088
                return false;
        }
        return true;
    }

1089

1090
    /** Factory method:  Spread selected argument. */
1091
    static MethodHandle makeSpreadArguments(MethodType newType, MethodHandle target,
1092
                Class<?> spreadArgType, int spreadArgPos, int spreadArgCount) {
1093
        // FIXME: Get rid of newType; derive new arguments from structure of spreadArgType
1094
        MethodType targetType = target.type();
1095 1096 1097
        assert(canSpreadArguments(newType, targetType, spreadArgType, spreadArgPos, spreadArgCount))
            : "[newType, targetType, spreadArgType, spreadArgPos, spreadArgCount] = "
              + Arrays.asList(newType, targetType, spreadArgType, spreadArgPos, spreadArgCount);
1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110
        // dest is not significant; remove?
        int dest = T_VOID;
        for (int i = 0; i < spreadArgCount; i++) {
            Class<?> arg = VerifyType.spreadArgElementType(spreadArgType, i);
            if (arg == null)  arg = Object.class;
            int dest2 = basicType(arg);
            if      (dest == T_VOID)  dest = dest2;
            else if (dest != dest2)   dest = T_VOID;
            if (dest == T_VOID)  break;
            targetType = targetType.changeParameterType(spreadArgPos + i, arg);
        }
        target = target.asType(targetType);
        int arrayArgSize = 1;  // always a reference
1111 1112 1113
        // in  arglist: [0: ...keep1 | spos: spreadArg | spos+1:      keep2... ]
        // out arglist: [0: ...keep1 | spos: spread... | spos+scount: keep2... ]
        int keep2OutPos  = spreadArgPos + spreadArgCount;
1114 1115 1116 1117
        int keep1OutSlot = targetType.parameterSlotDepth(spreadArgPos);   // leading edge of |spread...|
        int spreadSlot   = targetType.parameterSlotDepth(keep2OutPos);    // trailing edge of |spread...|
        assert(spreadSlot == newType.parameterSlotDepth(spreadArgPos+arrayArgSize));
        int slotCount    = keep1OutSlot - spreadSlot;                     // slots in |spread...|
1118
        assert(slotCount >= spreadArgCount);
1119 1120
        int stackMove = - arrayArgSize + slotCount;  // pop array, push N slots
        long conv = makeSpreadConv(OP_SPREAD_ARGS, spreadArgPos, T_OBJECT, dest, stackMove);
1121 1122 1123
        MethodHandle res = new AdapterMethodHandle(target, newType, conv, spreadArgType);
        assert(res.type().parameterType(spreadArgPos) == spreadArgType);
        return res;
1124 1125
    }

1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187
    /** Can an adapter collect a series of arguments, replacing them by zero or one results? */
    static boolean canCollectArguments(MethodType targetType,
                MethodType collectorType, int collectArgPos, boolean retainOriginalArgs) {
        if (!convOpSupported(retainOriginalArgs ? OP_FOLD_ARGS : OP_COLLECT_ARGS))  return false;
        int collectArgCount = collectorType.parameterCount();
        Class<?> rtype = collectorType.returnType();
        assert(rtype == void.class || targetType.parameterType(collectArgPos) == rtype)
                // [(Object)Object[], (Object[])Object[], 0, 1]
                : Arrays.asList(targetType, collectorType, collectArgPos, collectArgCount)
                ;
        return true;
    }

    /** Factory method:  Collect or filter selected argument(s). */
    static MethodHandle makeCollectArguments(MethodHandle target,
                MethodHandle collector, int collectArgPos, boolean retainOriginalArgs) {
        assert(canCollectArguments(target.type(), collector.type(), collectArgPos, retainOriginalArgs));
        MethodType targetType = target.type();
        MethodType collectorType = collector.type();
        int collectArgCount = collectorType.parameterCount();
        Class<?> collectValType = collectorType.returnType();
        int collectValCount = (collectValType == void.class ? 0 : 1);
        int collectValSlots = collectorType.returnSlotCount();
        MethodType newType = targetType
                .dropParameterTypes(collectArgPos, collectArgPos+collectValCount);
        if (!retainOriginalArgs) {
            newType = newType
                .insertParameterTypes(collectArgPos, collectorType.parameterList());
        } else {
            // parameter types at the fold point must be the same
            assert(diffParamTypes(newType, collectArgPos, targetType, collectValCount, collectArgCount, false) == 0)
                : Arrays.asList(target, collector, collectArgPos, retainOriginalArgs);
        }
        // in  arglist: [0: ...keep1 | cpos: collect...  | cpos+cacount: keep2... ]
        // out arglist: [0: ...keep1 | cpos: collectVal? | cpos+cvcount: keep2... ]
        // out(retain): [0: ...keep1 | cpos: cV? coll... | cpos+cvc+cac: keep2... ]
        int keep2InPos   = collectArgPos + collectArgCount;
        int keep1InSlot  = newType.parameterSlotDepth(collectArgPos);  // leading edge of |collect...|
        int collectSlot  = newType.parameterSlotDepth(keep2InPos);     // trailing edge of |collect...|
        int slotCount    = keep1InSlot - collectSlot;                  // slots in |collect...|
        assert(slotCount >= collectArgCount);
        assert(collectSlot == targetType.parameterSlotDepth(
                collectArgPos + collectValCount + (retainOriginalArgs ? collectArgCount : 0) ));
        int dest = basicType(collectValType);
        int src = T_VOID;
        // src is not significant; remove?
        for (int i = 0; i < collectArgCount; i++) {
            int src2 = basicType(collectorType.parameterType(i));
            if      (src == T_VOID)  src = src2;
            else if (src != src2)    src = T_VOID;
            if (src == T_VOID)  break;
        }
        int stackMove = collectValSlots;  // push 0..2 results
        if (!retainOriginalArgs)  stackMove -= slotCount; // pop N arguments
        int lastCollectArg = keep2InPos-1;
        long conv = makeSpreadConv(retainOriginalArgs ? OP_FOLD_ARGS : OP_COLLECT_ARGS,
                                   lastCollectArg, src, dest, stackMove);
        MethodHandle res = new AdapterMethodHandle(target, newType, conv, collector);
        assert(res.type().parameterList().subList(collectArgPos, collectArgPos+collectArgCount)
                .equals(collector.type().parameterList()));
        return res;
    }
1188 1189

    @Override
1190
    String debugString() {
1191
        return getNameString(nonAdapter((MethodHandle)vmtarget), this);
1192 1193 1194 1195 1196 1197 1198 1199
    }

    private static MethodHandle nonAdapter(MethodHandle mh) {
        while (mh instanceof AdapterMethodHandle) {
            mh = (MethodHandle) mh.vmtarget;
        }
        return mh;
    }
1200
}