6939224: MethodHandle.invokeGeneric needs to perform the correct set of conversions

JDK changes which run atop the corresponding JVM hook

Reviewed-by: never, twisti
diff --git a/jdk/src/share/classes/java/dyn/MethodHandle.java b/jdk/src/share/classes/java/dyn/MethodHandle.java
index 4904e97..251d338 100644
--- a/jdk/src/share/classes/java/dyn/MethodHandle.java
+++ b/jdk/src/share/classes/java/dyn/MethodHandle.java
@@ -329,6 +329,7 @@
     public final Object invokeVarargs(Object... arguments) throws Throwable {
         int argc = arguments == null ? 0 : arguments.length;
         MethodType type = type();
+        if (type.parameterCount() != argc)  throw badParameterCount(type, argc);
         if (argc <= 10) {
             MethodHandle invoker = MethodHandles.invokers(type).genericInvoker();
             switch (argc) {
@@ -377,6 +378,10 @@
         return invokeVarargs(arguments.toArray());
     }
 
+    private static WrongMethodTypeException badParameterCount(MethodType type, int argc) {
+        return new WrongMethodTypeException(type+" does not take "+argc+" parameters");
+    }
+
     /*  --- this is intentionally NOT a javadoc yet ---
      * <em>PROVISIONAL API, WORK IN PROGRESS:</em>
      * Produce an adapter method handle which adapts the type of the
@@ -446,7 +451,7 @@
      * @throws IllegalArgumentException if the conversion cannot be made
      * @see MethodHandles#convertArguments
      */
-    public final MethodHandle asType(MethodType newType) {
+    public MethodHandle asType(MethodType newType) {
         return MethodHandles.convertArguments(this, newType);
     }
 
diff --git a/jdk/src/share/classes/java/dyn/MethodHandles.java b/jdk/src/share/classes/java/dyn/MethodHandles.java
index b6e8333..3e1fef7 100644
--- a/jdk/src/share/classes/java/dyn/MethodHandles.java
+++ b/jdk/src/share/classes/java/dyn/MethodHandles.java
@@ -1068,10 +1068,14 @@
         MethodType oldType = target.type();
         if (oldType.equals(newType))
             return target;
-        MethodHandle res = MethodHandleImpl.convertArguments(IMPL_TOKEN, target,
-                                                 newType, oldType, null);
+        MethodHandle res = null;
+        try {
+            res = MethodHandleImpl.convertArguments(IMPL_TOKEN, target,
+                                                    newType, oldType, null);
+        } catch (IllegalArgumentException ex) {
+        }
         if (res == null)
-            throw newIllegalArgumentException("cannot convert to "+newType+": "+target);
+            throw new WrongMethodTypeException("cannot convert to "+newType+": "+target);
         return res;
     }
 
@@ -1392,6 +1396,20 @@
         return adapter;
     }
 
+    /** Apply the given filter function to the return value of the given target.
+     */
+    /*public*/ static
+    MethodHandle filterReturnValue(MethodHandle target, MethodHandle filter) {
+        MethodType targetType = target.type();
+        MethodType filterType = filter.type();
+        if (filterType.parameterCount() != 1
+            || filterType.parameterType(0) != targetType.returnType())
+            throw newIllegalArgumentException("target and filter types do not match");
+        // FIXME: Too many nodes here.
+        MethodHandle returner = dropArguments(filter, 0, targetType.parameterList());
+        return foldArguments(returner, exactInvoker(target.type()).bindTo(target));
+    }
+
     /**
      * <em>PROVISIONAL API, WORK IN PROGRESS:</em>
      * Adapt a target method handle {@code target} by pre-processing
@@ -1434,7 +1452,7 @@
      * @return method handle which incorporates the specified argument folding logic
      * @throws IllegalArgumentException if the first argument type of
      *          {@code target} is not the same as {@code combiner}'s return type,
-     *          or if the next {@code foldArgs} argument types of {@code target}
+     *          or if the following argument types of {@code target}
      *          are not identical with the argument types of {@code combiner}
      */
     public static
@@ -1443,12 +1461,39 @@
         MethodType combinerType = combiner.type();
         int foldArgs = combinerType.parameterCount();
         boolean ok = (targetType.parameterCount() >= 1 + foldArgs);
+        if (ok && !combinerType.parameterList().equals(targetType.parameterList().subList(1, foldArgs+1)))
+            ok = false;
+        if (ok && !combinerType.returnType().equals(targetType.parameterType(0)))
+            ok = false;
         if (!ok)
             throw misMatchedTypes("target and combiner types", targetType, combinerType);
         MethodType newType = targetType.dropParameterTypes(0, 1);
         return MethodHandleImpl.foldArguments(IMPL_TOKEN, target, newType, combiner);
     }
 
