1 /*
   2  * Copyright (c) 2008, 2016, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 package java.lang.invoke;
  27 
  28 import jdk.internal.vm.annotation.DontInline;
  29 import jdk.internal.vm.annotation.ForceInline;
  30 import jdk.internal.vm.annotation.Stable;
  31 
  32 import java.lang.reflect.Array;
  33 import java.util.Arrays;
  34 
  35 import static java.lang.invoke.MethodHandleStatics.*;
  36 import static java.lang.invoke.MethodHandleNatives.Constants.*;
  37 import static java.lang.invoke.MethodHandles.Lookup.IMPL_LOOKUP;
  38 import static java.lang.invoke.LambdaForm.*;
  39 
  40 /**
  41  * Construction and caching of often-used invokers.
  42  * @author jrose
  43  */
  44 class Invokers {
  45     // exact type (sans leading target MH) for the outgoing call
  46     private final MethodType targetType;
  47 
  48     // Cached adapter information:
  49     private final @Stable MethodHandle[] invokers = new MethodHandle[INV_LIMIT];
  50     // Indexes into invokers:
  51     static final int
  52             INV_EXACT          =  0,  // MethodHandles.exactInvoker
  53             INV_GENERIC        =  1,  // MethodHandles.invoker (generic invocation)
  54             INV_BASIC          =  2,  // MethodHandles.basicInvoker
  55             INV_LIMIT          =  3;
  56 
  57     /** Compute and cache information common to all collecting adapters
  58      *  that implement members of the erasure-family of the given erased type.
  59      */
  60     /*non-public*/ Invokers(MethodType targetType) {
  61         this.targetType = targetType;
  62     }
  63 
  64     /*non-public*/ MethodHandle exactInvoker() {
  65         MethodHandle invoker = cachedInvoker(INV_EXACT);
  66         if (invoker != null)  return invoker;
  67         invoker = makeExactOrGeneralInvoker(true);
  68         return setCachedInvoker(INV_EXACT, invoker);
  69     }
  70 
  71     /*non-public*/ MethodHandle genericInvoker() {
  72         MethodHandle invoker = cachedInvoker(INV_GENERIC);
  73         if (invoker != null)  return invoker;
  74         invoker = makeExactOrGeneralInvoker(false);
  75         return setCachedInvoker(INV_GENERIC, invoker);
  76     }
  77 
  78     /*non-public*/ MethodHandle basicInvoker() {
  79         MethodHandle invoker = cachedInvoker(INV_BASIC);
  80         if (invoker != null)  return invoker;
  81         MethodType basicType = targetType.basicType();
  82         if (basicType != targetType) {
  83             // double cache; not used significantly
  84             return setCachedInvoker(INV_BASIC, basicType.invokers().basicInvoker());
  85         }
  86         invoker = basicType.form().cachedMethodHandle(MethodTypeForm.MH_BASIC_INV);
  87         if (invoker == null) {
  88             MemberName method = invokeBasicMethod(basicType);
  89             invoker = DirectMethodHandle.make(method);
  90             assert(checkInvoker(invoker));
  91             invoker = basicType.form().setCachedMethodHandle(MethodTypeForm.MH_BASIC_INV, invoker);
  92         }
  93         return setCachedInvoker(INV_BASIC, invoker);
  94     }
  95 
  96     private MethodHandle cachedInvoker(int idx) {
  97         return invokers[idx];
  98     }
  99 
 100     private synchronized MethodHandle setCachedInvoker(int idx, final MethodHandle invoker) {
 101         // Simulate a CAS, to avoid racy duplication of results.
 102         MethodHandle prev = invokers[idx];
 103         if (prev != null)  return prev;
 104         return invokers[idx] = invoker;
 105     }
 106 
 107     private MethodHandle makeExactOrGeneralInvoker(boolean isExact) {
 108         MethodType mtype = targetType;
 109         MethodType invokerType = mtype.invokerType();
 110         int which = (isExact ? MethodTypeForm.LF_EX_INVOKER : MethodTypeForm.LF_GEN_INVOKER);
 111         LambdaForm lform = invokeHandleForm(mtype, false, which);
 112         MethodHandle invoker = BoundMethodHandle.bindSingle(invokerType, lform, mtype);
 113         String whichName = (isExact ? "invokeExact" : "invoke");
 114         invoker = invoker.withInternalMemberName(MemberName.makeMethodHandleInvoke(whichName, mtype), false);
 115         assert(checkInvoker(invoker));
 116         maybeCompileToBytecode(invoker);
 117         return invoker;
 118     }
 119 
 120     /** If the target type seems to be common enough, eagerly compile the invoker to bytecodes. */
 121     private void maybeCompileToBytecode(MethodHandle invoker) {
 122         final int EAGER_COMPILE_ARITY_LIMIT = 10;
 123         if (targetType == targetType.erase() &&
 124             targetType.parameterCount() < EAGER_COMPILE_ARITY_LIMIT) {
 125             invoker.form.compileToBytecode();
 126         }
 127     }
 128 
 129     // This next one is called from LambdaForm.NamedFunction.<init>.
 130     /*non-public*/ static MemberName invokeBasicMethod(MethodType basicType) {
 131         assert(basicType == basicType.basicType());
 132         try {
 133             //Lookup.findVirtual(MethodHandle.class, name, type);
 134             return IMPL_LOOKUP.resolveOrFail(REF_invokeVirtual, MethodHandle.class, "invokeBasic", basicType);
 135         } catch (ReflectiveOperationException ex) {
 136             throw newInternalError("JVM cannot find invoker for "+basicType, ex);
 137         }
 138     }
 139 
 140     private boolean checkInvoker(MethodHandle invoker) {
 141         assert(targetType.invokerType().equals(invoker.type()))
 142                 : java.util.Arrays.asList(targetType, targetType.invokerType(), invoker);
 143         assert(invoker.internalMemberName() == null ||
 144                invoker.internalMemberName().getMethodType().equals(targetType));
 145         assert(!invoker.isVarargsCollector());
 146         return true;
 147     }
 148 
 149     /**
 150      * Find or create an invoker which passes unchanged a given number of arguments
 151      * and spreads the rest from a trailing array argument.
 152      * The invoker target type is the post-spread type {@code (TYPEOF(uarg*), TYPEOF(sarg*))=>RT}.
 153      * All the {@code sarg}s must have a common type {@code C}.  (If there are none, {@code Object} is assumed.}
 154      * @param leadingArgCount the number of unchanged (non-spread) arguments
 155      * @return {@code invoker.invokeExact(mh, uarg*, C[]{sarg*}) := (RT)mh.invoke(uarg*, sarg*)}
 156      */
 157     /*non-public*/ MethodHandle spreadInvoker(int leadingArgCount) {
 158         int spreadArgCount = targetType.parameterCount() - leadingArgCount;
 159         MethodType postSpreadType = targetType;
 160         Class<?> argArrayType = impliedRestargType(postSpreadType, leadingArgCount);
 161         if (postSpreadType.parameterSlotCount() <= MethodType.MAX_MH_INVOKER_ARITY) {
 162             return genericInvoker().asSpreader(argArrayType, spreadArgCount);
 163         }
 164         // Cannot build a generic invoker here of type ginvoker.invoke(mh, a*[254]).
 165         // Instead, factor sinvoker.invoke(mh, a) into ainvoker.invoke(filter(mh), a)
 166         // where filter(mh) == mh.asSpreader(Object[], spreadArgCount)
 167         MethodType preSpreadType = postSpreadType
 168             .replaceParameterTypes(leadingArgCount, postSpreadType.parameterCount(), argArrayType);
 169         MethodHandle arrayInvoker = MethodHandles.invoker(preSpreadType);
 170         MethodHandle makeSpreader = MethodHandles.insertArguments(Lazy.MH_asSpreader, 1, argArrayType, spreadArgCount);
 171         return MethodHandles.filterArgument(arrayInvoker, 0, makeSpreader);
 172     }
 173 
 174     private static Class<?> impliedRestargType(MethodType restargType, int fromPos) {
 175         if (restargType.isGeneric())  return Object[].class;  // can be nothing else
 176         int maxPos = restargType.parameterCount();
 177         if (fromPos >= maxPos)  return Object[].class;  // reasonable default
 178         Class<?> argType = restargType.parameterType(fromPos);
 179         for (int i = fromPos+1; i < maxPos; i++) {
 180             if (argType != restargType.parameterType(i))
 181                 throw newIllegalArgumentException("need homogeneous rest arguments", restargType);
 182         }
 183         if (argType == Object.class)  return Object[].class;
 184         return Array.newInstance(argType, 0).getClass();
 185     }
 186 
 187     public String toString() {
 188         return "Invokers"+targetType;
 189     }
 190 
 191     static MemberName methodHandleInvokeLinkerMethod(String name,
 192                                                      MethodType mtype,
 193                                                      Object[] appendixResult) {
 194         int which;
 195         switch (name) {
 196         case "invokeExact":  which = MethodTypeForm.LF_EX_LINKER; break;
 197         case "invoke":       which = MethodTypeForm.LF_GEN_LINKER; break;
 198         default:             throw new InternalError("not invoker: "+name);
 199         }
 200         LambdaForm lform;
 201         if (mtype.parameterSlotCount() <= MethodType.MAX_MH_ARITY - MH_LINKER_ARG_APPENDED) {
 202             lform = invokeHandleForm(mtype, false, which);
 203             appendixResult[0] = mtype;
 204         } else {
 205             lform = invokeHandleForm(mtype, true, which);
 206         }
 207         return lform.vmentry;
 208     }
 209 
 210     // argument count to account for trailing "appendix value" (typically the mtype)
 211     private static final int MH_LINKER_ARG_APPENDED = 1;
 212 
 213     /** Returns an adapter for invokeExact or generic invoke, as a MH or constant pool linker.
 214      * If !customized, caller is responsible for supplying, during adapter execution,
 215      * a copy of the exact mtype.  This is because the adapter might be generalized to
 216      * a basic type.
 217      * @param mtype the caller's method type (either basic or full-custom)
 218      * @param customized whether to use a trailing appendix argument (to carry the mtype)
 219      * @param which bit-encoded 0x01 whether it is a CP adapter ("linker") or MHs.invoker value ("invoker");
 220      *                          0x02 whether it is for invokeExact or generic invoke
 221      */
 222     private static LambdaForm invokeHandleForm(MethodType mtype, boolean customized, int which) {
 223         boolean isCached;
 224         if (!customized) {
 225             mtype = mtype.basicType();  // normalize Z to I, String to Object, etc.
 226             isCached = true;
 227         } else {
 228             isCached = false;  // maybe cache if mtype == mtype.basicType()
 229         }
 230         boolean isLinker, isGeneric;
 231         String debugName;
 232         switch (which) {
 233         case MethodTypeForm.LF_EX_LINKER:   isLinker = true;  isGeneric = false; debugName = "invokeExact_MT"; break;
 234         case MethodTypeForm.LF_EX_INVOKER:  isLinker = false; isGeneric = false; debugName = "exactInvoker"; break;
 235         case MethodTypeForm.LF_GEN_LINKER:  isLinker = true;  isGeneric = true;  debugName = "invoke_MT"; break;
 236         case MethodTypeForm.LF_GEN_INVOKER: isLinker = false; isGeneric = true;  debugName = "invoker"; break;
 237         default: throw new InternalError();
 238         }
 239         LambdaForm lform;
 240         if (isCached) {
 241             lform = mtype.form().cachedLambdaForm(which);
 242             if (lform != null)  return lform;
 243         }
 244         // exactInvokerForm (Object,Object)Object
 245         //   link with java.lang.invoke.MethodHandle.invokeBasic(MethodHandle,Object,Object)Object/invokeSpecial
 246         final int THIS_MH      = 0;
 247         final int CALL_MH      = THIS_MH + (isLinker ? 0 : 1);
 248         final int ARG_BASE     = CALL_MH + 1;
 249         final int OUTARG_LIMIT = ARG_BASE + mtype.parameterCount();
 250         final int INARG_LIMIT  = OUTARG_LIMIT + (isLinker && !customized ? 1 : 0);
 251         int nameCursor = OUTARG_LIMIT;
 252         final int MTYPE_ARG    = customized ? -1 : nameCursor++;  // might be last in-argument
 253         final int CHECK_TYPE   = nameCursor++;
 254         final int CHECK_CUSTOM = (CUSTOMIZE_THRESHOLD >= 0) ? nameCursor++ : -1;
 255         final int LINKER_CALL  = nameCursor++;
 256         MethodType invokerFormType = mtype.invokerType();
 257         if (isLinker) {
 258             if (!customized)
 259                 invokerFormType = invokerFormType.appendParameterTypes(MemberName.class);
 260         } else {
 261             invokerFormType = invokerFormType.invokerType();
 262         }
 263         Name[] names = arguments(nameCursor - INARG_LIMIT, invokerFormType);
 264         assert(names.length == nameCursor)
 265                 : Arrays.asList(mtype, customized, which, nameCursor, names.length);
 266         if (MTYPE_ARG >= INARG_LIMIT) {
 267             assert(names[MTYPE_ARG] == null);
 268             BoundMethodHandle.SpeciesData speciesData = BoundMethodHandle.speciesData_L();
 269             names[THIS_MH] = names[THIS_MH].withConstraint(speciesData);
 270             NamedFunction getter = speciesData.getterFunction(0);
 271             names[MTYPE_ARG] = new Name(getter, names[THIS_MH]);
 272             // else if isLinker, then MTYPE is passed in from the caller (e.g., the JVM)
 273         }
 274 
 275         // Make the final call.  If isGeneric, then prepend the result of type checking.
 276         MethodType outCallType = mtype.basicType();
 277         Object[] outArgs = Arrays.copyOfRange(names, CALL_MH, OUTARG_LIMIT, Object[].class);
 278         Object mtypeArg = (customized ? mtype : names[MTYPE_ARG]);
 279         if (!isGeneric) {
 280             names[CHECK_TYPE] = new Name(NF_checkExactType, names[CALL_MH], mtypeArg);
 281             // mh.invokeExact(a*):R => checkExactType(mh, TYPEOF(a*:R)); mh.invokeBasic(a*)
 282         } else {
 283             names[CHECK_TYPE] = new Name(NF_checkGenericType, names[CALL_MH], mtypeArg);
 284             // mh.invokeGeneric(a*):R => checkGenericType(mh, TYPEOF(a*:R)).invokeBasic(a*)
 285             outArgs[0] = names[CHECK_TYPE];
 286         }
 287         if (CHECK_CUSTOM != -1) {
 288             names[CHECK_CUSTOM] = new Name(NF_checkCustomized, outArgs[0]);
 289         }
 290         names[LINKER_CALL] = new Name(outCallType, outArgs);
 291         lform = new LambdaForm(debugName, INARG_LIMIT, names);
 292         if (isLinker)
 293             lform.compileToBytecode();  // JVM needs a real methodOop
 294         if (isCached)
 295             lform = mtype.form().setCachedLambdaForm(which, lform);
 296         return lform;
 297     }
 298 
 299     /*non-public*/ static
 300     WrongMethodTypeException newWrongMethodTypeException(MethodType actual, MethodType expected) {
 301         // FIXME: merge with JVM logic for throwing WMTE
 302         return new WrongMethodTypeException("expected "+expected+" but found "+actual);
 303     }
 304 
 305     /** Static definition of MethodHandle.invokeExact checking code. */
 306     /*non-public*/ static
 307     @ForceInline
 308     void checkExactType(MethodHandle mh, MethodType expected) {
 309         MethodType actual = mh.type();
 310         if (actual != expected)
 311             throw newWrongMethodTypeException(expected, actual);
 312     }
 313 
 314     /** Static definition of MethodHandle.invokeGeneric checking code.
 315      * Directly returns the type-adjusted MH to invoke, as follows:
 316      * {@code (R)MH.invoke(a*) => MH.asType(TYPEOF(a*:R)).invokeBasic(a*)}
 317      */
 318     /*non-public*/ static
 319     @ForceInline
 320     MethodHandle checkGenericType(MethodHandle mh,  MethodType expected) {
 321         return mh.asType(expected);
 322         /* Maybe add more paths here.  Possible optimizations:
 323          * for (R)MH.invoke(a*),
 324          * let MT0 = TYPEOF(a*:R), MT1 = MH.type
 325          *
 326          * if MT0==MT1 or MT1 can be safely called by MT0
 327          *  => MH.invokeBasic(a*)
 328          * if MT1 can be safely called by MT0[R := Object]
 329          *  => MH.invokeBasic(a*) & checkcast(R)
 330          * if MT1 can be safely called by MT0[* := Object]
 331          *  => checkcast(A)* & MH.invokeBasic(a*) & checkcast(R)
 332          * if a big adapter BA can be pulled out of (MT0,MT1)
 333          *  => BA.invokeBasic(MT0,MH,a*)
 334          * if a local adapter LA can cached on static CS0 = new GICS(MT0)
 335          *  => CS0.LA.invokeBasic(MH,a*)
 336          * else
 337          *  => MH.asType(MT0).invokeBasic(A*)
 338          */
 339     }
 340 
 341     static MemberName linkToCallSiteMethod(MethodType mtype) {
 342         LambdaForm lform = callSiteForm(mtype, false);
 343         return lform.vmentry;
 344     }
 345 
 346     static MemberName linkToTargetMethod(MethodType mtype) {
 347         LambdaForm lform = callSiteForm(mtype, true);
 348         return lform.vmentry;
 349     }
 350 
 351     // skipCallSite is true if we are optimizing a ConstantCallSite
 352     private static LambdaForm callSiteForm(MethodType mtype, boolean skipCallSite) {
 353         mtype = mtype.basicType();  // normalize Z to I, String to Object, etc.
 354         final int which = (skipCallSite ? MethodTypeForm.LF_MH_LINKER : MethodTypeForm.LF_CS_LINKER);
 355         LambdaForm lform = mtype.form().cachedLambdaForm(which);
 356         if (lform != null)  return lform;
 357         // exactInvokerForm (Object,Object)Object
 358         //   link with java.lang.invoke.MethodHandle.invokeBasic(MethodHandle,Object,Object)Object/invokeSpecial
 359         final int ARG_BASE     = 0;
 360         final int OUTARG_LIMIT = ARG_BASE + mtype.parameterCount();
 361         final int INARG_LIMIT  = OUTARG_LIMIT + 1;
 362         int nameCursor = OUTARG_LIMIT;
 363         final int APPENDIX_ARG = nameCursor++;  // the last in-argument
 364         final int CSITE_ARG    = skipCallSite ? -1 : APPENDIX_ARG;
 365         final int CALL_MH      = skipCallSite ? APPENDIX_ARG : nameCursor++;  // result of getTarget
 366         final int LINKER_CALL  = nameCursor++;
 367         MethodType invokerFormType = mtype.appendParameterTypes(skipCallSite ? MethodHandle.class : CallSite.class);
 368         Name[] names = arguments(nameCursor - INARG_LIMIT, invokerFormType);
 369         assert(names.length == nameCursor);
 370         assert(names[APPENDIX_ARG] != null);
 371         if (!skipCallSite)
 372             names[CALL_MH] = new Name(NF_getCallSiteTarget, names[CSITE_ARG]);
 373         // (site.)invokedynamic(a*):R => mh = site.getTarget(); mh.invokeBasic(a*)
 374         final int PREPEND_MH = 0, PREPEND_COUNT = 1;
 375         Object[] outArgs = Arrays.copyOfRange(names, ARG_BASE, OUTARG_LIMIT + PREPEND_COUNT, Object[].class);
 376         // prepend MH argument:
 377         System.arraycopy(outArgs, 0, outArgs, PREPEND_COUNT, outArgs.length - PREPEND_COUNT);
 378         outArgs[PREPEND_MH] = names[CALL_MH];
 379         names[LINKER_CALL] = new Name(mtype, outArgs);
 380         lform = new LambdaForm((skipCallSite ? "linkToTargetMethod" : "linkToCallSite"), INARG_LIMIT, names);
 381         lform.compileToBytecode();  // JVM needs a real methodOop
 382         lform = mtype.form().setCachedLambdaForm(which, lform);
 383         return lform;
 384     }
 385 
 386     /** Static definition of MethodHandle.invokeGeneric checking code. */
 387     /*non-public*/ static
 388     @ForceInline
 389     MethodHandle getCallSiteTarget(CallSite site) {
 390         return site.getTarget();
 391     }
 392 
 393     /*non-public*/ static
 394     @ForceInline
 395     void checkCustomized(MethodHandle mh) {
 396         if (MethodHandleImpl.isCompileConstant(mh)) return;
 397         if (mh.form.customized == null) {
 398             maybeCustomize(mh);
 399         }
 400     }
 401 
 402     /*non-public*/ static
 403     @DontInline
 404     void maybeCustomize(MethodHandle mh) {
 405         byte count = mh.customizationCount;
 406         if (count >= CUSTOMIZE_THRESHOLD) {
 407             mh.customize();
 408         } else {
 409             mh.customizationCount = (byte)(count+1);
 410         }
 411     }
 412 
 413     // Local constant functions:
 414     private static final NamedFunction
 415         NF_checkExactType,
 416         NF_checkGenericType,
 417         NF_getCallSiteTarget,
 418         NF_checkCustomized;
 419     static {
 420         try {
 421             NamedFunction nfs[] = {
 422                 NF_checkExactType = new NamedFunction(Invokers.class
 423                         .getDeclaredMethod("checkExactType", MethodHandle.class,  MethodType.class)),
 424                 NF_checkGenericType = new NamedFunction(Invokers.class
 425                         .getDeclaredMethod("checkGenericType", MethodHandle.class,  MethodType.class)),
 426                 NF_getCallSiteTarget = new NamedFunction(Invokers.class
 427                         .getDeclaredMethod("getCallSiteTarget", CallSite.class)),
 428                 NF_checkCustomized = new NamedFunction(Invokers.class
 429                         .getDeclaredMethod("checkCustomized", MethodHandle.class))
 430             };
 431             // Each nf must be statically invocable or we get tied up in our bootstraps.
 432             assert(InvokerBytecodeGenerator.isStaticallyInvocable(nfs));
 433         } catch (ReflectiveOperationException ex) {
 434             throw newInternalError(ex);
 435         }
 436     }
 437 
 438     private static class Lazy {
 439         private static final MethodHandle MH_asSpreader;
 440 
 441         static {
 442             try {
 443                 MH_asSpreader = IMPL_LOOKUP.findVirtual(MethodHandle.class, "asSpreader",
 444                         MethodType.methodType(MethodHandle.class, Class.class, int.class));
 445             } catch (ReflectiveOperationException ex) {
 446                 throw newInternalError(ex);
 447             }
 448         }
 449     }
 450 }