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