+    // /**
+    //  * <em>PROVISIONAL API, WORK IN PROGRESS:</em>
+    //  * Adapt a target method handle {@code target} by pre-processing
+    //  * some of its arguments to derive a new target method handle.
+    //  * Call the new target on the original arguments.
+    //  * @param combined method handle to call initially on the incoming arguments
+    //  * @return method handle which incorporates the specified dispatching logic
+    //  * @throws IllegalArgumentException if the first argument type of
+    //  *          {@code combiner}'s return type is not {@link MethodHandle},
+    //  *          or if the next argument types of {@code target}
+    //  *          are not identical with the argument types of {@code combiner}
+    //  */
+    // public static
+    // MethodHandle dispatchArguments(MethodType targetType, MethodHandle dispatcher) {
+    //     MethodType dispatcherType = dispatcher.type();
+    //     int foldArgs = dispatcherType.parameterCount();
+    //     boolean ok = (targetType.parameterCount() >= foldArgs);
+    //     if (!ok)
+    //         throw misMatchedTypes("target and dispatcher types", targetType, dispatcherType);
+    //     MethodHandle target = exactInvoker(targetType);
+    //     return MethodHandleImpl.foldArguments(IMPL_TOKEN, target, targetType, dispatcher);
+    // }
+
     /**
      * <em>PROVISIONAL API, WORK IN PROGRESS:</em>
      * Make a method handle which adapts a target method handle,
@@ -1691,4 +1736,9 @@
         }
         return null;
     }
+
+    /*non-public*/
+    static MethodHandle withTypeHandler(MethodHandle target, MethodHandle typeHandler) {
+        return MethodHandleImpl.withTypeHandler(IMPL_TOKEN, target, typeHandler);
+    }
 }
diff --git a/jdk/src/share/classes/sun/dyn/AdapterMethodHandle.java b/jdk/src/share/classes/sun/dyn/AdapterMethodHandle.java
index fb9b7fa..65bbd37 100644
--- a/jdk/src/share/classes/sun/dyn/AdapterMethodHandle.java
+++ b/jdk/src/share/classes/sun/dyn/AdapterMethodHandle.java
@@ -478,6 +478,39 @@
         return new AdapterMethodHandle(target, newType, makeConv(raw ? OP_RETYPE_RAW : OP_RETYPE_ONLY));
     }
 
+    static MethodHandle makeTypeHandler(Access token,
+                MethodHandle target, MethodHandle typeHandler) {
+        Access.check(token);
+        return new WithTypeHandler(target, typeHandler);
+    }
+
+    static class WithTypeHandler extends AdapterMethodHandle {
+        final MethodHandle target, typeHandler;
+        WithTypeHandler(MethodHandle target, MethodHandle typeHandler) {
+            super(target, target.type(), OP_RETYPE_ONLY);
+            this.target = target;
+            this.typeHandler = typeHandler.asType(TYPE_HANDLER_TYPE);
+        }
+
+        public MethodHandle asType(MethodType newType) {
+            if (this.type() == newType)
+                return this;
+            try {
+                MethodHandle retyped = (MethodHandle) typeHandler.<MethodHandle>invokeExact(target, newType);
+                // Contract:  Must return the desired type, or throw WMT
+                if (retyped.type() != newType)
+                    throw new WrongMethodTypeException(retyped.toString());
+                return retyped;
+            } catch (Throwable ex) {
+                if (ex instanceof Error)  throw (Error)ex;
+                if (ex instanceof RuntimeException)  throw (RuntimeException)ex;
+                throw new RuntimeException(ex);
+            }
+        }
+        private static final MethodType TYPE_HANDLER_TYPE
+            = MethodType.methodType(MethodHandle.class, MethodHandle.class, MethodType.class);
+    }
+
     /** Can a checkcast adapter validly convert the target to newType?
      *  The JVM supports all kind of reference casts, even silly ones.
      */
