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.util.Wrapper;
  29 import static java.lang.invoke.MethodHandleStatics.*;
  30 import static java.lang.invoke.MethodHandleNatives.Constants.*;
  31  import static java.lang.invoke.MethodHandles.Lookup.IMPL_LOOKUP;
  32 
  33 /**
  34  * Shared information for a group of method types, which differ
  35  * only by reference types, and therefore share a common erasure
  36  * and wrapping.
  37  * <p>
  38  * For an empirical discussion of the structure of method types,
  39  * see <a href="http://groups.google.com/group/jvm-languages/browse_thread/thread/ac9308ae74da9b7e/">
  40  * the thread "Avoiding Boxing" on jvm-languages</a>.
  41  * There are approximately 2000 distinct erased method types in the JDK.
  42  * There are a little over 10 times that number of unerased types.
  43  * No more than half of these are likely to be loaded at once.
  44  * @author John Rose
  45  */
  46 final class MethodTypeForm {
  47     final int[] argToSlotTable, slotToArgTable;
  48     final long argCounts;               // packed slot & value counts
  49     final long primCounts;              // packed prim & double counts
  50     final int vmslots;                  // total number of parameter slots
  51     final MethodType erasedType;        // the canonical erasure
  52     final MethodType basicType;         // the canonical erasure, with primitives simplified
  53 
  54     // Cached adapter information:
  55     @Stable String typeString;           // argument type signature characters
  56     @Stable MethodHandle genericInvoker; // JVM hook for inexact invoke
  57     @Stable MethodHandle basicInvoker;   // cached instance of MH.invokeBasic
  58     @Stable MethodHandle namedFunctionInvoker; // cached helper for LF.NamedFunction
  59 
  60     // Cached lambda form information, for basic types only:
  61     final @Stable LambdaForm[] lambdaForms;
  62     // Indexes into lambdaForms:
  63     static final int
  64             LF_INVVIRTUAL     =  0,  // DMH invokeVirtual
  65             LF_INVSTATIC      =  1,
  66             LF_INVSPECIAL     =  2,
  67             LF_NEWINVSPECIAL  =  3,
  68             LF_INVINTERFACE   =  4,
  69             LF_INVSTATIC_INIT =  5,  // DMH invokeStatic with <clinit> barrier
  70             LF_INTERPRET      =  6,  // LF interpreter
  71             LF_COUNTER        =  7,  // CMH wrapper
  72             LF_REINVOKE       =  8,  // other wrapper
  73             LF_EX_LINKER      =  9,  // invokeExact_MT
  74             LF_EX_INVOKER     = 10,  // invokeExact MH
  75             LF_GEN_LINKER     = 11,
  76             LF_GEN_INVOKER    = 12,
  77             LF_CS_LINKER      = 13,  // linkToCallSite_CS
  78             LF_MH_LINKER      = 14,  // linkToCallSite_MH
  79             LF_LIMIT          = 15;
  80 
  81     public MethodType erasedType() {
  82         return erasedType;
  83     }
  84 
  85     public MethodType basicType() {
  86         return basicType;
  87     }
  88 
  89     public LambdaForm cachedLambdaForm(int which) {
  90         return lambdaForms[which];
  91     }
  92 
  93     public LambdaForm setCachedLambdaForm(int which, LambdaForm form) {
  94         // Should we perform some sort of CAS, to avoid racy duplication?
  95         return lambdaForms[which] = form;
  96     }
  97 
  98     public MethodHandle basicInvoker() {
  99         assert(erasedType == basicType) : "erasedType: " + erasedType + " != basicType: " + basicType;  // primitives must be flattened also
 100         MethodHandle invoker = basicInvoker;
 101         if (invoker != null)  return invoker;
 102         invoker = DirectMethodHandle.make(invokeBasicMethod(basicType));
 103         basicInvoker = invoker;
 104         return invoker;
 105     }
 106 
 107     // This next one is called from LambdaForm.NamedFunction.<init>.
 108     /*non-public*/ static MemberName invokeBasicMethod(MethodType basicType) {
 109         assert(basicType == basicType.basicType());
 110         try {
 111             // Do approximately the same as this public API call:
 112             //   Lookup.findVirtual(MethodHandle.class, name, type);
 113             // But bypass access and corner case checks, since we know exactly what we need.
 114             return IMPL_LOOKUP.resolveOrFail(REF_invokeVirtual, MethodHandle.class, "invokeBasic", basicType);
 115          } catch (ReflectiveOperationException ex) {
 116             throw newInternalError("JVM cannot find invoker for "+basicType, ex);
 117         }
 118     }
 119 
 120     /**
 121      * Build an MTF for a given type, which must have all references erased to Object.
 122      * This MTF will stand for that type and all un-erased variations.
 123      * Eagerly compute some basic properties of the type, common to all variations.
 124      */
 125     protected MethodTypeForm(MethodType erasedType) {
 126         this.erasedType = erasedType;
 127 
 128         Class<?>[] ptypes = erasedType.ptypes();
 129         int ptypeCount = ptypes.length;
 130         int pslotCount = ptypeCount;            // temp. estimate
 131         int rtypeCount = 1;                     // temp. estimate
 132         int rslotCount = 1;                     // temp. estimate
 133 
 134         int[] argToSlotTab = null, slotToArgTab = null;
 135 
 136         // Walk the argument types, looking for primitives.
 137         int pac = 0, lac = 0, prc = 0, lrc = 0;
 138         Class<?>[] epts = ptypes;
 139         Class<?>[] bpts = epts;
 140         for (int i = 0; i < epts.length; i++) {
 141             Class<?> pt = epts[i];
 142             if (pt != Object.class) {
 143                 ++pac;
 144                 Wrapper w = Wrapper.forPrimitiveType(pt);
 145                 if (w.isDoubleWord())  ++lac;
 146                 if (w.isSubwordOrInt() && pt != int.class) {
 147                     if (bpts == epts)
 148                         bpts = bpts.clone();
 149                     bpts[i] = int.class;
 150                 }
 151             }
 152         }
 153         pslotCount += lac;                  // #slots = #args + #longs
 154         Class<?> rt = erasedType.returnType();
 155         Class<?> bt = rt;
 156         if (rt != Object.class) {
 157             ++prc;          // even void.class counts as a prim here
 158             Wrapper w = Wrapper.forPrimitiveType(rt);
 159             if (w.isDoubleWord())  ++lrc;
 160             if (w.isSubwordOrInt() && rt != int.class)
 161                 bt = int.class;
 162             // adjust #slots, #args
 163             if (rt == void.class)
 164                 rtypeCount = rslotCount = 0;
 165             else
 166                 rslotCount += lrc;
 167         }
 168         if (epts == bpts && bt == rt) {
 169             this.basicType = erasedType;
 170         } else {
 171             this.basicType = MethodType.makeImpl(bt, bpts, true);
 172         }
 173         if (lac != 0) {
 174             int slot = ptypeCount + lac;
 175             slotToArgTab = new int[slot+1];
 176             argToSlotTab = new int[1+ptypeCount];
 177             argToSlotTab[0] = slot;  // argument "-1" is past end of slots
 178             for (int i = 0; i < epts.length; i++) {
 179                 Class<?> pt = epts[i];
 180                 Wrapper w = Wrapper.forBasicType(pt);
 181                 if (w.isDoubleWord())  --slot;
 182                 --slot;
 183                 slotToArgTab[slot] = i+1; // "+1" see argSlotToParameter note
 184                 argToSlotTab[1+i]  = slot;
 185             }
 186             assert(slot == 0);  // filled the table
 187         }
 188         this.primCounts = pack(lrc, prc, lac, pac);
 189         this.argCounts = pack(rslotCount, rtypeCount, pslotCount, ptypeCount);
 190         if (slotToArgTab == null) {
 191             int slot = ptypeCount; // first arg is deepest in stack
 192             slotToArgTab = new int[slot+1];
 193             argToSlotTab = new int[1+ptypeCount];
 194             argToSlotTab[0] = slot;  // argument "-1" is past end of slots
 195             for (int i = 0; i < ptypeCount; i++) {
 196                 --slot;
 197                 slotToArgTab[slot] = i+1; // "+1" see argSlotToParameter note
 198                 argToSlotTab[1+i]  = slot;
 199             }
 200         }
 201         this.argToSlotTable = argToSlotTab;
 202         this.slotToArgTable = slotToArgTab;
 203 
 204         if (pslotCount >= 256)  throw newIllegalArgumentException("too many arguments");
 205 
 206         // send a few bits down to the JVM:
 207         this.vmslots = parameterSlotCount();
 208 
 209         if (basicType == erasedType) {
 210             lambdaForms = new LambdaForm[LF_LIMIT];
 211         } else {
 212             lambdaForms = null;  // could be basicType.form().lambdaForms;
 213         }
 214     }
 215 
 216     private static long pack(int a, int b, int c, int d) {
 217         assert(((a|b|c|d) & ~0xFFFF) == 0);
 218         long hw = ((a << 16) | b), lw = ((c << 16) | d);
 219         return (hw << 32) | lw;
 220     }
 221     private static char unpack(long packed, int word) { // word==0 => return a, ==3 => return d
 222         assert(word <= 3);
 223         return (char)(packed >> ((3-word) * 16));
 224     }
 225 
 226     public int parameterCount() {                      // # outgoing values
 227         return unpack(argCounts, 3);
 228     }
 229     public int parameterSlotCount() {                  // # outgoing interpreter slots
 230         return unpack(argCounts, 2);
 231     }
 232     public int returnCount() {                         // = 0 (V), or 1
 233         return unpack(argCounts, 1);
 234     }
 235     public int returnSlotCount() {                     // = 0 (V), 2 (J/D), or 1
 236         return unpack(argCounts, 0);
 237     }
 238     public int primitiveParameterCount() {
 239         return unpack(primCounts, 3);
 240     }
 241     public int longPrimitiveParameterCount() {
 242         return unpack(primCounts, 2);
 243     }
 244     public int primitiveReturnCount() {                // = 0 (obj), or 1
 245         return unpack(primCounts, 1);
 246     }
 247     public int longPrimitiveReturnCount() {            // = 1 (J/D), or 0
 248         return unpack(primCounts, 0);
 249     }
 250     public boolean hasPrimitives() {
 251         return primCounts != 0;
 252     }
 253     public boolean hasNonVoidPrimitives() {
 254         if (primCounts == 0)  return false;
 255         if (primitiveParameterCount() != 0)  return true;
 256         return (primitiveReturnCount() != 0 && returnCount() != 0);
 257     }
 258     public boolean hasLongPrimitives() {
 259         return (longPrimitiveParameterCount() | longPrimitiveReturnCount()) != 0;
 260     }
 261     public int parameterToArgSlot(int i) {
 262         return argToSlotTable[1+i];
 263     }
 264     public int argSlotToParameter(int argSlot) {
 265         // Note:  Empty slots are represented by zero in this table.
 266         // Valid arguments slots contain incremented entries, so as to be non-zero.
 267         // We return -1 the caller to mean an empty slot.
 268         return slotToArgTable[argSlot] - 1;
 269     }
 270 
 271     static MethodTypeForm findForm(MethodType mt) {
 272         MethodType erased = canonicalize(mt, ERASE, ERASE);
 273         if (erased == null) {
 274             // It is already erased.  Make a new MethodTypeForm.
 275             return new MethodTypeForm(mt);
 276         } else {
 277             // Share the MethodTypeForm with the erased version.
 278             return erased.form();
 279         }
 280     }
 281 
 282     /** Codes for {@link #canonicalize(java.lang.Class, int)}.
 283      * ERASE means change every reference to {@code Object}.
 284      * WRAP means convert primitives (including {@code void} to their
 285      * corresponding wrapper types.  UNWRAP means the reverse of WRAP.
 286      * INTS means convert all non-void primitive types to int or long,
 287      * according to size.  LONGS means convert all non-void primitives
 288      * to long, regardless of size.  RAW_RETURN means convert a type
 289      * (assumed to be a return type) to int if it is smaller than an int,
 290      * or if it is void.
 291      */
 292     public static final int NO_CHANGE = 0, ERASE = 1, WRAP = 2, UNWRAP = 3, INTS = 4, LONGS = 5, RAW_RETURN = 6;
 293 
 294     /** Canonicalize the types in the given method type.
 295      * If any types change, intern the new type, and return it.
 296      * Otherwise return null.
 297      */
 298     public static MethodType canonicalize(MethodType mt, int howRet, int howArgs) {
 299         Class<?>[] ptypes = mt.ptypes();
 300         Class<?>[] ptc = MethodTypeForm.canonicalizes(ptypes, howArgs);
 301         Class<?> rtype = mt.returnType();
 302         Class<?> rtc = MethodTypeForm.canonicalize(rtype, howRet);
 303         if (ptc == null && rtc == null) {
 304             // It is already canonical.
 305             return null;
 306         }
 307         // Find the erased version of the method type:
 308         if (rtc == null)  rtc = rtype;
 309         if (ptc == null)  ptc = ptypes;
 310         return MethodType.makeImpl(rtc, ptc, true);
 311     }
 312 
 313     /** Canonicalize the given return or param type.
 314      *  Return null if the type is already canonicalized.
 315      */
 316     static Class<?> canonicalize(Class<?> t, int how) {
 317         Class<?> ct;
 318         if (t == Object.class) {
 319             // no change, ever
 320         } else if (!t.isPrimitive()) {
 321             switch (how) {
 322                 case UNWRAP:
 323                     ct = Wrapper.asPrimitiveType(t);
 324                     if (ct != t)  return ct;
 325                     break;
 326                 case RAW_RETURN:
 327                 case ERASE:
 328                     return Object.class;
 329             }
 330         } else if (t == void.class) {
 331             // no change, usually
 332             switch (how) {
 333                 case RAW_RETURN:
 334                     return int.class;
 335                 case WRAP:
 336                     return Void.class;
 337             }
 338         } else {
 339             // non-void primitive
 340             switch (how) {
 341                 case WRAP:
 342                     return Wrapper.asWrapperType(t);
 343                 case INTS:
 344                     if (t == int.class || t == long.class)
 345                         return null;  // no change
 346                     if (t == double.class)
 347                         return long.class;
 348                     return int.class;
 349                 case LONGS:
 350                     if (t == long.class)
 351                         return null;  // no change
 352                     return long.class;
 353                 case RAW_RETURN:
 354                     if (t == int.class || t == long.class ||
 355                         t == float.class || t == double.class)
 356                         return null;  // no change
 357                     // everything else returns as an int
 358                     return int.class;
 359             }
 360         }
 361         // no change; return null to signify
 362         return null;
 363     }
 364 
 365     /** Canonicalize each param type in the given array.
 366      *  Return null if all types are already canonicalized.
 367      */
 368     static Class<?>[] canonicalizes(Class<?>[] ts, int how) {
 369         Class<?>[] cs = null;
 370         for (int imax = ts.length, i = 0; i < imax; i++) {
 371             Class<?> c = canonicalize(ts[i], how);
 372             if (c == void.class)
 373                 c = null;  // a Void parameter was unwrapped to void; ignore
 374             if (c != null) {
 375                 if (cs == null)
 376                     cs = ts.clone();
 377                 cs[i] = c;
 378             }
 379         }
 380         return cs;
 381     }
 382 
 383     @Override
 384     public String toString() {
 385         return "Form"+erasedType;
 386     }
 387 
 388 }