rt/emul/compact/src/main/java/java/lang/invoke/CallSite.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Sun, 10 Aug 2014 06:13:36 +0200
branchjdk8
changeset 1651 5c990ed353e9
parent 1646 c880a8a8803b
permissions -rw-r--r--
Almost compiled java.lang.invoke, except the parts that deal with Asm bytecode generator
     1 /*
     2  * Copyright (c) 2008, 2013, 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 sun.invoke.empty.Empty;
    29 import static java.lang.invoke.MethodHandleStatics.*;
    30 import static java.lang.invoke.MethodHandles.Lookup.IMPL_LOOKUP;
    31 
    32 /**
    33  * A {@code CallSite} is a holder for a variable {@link MethodHandle},
    34  * which is called its {@code target}.
    35  * An {@code invokedynamic} instruction linked to a {@code CallSite} delegates
    36  * all calls to the site's current target.
    37  * A {@code CallSite} may be associated with several {@code invokedynamic}
    38  * instructions, or it may be "free floating", associated with none.
    39  * In any case, it may be invoked through an associated method handle
    40  * called its {@linkplain #dynamicInvoker dynamic invoker}.
    41  * <p>
    42  * {@code CallSite} is an abstract class which does not allow
    43  * direct subclassing by users.  It has three immediate,
    44  * concrete subclasses that may be either instantiated or subclassed.
    45  * <ul>
    46  * <li>If a mutable target is not required, an {@code invokedynamic} instruction
    47  * may be permanently bound by means of a {@linkplain ConstantCallSite constant call site}.
    48  * <li>If a mutable target is required which has volatile variable semantics,
    49  * because updates to the target must be immediately and reliably witnessed by other threads,
    50  * a {@linkplain VolatileCallSite volatile call site} may be used.
    51  * <li>Otherwise, if a mutable target is required,
    52  * a {@linkplain MutableCallSite mutable call site} may be used.
    53  * </ul>
    54  * <p>
    55  * A non-constant call site may be <em>relinked</em> by changing its target.
    56  * The new target must have the same {@linkplain MethodHandle#type() type}
    57  * as the previous target.
    58  * Thus, though a call site can be relinked to a series of
    59  * successive targets, it cannot change its type.
    60  * <p>
    61  * Here is a sample use of call sites and bootstrap methods which links every
    62  * dynamic call site to print its arguments:
    63 <blockquote><pre>{@code
    64 static void test() throws Throwable {
    65     // THE FOLLOWING LINE IS PSEUDOCODE FOR A JVM INSTRUCTION
    66     InvokeDynamic[#bootstrapDynamic].baz("baz arg", 2, 3.14);
    67 }
    68 private static void printArgs(Object... args) {
    69   System.out.println(java.util.Arrays.deepToString(args));
    70 }
    71 private static final MethodHandle printArgs;
    72 static {
    73   MethodHandles.Lookup lookup = MethodHandles.lookup();
    74   Class thisClass = lookup.lookupClass();  // (who am I?)
    75   printArgs = lookup.findStatic(thisClass,
    76       "printArgs", MethodType.methodType(void.class, Object[].class));
    77 }
    78 private static CallSite bootstrapDynamic(MethodHandles.Lookup caller, String name, MethodType type) {
    79   // ignore caller and name, but match the type:
    80   return new ConstantCallSite(printArgs.asType(type));
    81 }
    82 }</pre></blockquote>
    83  * @author John Rose, JSR 292 EG
    84  */
    85 abstract
    86 public class CallSite {
    87     static { MethodHandleImpl.initStatics(); }
    88 
    89     // The actual payload of this call site:
    90     /*package-private*/
    91     MethodHandle target;    // Note: This field is known to the JVM.  Do not change.
    92 
    93     /**
    94      * Make a blank call site object with the given method type.
    95      * An initial target method is supplied which will throw
    96      * an {@link IllegalStateException} if called.
    97      * <p>
    98      * Before this {@code CallSite} object is returned from a bootstrap method,
    99      * it is usually provided with a more useful target method,
   100      * via a call to {@link CallSite#setTarget(MethodHandle) setTarget}.
   101      * @throws NullPointerException if the proposed type is null
   102      */
   103     /*package-private*/
   104     CallSite(MethodType type) {
   105         target = type.invokers().uninitializedCallSite();
   106     }
   107 
   108     /**
   109      * Make a call site object equipped with an initial target method handle.
   110      * @param target the method handle which will be the initial target of the call site
   111      * @throws NullPointerException if the proposed target is null
   112      */
   113     /*package-private*/
   114     CallSite(MethodHandle target) {
   115         target.type();  // null check
   116         this.target = target;
   117     }
   118 
   119     /**
   120      * Make a call site object equipped with an initial target method handle.
   121      * @param targetType the desired type of the call site
   122      * @param createTargetHook a hook which will bind the call site to the target method handle
   123      * @throws WrongMethodTypeException if the hook cannot be invoked on the required arguments,
   124      *         or if the target returned by the hook is not of the given {@code targetType}
   125      * @throws NullPointerException if the hook returns a null value
   126      * @throws ClassCastException if the hook returns something other than a {@code MethodHandle}
   127      * @throws Throwable anything else thrown by the hook function
   128      */
   129     /*package-private*/
   130     CallSite(MethodType targetType, MethodHandle createTargetHook) throws Throwable {
   131         this(targetType);
   132         ConstantCallSite selfCCS = (ConstantCallSite) this;
   133         MethodHandle boundTarget = (MethodHandle) createTargetHook.invokeWithArguments(selfCCS);
   134         checkTargetChange(this.target, boundTarget);
   135         this.target = boundTarget;
   136     }
   137 
   138     /**
   139      * Returns the type of this call site's target.
   140      * Although targets may change, any call site's type is permanent, and can never change to an unequal type.
   141      * The {@code setTarget} method enforces this invariant by refusing any new target that does
   142      * not have the previous target's type.
   143      * @return the type of the current target, which is also the type of any future target
   144      */
   145     public MethodType type() {
   146         // warning:  do not call getTarget here, because CCS.getTarget can throw IllegalStateException
   147         return target.type();
   148     }
   149 
   150     /**
   151      * Returns the target method of the call site, according to the
   152      * behavior defined by this call site's specific class.
   153      * The immediate subclasses of {@code CallSite} document the
   154      * class-specific behaviors of this method.
   155      *
   156      * @return the current linkage state of the call site, its target method handle
   157      * @see ConstantCallSite
   158      * @see VolatileCallSite
   159      * @see #setTarget
   160      * @see ConstantCallSite#getTarget
   161      * @see MutableCallSite#getTarget
   162      * @see VolatileCallSite#getTarget
   163      */
   164     public abstract MethodHandle getTarget();
   165 
   166     /**
   167      * Updates the target method of this call site, according to the
   168      * behavior defined by this call site's specific class.
   169      * The immediate subclasses of {@code CallSite} document the
   170      * class-specific behaviors of this method.
   171      * <p>
   172      * The type of the new target must be {@linkplain MethodType#equals equal to}
   173      * the type of the old target.
   174      *
   175      * @param newTarget the new target
   176      * @throws NullPointerException if the proposed new target is null
   177      * @throws WrongMethodTypeException if the proposed new target
   178      *         has a method type that differs from the previous target
   179      * @see CallSite#getTarget
   180      * @see ConstantCallSite#setTarget
   181      * @see MutableCallSite#setTarget
   182      * @see VolatileCallSite#setTarget
   183      */
   184     public abstract void setTarget(MethodHandle newTarget);
   185 
   186     void checkTargetChange(MethodHandle oldTarget, MethodHandle newTarget) {
   187         MethodType oldType = oldTarget.type();
   188         MethodType newType = newTarget.type();  // null check!
   189         if (!newType.equals(oldType))
   190             throw wrongTargetType(newTarget, oldType);
   191     }
   192 
   193     private static WrongMethodTypeException wrongTargetType(MethodHandle target, MethodType type) {
   194         return new WrongMethodTypeException(String.valueOf(target)+" should be of type "+type);
   195     }
   196 
   197     /**
   198      * Produces a method handle equivalent to an invokedynamic instruction
   199      * which has been linked to this call site.
   200      * <p>
   201      * This method is equivalent to the following code:
   202      * <blockquote><pre>{@code
   203      * MethodHandle getTarget, invoker, result;
   204      * getTarget = MethodHandles.publicLookup().bind(this, "getTarget", MethodType.methodType(MethodHandle.class));
   205      * invoker = MethodHandles.exactInvoker(this.type());
   206      * result = MethodHandles.foldArguments(invoker, getTarget)
   207      * }</pre></blockquote>
   208      *
   209      * @return a method handle which always invokes this call site's current target
   210      */
   211     public abstract MethodHandle dynamicInvoker();
   212 
   213     /*non-public*/ MethodHandle makeDynamicInvoker() {
   214         MethodHandle getTarget = GET_TARGET.bindReceiver(this);
   215         MethodHandle invoker = MethodHandles.exactInvoker(this.type());
   216         return MethodHandles.foldArguments(invoker, getTarget);
   217     }
   218 
   219     private static final MethodHandle GET_TARGET;
   220     static {
   221         try {
   222             GET_TARGET = IMPL_LOOKUP.
   223                 findVirtual(CallSite.class, "getTarget", MethodType.methodType(MethodHandle.class));
   224         } catch (ReflectiveOperationException e) {
   225             throw newInternalError(e);
   226         }
   227     }
   228 
   229     /** This guy is rolled into the default target if a MethodType is supplied to the constructor. */
   230     /*package-private*/
   231     static Empty uninitializedCallSite() {
   232         throw new IllegalStateException("uninitialized call site");
   233     }
   234 
   235     /*package-private*/
   236     void setTargetNormal(MethodHandle newTarget) {
   237         MethodHandleNatives.setCallSiteTargetNormal(this, newTarget);
   238     }
   239     /*package-private*/
   240     MethodHandle getTargetVolatile() {
   241         return target;
   242     }
   243     /*package-private*/
   244     void setTargetVolatile(MethodHandle newTarget) {
   245         MethodHandleNatives.setCallSiteTargetVolatile(this, newTarget);
   246     }
   247 
   248     // this implements the upcall from the JVM, MethodHandleNatives.makeDynamicCallSite:
   249     static CallSite makeSite(MethodHandle bootstrapMethod,
   250                              // Callee information:
   251                              String name, MethodType type,
   252                              // Extra arguments for BSM, if any:
   253                              Object info,
   254                              // Caller information:
   255                              Class<?> callerClass) {
   256         MethodHandles.Lookup caller = IMPL_LOOKUP.in(callerClass);
   257         CallSite site;
   258         try {
   259             Object binding;
   260             info = maybeReBox(info);
   261             if (info == null) {
   262                 binding = bootstrapMethod.invoke(caller, name, type);
   263             } else if (!info.getClass().isArray()) {
   264                 binding = bootstrapMethod.invoke(caller, name, type, info);
   265             } else {
   266                 Object[] argv = (Object[]) info;
   267                 maybeReBoxElements(argv);
   268                 switch (argv.length) {
   269                 case 0:
   270                     binding = bootstrapMethod.invoke(caller, name, type);
   271                     break;
   272                 case 1:
   273                     binding = bootstrapMethod.invoke(caller, name, type,
   274                                                      argv[0]);
   275                     break;
   276                 case 2:
   277                     binding = bootstrapMethod.invoke(caller, name, type,
   278                                                      argv[0], argv[1]);
   279                     break;
   280                 case 3:
   281                     binding = bootstrapMethod.invoke(caller, name, type,
   282                                                      argv[0], argv[1], argv[2]);
   283                     break;
   284                 case 4:
   285                     binding = bootstrapMethod.invoke(caller, name, type,
   286                                                      argv[0], argv[1], argv[2], argv[3]);
   287                     break;
   288                 case 5:
   289                     binding = bootstrapMethod.invoke(caller, name, type,
   290                                                      argv[0], argv[1], argv[2], argv[3], argv[4]);
   291                     break;
   292                 case 6:
   293                     binding = bootstrapMethod.invoke(caller, name, type,
   294                                                      argv[0], argv[1], argv[2], argv[3], argv[4], argv[5]);
   295                     break;
   296                 default:
   297                     final int NON_SPREAD_ARG_COUNT = 3;  // (caller, name, type)
   298                     if (NON_SPREAD_ARG_COUNT + argv.length > MethodType.MAX_MH_ARITY)
   299                         throw new BootstrapMethodError("too many bootstrap method arguments");
   300                     MethodType bsmType = bootstrapMethod.type();
   301                     MethodType invocationType = MethodType.genericMethodType(NON_SPREAD_ARG_COUNT + argv.length);
   302                     MethodHandle typedBSM = bootstrapMethod.asType(invocationType);
   303                     MethodHandle spreader = invocationType.invokers().spreadInvoker(NON_SPREAD_ARG_COUNT);
   304                     binding = spreader.invokeExact(typedBSM, (Object)caller, (Object)name, (Object)type, argv);
   305                 }
   306             }
   307             //System.out.println("BSM for "+name+type+" => "+binding);
   308             if (binding instanceof CallSite) {
   309                 site = (CallSite) binding;
   310             }  else {
   311                 throw new ClassCastException("bootstrap method failed to produce a CallSite");
   312             }
   313             if (!site.getTarget().type().equals(type))
   314                 throw new WrongMethodTypeException("wrong type: "+site.getTarget());
   315         } catch (Throwable ex) {
   316             BootstrapMethodError bex;
   317             if (ex instanceof BootstrapMethodError)
   318                 bex = (BootstrapMethodError) ex;
   319             else
   320                 bex = new BootstrapMethodError("call site initialization exception", ex);
   321             throw bex;
   322         }
   323         return site;
   324     }
   325 
   326     private static Object maybeReBox(Object x) {
   327         if (x instanceof Integer) {
   328             int xi = (int) x;
   329             if (xi == (byte) xi)
   330                 x = xi;  // must rebox; see JLS 5.1.7
   331         }
   332         return x;
   333     }
   334     private static void maybeReBoxElements(Object[] xa) {
   335         for (int i = 0; i < xa.length; i++) {
   336             xa[i] = maybeReBox(xa[i]);
   337         }
   338     }
   339 }