diff --git a/jdk/src/share/classes/sun/dyn/BoundMethodHandle.java b/jdk/src/share/classes/sun/dyn/BoundMethodHandle.java
index f2ae32e..4f25262 100644
--- a/jdk/src/share/classes/sun/dyn/BoundMethodHandle.java
+++ b/jdk/src/share/classes/sun/dyn/BoundMethodHandle.java
@@ -103,7 +103,7 @@
         super(Access.TOKEN, type);
         this.argument = argument;
         this.vmargslot = vmargslot;
-        assert(this.getClass() == AdapterMethodHandle.class);
+        assert(this instanceof AdapterMethodHandle);
     }
 
     /** Initialize the current object as a Java method handle, binding it
diff --git a/jdk/src/share/classes/sun/dyn/InvokeGeneric.java b/jdk/src/share/classes/sun/dyn/InvokeGeneric.java
new file mode 100644
index 0000000..8137bb4
--- /dev/null
+++ b/jdk/src/share/classes/sun/dyn/InvokeGeneric.java
@@ -0,0 +1,160 @@
+/*
+ * Copyright (c) 2009, 2010, Oracle and/or its affiliates. All rights reserved.
+ * 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
+ * published by the Free Software Foundation.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * 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.
+ *
+ * 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.
+ */
+
+package sun.dyn;
+
+import java.dyn.*;
+import java.lang.reflect.*;
+import sun.dyn.util.*;
+
+/**
+ * Adapters which manage MethodHanndle.invokeGeneric calls.
+ * The JVM calls one of these when the exact type match fails.
+ * @author jrose
+ */
+class InvokeGeneric {
+    // erased type for the call, which originates from an invokeGeneric site
+    private final MethodType erasedCallerType;
+    // an invoker of type (MT, MH; A...) -> R
+    private final MethodHandle initialInvoker;
+
+    /** Compute and cache information for this adapter, so that it can
+     *  call out to targets of the erasure-family of the given erased type.
+     */
+    private InvokeGeneric(MethodType erasedCallerType) throws NoAccessException {
+        this.erasedCallerType = erasedCallerType;
+        this.initialInvoker = makeInitialInvoker();
+        assert initialInvoker.type().equals(erasedCallerType
+                                            .insertParameterTypes(0, MethodType.class, MethodHandle.class))
+            : initialInvoker.type();
+    }
+
+    private static MethodHandles.Lookup lookup() {
+        return MethodHandleImpl.IMPL_LOOKUP;
+    }
+
+    /** Return the adapter information for this type's erasure. */
+    static MethodHandle genericInvokerOf(MethodType type) {
+        MethodTypeImpl form = MethodTypeImpl.of(type);
+        MethodHandle genericInvoker = form.genericInvoker;
+        if (genericInvoker == null) {
+            try {
+                InvokeGeneric gen = new InvokeGeneric(form.erasedType());
+                form.genericInvoker = genericInvoker = gen.initialInvoker;
+            } catch (NoAccessException ex) {
+                throw new RuntimeException(ex);
+            }
+        }
+        return genericInvoker;
+    }
+
+    private MethodHandle makeInitialInvoker() throws NoAccessException {
+        // postDispatch = #(MH'; MT, MH; A...){MH'(MT, MH; A)}
+        MethodHandle postDispatch = makePostDispatchInvoker();
+        MethodHandle invoker;
+        if (returnConversionPossible()) {
+            invoker = MethodHandles.foldArguments(postDispatch,
+                                                  dispatcher("dispatchWithConversion"));
+        } else {
+            invoker = MethodHandles.foldArguments(postDispatch, dispatcher("dispatch"));
+        }
+        return invoker;
+    }
+
+    private static final Class<?>[] EXTRA_ARGS = { MethodType.class, MethodHandle.class };
+    private MethodHandle makePostDispatchInvoker() {
+        // Take (MH'; MT, MH; A...) and run MH'(MT, MH; A...).
+        MethodType invokerType = erasedCallerType.insertParameterTypes(0, EXTRA_ARGS);
+        return MethodHandles.exactInvoker(invokerType);
+    }
+    private MethodHandle dropDispatchArguments(MethodHandle targetInvoker) {
+        assert(targetInvoker.type().parameterType(0) == MethodHandle.class);
+        return MethodHandles.dropArguments(targetInvoker, 1, EXTRA_ARGS);
+    }
+
+    private MethodHandle dispatcher(String dispatchName) throws NoAccessException {
+        return lookup().bind(this, dispatchName,
+                             MethodType.methodType(MethodHandle.class,
+                                                   MethodType.class, MethodHandle.class));
+    }
+
+    static final boolean USE_AS_TYPE_PATH = true;
+
+    /** Return a method handle to invoke on the callerType, target, and remaining arguments.
+     *  The method handle must finish the call.
+     *  This is the first look at the caller type and target.
+     */
+    private MethodHandle dispatch(MethodType callerType, MethodHandle target) {
+        MethodType targetType = target.type();
+        if (USE_AS_TYPE_PATH || target instanceof AdapterMethodHandle.WithTypeHandler) {
+            MethodHandle newTarget = target.asType(callerType);
+            targetType = callerType;
+            Invokers invokers = MethodTypeImpl.invokers(Access.TOKEN, targetType);
+            MethodHandle invoker = invokers.erasedInvokerWithDrops;
+            if (invoker == null) {
+                invokers.erasedInvokerWithDrops = invoker =
+                    dropDispatchArguments(invokers.erasedInvoker());
+            }
+            return invoker.bindTo(newTarget);
+        }
+        throw new RuntimeException("NYI");
+    }
+
+    private MethodHandle dispatchWithConversion(MethodType callerType, MethodHandle target) {
+        MethodHandle finisher = dispatch(callerType, target);
+        if (returnConversionNeeded(callerType, target))
+            finisher = addReturnConversion(finisher, callerType.returnType());  //FIXME: slow
+        return finisher;
+    }
+
+    private boolean returnConversionPossible() {
+        Class<?> needType = erasedCallerType.returnType();
+        return !needType.isPrimitive();
+    }
+    private boolean returnConversionNeeded(MethodType callerType, MethodHandle target) {
+        Class<?> needType = callerType.returnType();
+        if (needType == erasedCallerType.returnType())
+            return false;  // no conversions possible, since must be primitive or Object
+        Class<?> haveType = target.type().returnType();
+        if (VerifyType.isNullConversion(haveType, needType))
+            return false;
+        return true;
+    }
+    private MethodHandle addReturnConversion(MethodHandle target, Class<?> type) {
+        if (true) throw new RuntimeException("NYI");
+        // FIXME: This is slow because it creates a closure node on every call that requires a return cast.
+        MethodType targetType = target.type();
+        MethodHandle caster = ValueConversions.identity(type);
+        caster = caster.asType(MethodType.methodType(type, targetType.returnType()));
+        // Drop irrelevant arguments, because we only care about the return value:
+        caster = MethodHandles.dropArguments(caster, 1, targetType.parameterList());
+        MethodHandle result = MethodHandles.foldArguments(caster, target);
+        return result.asType(target.type());
+    }
+
+    public String toString() {
+        return "InvokeGeneric"+erasedCallerType;
+    }
+}
diff --git a/jdk/src/share/classes/sun/dyn/Invokers.java b/jdk/src/share/classes/sun/dyn/Invokers.java
index b3d2823..2f2c92a 100644
--- a/jdk/src/share/classes/sun/dyn/Invokers.java
+++ b/jdk/src/share/classes/sun/dyn/Invokers.java
@@ -38,6 +38,10 @@
     // exact invoker for the outgoing call
     private /*lazy*/ MethodHandle exactInvoker;
 
+    // erased (partially untyped but with primitives) invoker for the outgoing call
+    private /*lazy*/ MethodHandle erasedInvoker;
+    /*lazy*/ MethodHandle erasedInvokerWithDrops;  // for InvokeGeneric
+
     // generic (untyped) invoker for the outgoing call
     private /*lazy*/ MethodHandle genericInvoker;
 
@@ -80,6 +84,19 @@
         return invoker;
     }
 
+    public MethodHandle erasedInvoker() {
+        MethodHandle invoker1 = exactInvoker();
+        MethodHandle invoker = erasedInvoker;
+        if (invoker != null)  return invoker;
+        MethodType erasedType = targetType.erase();
+        if (erasedType == targetType.generic())
+            invoker = genericInvoker();
+        else
+            invoker = MethodHandles.convertArguments(invoker1, invokerType(erasedType));
+        erasedInvoker = invoker;
+        return invoker;
+    }
+
     public MethodHandle varargsInvoker(int objectArgCount) {
         MethodHandle vaInvoker = varargsInvokers[objectArgCount];
         if (vaInvoker != null)  return vaInvoker;
diff --git a/jdk/src/share/classes/sun/dyn/MethodHandleImpl.java b/jdk/src/share/classes/sun/dyn/MethodHandleImpl.java
index caa96b9..49a6253 100644
--- a/jdk/src/share/classes/sun/dyn/MethodHandleImpl.java
+++ b/jdk/src/share/classes/sun/dyn/MethodHandleImpl.java
@@ -560,7 +560,9 @@
     MethodHandle bindReceiver(Access token,
                               MethodHandle target, Object receiver) {
         Access.check(token);
-        if (target instanceof AdapterMethodHandle) {
+        if (target instanceof AdapterMethodHandle &&
+            ((AdapterMethodHandle)target).conversionOp() == MethodHandleNatives.Constants.OP_RETYPE_ONLY
+            ) {
             Object info = MethodHandleNatives.getTargetInfo(target);
             if (info instanceof DirectMethodHandle) {
                 DirectMethodHandle dmh = (DirectMethodHandle) info;
@@ -1257,4 +1259,9 @@
         Access.check(token);
         return MethodHandleNatives.getBootstrap(callerClass);
     }
+
+    public static MethodHandle withTypeHandler(Access token, MethodHandle target, MethodHandle typeHandler) {
+        Access.check(token);
+        return AdapterMethodHandle.makeTypeHandler(token, target, typeHandler);
+    }
 }
diff --git a/jdk/src/share/classes/sun/dyn/MethodHandleNatives.java b/jdk/src/share/classes/sun/dyn/MethodHandleNatives.java
index 47a9a2d..3d0629d 100644
--- a/jdk/src/share/classes/sun/dyn/MethodHandleNatives.java
+++ b/jdk/src/share/classes/sun/dyn/MethodHandleNatives.java
@@ -317,6 +317,20 @@
     }
 
     /**
+     * The JVM wants to use a MethodType with invokeGeneric.  Give the runtime fair warning.
+     */
+    static void notifyGenericMethodType(MethodType type) {
+        try {
+            // Trigger adapter creation.
+            InvokeGeneric.genericInvokerOf(type);
+        } catch (Exception ex) {
+            Error err = new InternalError("Exception while resolving invokeGeneric");
+            err.initCause(ex);
+            throw err;
+        }
+    }
+
+    /**
      * The JVM is resolving a CONSTANT_MethodHandle CP entry.  And it wants our help.
      * It will make an up-call to this method.  (Do not change the name or signature.)
      */
diff --git a/jdk/src/share/classes/sun/dyn/MethodTypeImpl.java b/jdk/src/share/classes/sun/dyn/MethodTypeImpl.java
index 0a31814..059f269 100644
--- a/jdk/src/share/classes/sun/dyn/MethodTypeImpl.java
+++ b/jdk/src/share/classes/sun/dyn/MethodTypeImpl.java
@@ -48,6 +48,7 @@
     final long primCounts;              // packed prim & double counts
     final int vmslots;                  // total number of parameter slots
     final MethodType erasedType;        // the canonical erasure
+
     /*lazy*/ MethodType primsAsBoxes;   // replace prims by wrappers
     /*lazy*/ MethodType primArgsAsBoxes; // wrap args only; make raw return
     /*lazy*/ MethodType primsAsInts;    // replace prims by int/long
@@ -59,6 +60,7 @@
     /*lazy*/ FromGeneric fromGeneric;   // convert cs. w/o prims to with
     /*lazy*/ SpreadGeneric[] spreadGeneric; // expand one argument to many
     /*lazy*/ FilterGeneric filterGeneric; // convert argument(s) on the fly
+    /*lazy*/ MethodHandle genericInvoker; // hook for invokeGeneric
 
     public MethodType erasedType() {
         return erasedType;
diff --git a/jdk/src/share/classes/sun/dyn/util/ValueConversions.java b/jdk/src/share/classes/sun/dyn/util/ValueConversions.java
index f5ee5cb..aeacb9e 100644
--- a/jdk/src/share/classes/sun/dyn/util/ValueConversions.java
+++ b/jdk/src/share/classes/sun/dyn/util/ValueConversions.java
@@ -377,7 +377,7 @@
             REBOX_CONVERSIONS = newWrapperCaches(2);
 
     /**
-     * Becase we normalize primitive types to reduce the number of signatures,
+     * Because we normalize primitive types to reduce the number of signatures,
      * primitives are sometimes manipulated under an "erased" type,
      * either int (for types other than long/double) or long (for all types).
      * When the erased primitive value is then boxed into an Integer or Long,
@@ -475,10 +475,10 @@
     }
 
     private static final EnumMap<Wrapper, MethodHandle>[]
-            ZERO_CONSTANT_FUNCTIONS = newWrapperCaches(1);
+            CONSTANT_FUNCTIONS = newWrapperCaches(2);
 
     public static MethodHandle zeroConstantFunction(Wrapper wrap) {
-        EnumMap<Wrapper, MethodHandle> cache = ZERO_CONSTANT_FUNCTIONS[0];
+        EnumMap<Wrapper, MethodHandle> cache = CONSTANT_FUNCTIONS[0];
         MethodHandle mh = cache.get(wrap);
         if (mh != null) {
             return mh;
@@ -544,6 +544,24 @@
     }
 
     /**
+     * Identity function on ints.
+     * @param x an arbitrary int value
+     * @return the same value x
+     */
+    static int identity(int x) {
+        return x;
+    }
+
+    /**
+     * Identity function on longs.
+     * @param x an arbitrary long value
+     * @return the same value x
+     */
+    static long identity(long x) {
+        return x;
+    }
+
+    /**
      * Identity function, with reference cast.
      * @param t an arbitrary reference type
      * @param x an arbitrary reference value
@@ -553,7 +571,7 @@
         return t.cast(x);
     }
 
-    private static final MethodHandle IDENTITY, CAST_REFERENCE, ALWAYS_NULL, ALWAYS_ZERO, ZERO_OBJECT, IGNORE, EMPTY;
+    private static final MethodHandle IDENTITY, IDENTITY_I, IDENTITY_J, CAST_REFERENCE, ALWAYS_NULL, ALWAYS_ZERO, ZERO_OBJECT, IGNORE, EMPTY;
     static {
         try {
             MethodType idType = MethodType.genericMethodType(1);
@@ -562,6 +580,8 @@
             MethodType ignoreType = idType.changeReturnType(void.class);
             MethodType zeroObjectType = MethodType.genericMethodType(0);
             IDENTITY = IMPL_LOOKUP.findStatic(ValueConversions.class, "identity", idType);
+            IDENTITY_I = IMPL_LOOKUP.findStatic(ValueConversions.class, "identity", MethodType.methodType(int.class, int.class));
+            IDENTITY_J = IMPL_LOOKUP.findStatic(ValueConversions.class, "identity", MethodType.methodType(long.class, long.class));
             //CAST_REFERENCE = IMPL_LOOKUP.findVirtual(Class.class, "cast", idType);
             CAST_REFERENCE = IMPL_LOOKUP.findStatic(ValueConversions.class, "castReference", castType);
             ALWAYS_NULL = IMPL_LOOKUP.findStatic(ValueConversions.class, "alwaysNull", idType);
@@ -613,6 +633,49 @@
         return IDENTITY;
     }
 
+    public static MethodHandle identity(Class<?> type) {
+        if (type == Object.class)
+            return IDENTITY;
+        else if (!type.isPrimitive())
+            return retype(MethodType.methodType(type, type), IDENTITY);
+        else
+            return identity(Wrapper.forPrimitiveType(type));
+    }
+
+    static MethodHandle identity(Wrapper wrap) {
+        EnumMap<Wrapper, MethodHandle> cache = CONSTANT_FUNCTIONS[1];
+        MethodHandle mh = cache.get(wrap);
+        if (mh != null) {
+            return mh;
+        }
+        // slow path
+        MethodType type = MethodType.methodType(wrap.primitiveType(), wrap.primitiveType());
+        try {
+            mh = IMPL_LOOKUP.findStatic(ValueConversions.class, "identity", type);
+        } catch (NoAccessException ex) {
+            mh = null;
+        }
+        if (mh == null && wrap == Wrapper.VOID) {
+            mh = EMPTY;  // #(){} : #()void
+        }
+        if (mh != null) {
+            cache.put(wrap, mh);
+            return mh;
+        }
+
+        // use a raw conversion
+        if (wrap.isSingleWord() && wrap != Wrapper.INT) {
+            mh = retype(type, identity(Wrapper.INT));
+        } else if (wrap.isDoubleWord() && wrap != Wrapper.LONG) {
+            mh = retype(type, identity(Wrapper.LONG));
+        }
+        if (mh != null) {
+            cache.put(wrap, mh);
+            return mh;
+        }
+        throw new IllegalArgumentException("cannot find identity for " + wrap);
+    }
+
     private static MethodHandle retype(MethodType type, MethodHandle mh) {
         return AdapterMethodHandle.makeRetypeOnly(IMPL_TOKEN, type, mh);
     }