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 java.lang.ref.SoftReference;
  30 import static java.lang.invoke.MethodHandleStatics.*;
  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 MethodType erasedType;        // the canonical erasure
  50     final MethodType basicType;         // the canonical erasure, with primitives simplified
  51 
  52     // Cached adapter information:
  53     @Stable final SoftReference<MethodHandle>[] methodHandles;
  54     // Indexes into methodHandles:
  55     static final int
  56             MH_BASIC_INV      =  0,  // cached instance of MH.invokeBasic
  57             MH_NF_INV         =  1,  // cached helper for LF.NamedFunction
  58             MH_UNINIT_CS      =  2,  // uninitialized call site
  59             MH_LIMIT          =  3;
  60 
  61     // Cached lambda form information, for basic types only:
  62     final @Stable SoftReference<LambdaForm>[] lambdaForms;
  63     // Indexes into lambdaForms:
  64     static final int
  65             LF_INVVIRTUAL              =  0,  // DMH invokeVirtual
  66             LF_INVSTATIC               =  1,
  67             LF_INVSPECIAL              =  2,
  68             LF_NEWINVSPECIAL           =  3,
  69             LF_INVINTERFACE            =  4,
  70             LF_INVSTATIC_INIT          =  5,  // DMH invokeStatic with <clinit> barrier
  71             LF_INTERPRET               =  6,  // LF interpreter
  72             LF_REBIND                  =  7,  // BoundMethodHandle
  73             LF_DELEGATE                =  8,  // DelegatingMethodHandle
  74             LF_DELEGATE_BLOCK_INLINING =  9,  // Counting DelegatingMethodHandle w/ @DontInline
  75             LF_EX_LINKER               = 10,  // invokeExact_MT (for invokehandle)
  76             LF_EX_INVOKER              = 11,  // MHs.invokeExact
  77             LF_GEN_LINKER              = 12,  // generic invoke_MT (for invokehandle)
  78             LF_GEN_INVOKER             = 13,  // generic MHs.invoke
  79             LF_CS_LINKER               = 14,  // linkToCallSite_CS
  80             LF_MH_LINKER               = 15,  // linkToCallSite_MH
  81             LF_GWC                     = 16,  // guardWithCatch (catchException)
  82             LF_GWT                     = 17,  // guardWithTest
  83             LF_LIMIT                   = 18;
  84 
  85     /** Return the type corresponding uniquely (1-1) to this MT-form.
  86      *  It might have any primitive returns or arguments, but will have no references except Object.
  87      */
  88     public MethodType erasedType() {
  89         return erasedType;
  90     }
  91 
  92     /** Return the basic type derived from the erased type of this MT-form.
  93      *  A basic type is erased (all references Object) and also has all primitive
  94      *  types (except int, long, float, double, void) normalized to int.
  95      *  Such basic types correspond to low-level JVM calling sequences.
  96      */
  97     public MethodType basicType() {
  98         return basicType;
  99     }
 100 
 101     private boolean assertIsBasicType() {
 102         // primitives must be flattened also
 103         assert(erasedType == basicType)
 104                 : "erasedType: " + erasedType + " != basicType: " + basicType;
 105         return true;
 106     }
 107 
 108     public MethodHandle cachedMethodHandle(int which) {
 109         assert(assertIsBasicType());
 110         SoftReference<MethodHandle> entry = methodHandles[which];
 111         return (entry != null) ? entry.get() : null;
 112     }
 113 
 114     synchronized public MethodHandle setCachedMethodHandle(int which, MethodHandle mh) {
 115         // Simulate a CAS, to avoid racy duplication of results.
 116         SoftReference<MethodHandle> entry = methodHandles[which];
 117         if (entry != null) {
 118             MethodHandle prev = entry.get();
 119             if (prev != null) {
 120                 return prev;
 121             }
 122         }
 123         methodHandles[which] = new SoftReference<>(mh);
 124         return mh;
 125     }
 126 
 127     public LambdaForm cachedLambdaForm(int which) {
 128         assert(assertIsBasicType());
 129         SoftReference<LambdaForm> entry = lambdaForms[which];
 130         return (entry != null) ? entry.get() : null;
 131     }
 132 
 133     synchronized public LambdaForm setCachedLambdaForm(int which, LambdaForm form) {
 134         // Simulate a CAS, to avoid racy duplication of results.
 135         SoftReference<LambdaForm> entry = lambdaForms[which];
 136         if (entry != null) {
 137             LambdaForm prev = entry.get();
 138             if (prev != null) {
 139                 return prev;
 140             }
 141         }
 142         lambdaForms[which] = new SoftReference<>(form);
 143         return form;
 144     }
 145 
 146     /**
 147      * Build an MTF for a given type, which must have all references erased to Object.
 148      * This MTF will stand for that type and all un-erased variations.
 149      * Eagerly compute some basic properties of the type, common to all variations.
 150      */
 151     @SuppressWarnings({"rawtypes", "unchecked"})
 152     protected MethodTypeForm(MethodType erasedType) {
 153         this.erasedType = erasedType;
 154 
 155         Class<?>[] ptypes = erasedType.ptypes();
 156         int ptypeCount = ptypes.length;
 157         int pslotCount = ptypeCount;            // temp. estimate
 158         int rtypeCount = 1;                     // temp. estimate
 159         int rslotCount = 1;                     // temp. estimate
 160 
 161         int[] argToSlotTab = null, slotToArgTab = null;
 162 
 163         // Walk the argument types, looking for primitives.
 164         int pac = 0, lac = 0, prc = 0, lrc = 0;
 165         Class<?>[] epts = ptypes;
 166         Class<?>[] bpts = epts;
 167         for (int i = 0; i < epts.length; i++) {
 168             Class<?> pt = epts[i];
 169             if (pt != Object.class) {
 170                 ++pac;
 171                 Wrapper w = Wrapper.forPrimitiveType(pt);
 172                 if (w.isDoubleWord())  ++lac;
 173                 if (w.isSubwordOrInt() && pt != int.class) {
 174                     if (bpts == epts)
 175                         bpts = bpts.clone();
 176                     bpts[i] = int.class;
 177                 }
 178             }
 179         }
 180         pslotCount += lac;                  // #slots = #args + #longs
 181         Class<?> rt = erasedType.returnType();
 182         Class<?> bt = rt;
 183         if (rt != Object.class) {
 184             ++prc;          // even void.class counts as a prim here
 185             Wrapper w = Wrapper.forPrimitiveType(rt);
 186             if (w.isDoubleWord())  ++lrc;
 187             if (w.isSubwordOrInt() && rt != int.class)
 188                 bt = int.class;
 189             // adjust #slots, #args
 190             if (rt == void.class)
 191                 rtypeCount = rslotCount = 0;
 192             else
 193                 rslotCount += lrc;
 194         }
 195         if (epts == bpts && bt == rt) {
 196             this.basicType = erasedType;
 197         } else {
 198             this.basicType = MethodType.makeImpl(bt, bpts, true);
 199             // fill in rest of data from the basic type:
 200             MethodTypeForm that = this.basicType.form();
 201             assert(this != that);
 202             this.primCounts = that.primCounts;
 203             this.argCounts = that.argCounts;
 204             this.argToSlotTable = that.argToSlotTable;
 205             this.slotToArgTable = that.slotToArgTable;
 206             this.methodHandles = null;
 207             this.lambdaForms = null;
 208             return;
 209         }
 210         if (lac != 0) {
 211             int slot = ptypeCount + lac;
 212             slotToArgTab = new int[slot+1];
 213             argToSlotTab = new int[1+ptypeCount];
 214             argToSlotTab[0] = slot;  // argument "-1" is past end of slots
 215             for (int i = 0; i < epts.length; i++) {
 216                 Class<?> pt = epts[i];
 217                 Wrapper w = Wrapper.forBasicType(pt);
 218                 if (w.isDoubleWord())  --slot;
 219                 --slot;
 220                 slotToArgTab[slot] = i+1; // "+1" see argSlotToParameter note
 221                 argToSlotTab[1+i]  = slot;
 222             }
 223             assert(slot == 0);  // filled the table
 224         } else if (pac != 0) {
 225             // have primitives but no long primitives; share slot counts with generic
 226             assert(ptypeCount == pslotCount);
 227             MethodTypeForm that = MethodType.genericMethodType(ptypeCount).form();
 228             assert(this != that);
 229             slotToArgTab = that.slotToArgTable;
 230             argToSlotTab = that.argToSlotTable;
 231         } else {
 232             int slot = ptypeCount; // first arg is deepest in stack
 233             slotToArgTab = new int[slot+1];
 234             argToSlotTab = new int[1+ptypeCount];
 235             argToSlotTab[0] = slot;  // argument "-1" is past end of slots
 236             for (int i = 0; i < ptypeCount; i++) {
 237                 --slot;
 238                 slotToArgTab[slot] = i+1; // "+1" see argSlotToParameter note
 239                 argToSlotTab[1+i]  = slot;
 240             }
 241         }
 242         this.primCounts = pack(lrc, prc, lac, pac);
 243         this.argCounts = pack(rslotCount, rtypeCount, pslotCount, ptypeCount);
 244         this.argToSlotTable = argToSlotTab;
 245         this.slotToArgTable = slotToArgTab;
 246 
 247         if (pslotCount >= 256)  throw newIllegalArgumentException("too many arguments");
 248 
 249         // Initialize caches, but only for basic types
 250         assert(basicType == erasedType);
 251         this.lambdaForms   = new SoftReference[LF_LIMIT];
 252         this.methodHandles = new SoftReference[MH_LIMIT];
 253     }
 254 
 255     private static long pack(int a, int b, int c, int d) {
 256         assert(((a|b|c|d) & ~0xFFFF) == 0);
 257         long hw = ((a << 16) | b), lw = ((c << 16) | d);
 258         return (hw << 32) | lw;
 259     }
 260     private static char unpack(long packed, int word) { // word==0 => return a, ==3 => return d
 261         assert(word <= 3);
 262         return (char)(packed >> ((3-word) * 16));
 263     }
 264 
 265     public int parameterCount() {                      // # outgoing values
 266         return unpack(argCounts, 3);
 267     }
 268     public int parameterSlotCount() {                  // # outgoing interpreter slots
 269         return unpack(argCounts, 2);
 270     }
 271     public int returnCount() {                         // = 0 (V), or 1
 272         return unpack(argCounts, 1);
 273     }
 274     public int returnSlotCount() {                     // = 0 (V), 2 (J/D), or 1
 275         return unpack(argCounts, 0);
 276     }
 277     public int primitiveParameterCount() {
 278         return unpack(primCounts, 3);
 279     }
 280     public int longPrimitiveParameterCount() {
 281         return unpack(primCounts, 2);
 282     }
 283     public int primitiveReturnCount() {                // = 0 (obj), or 1
 284         return unpack(primCounts, 1);
 285     }
 286     public int longPrimitiveReturnCount() {            // = 1 (J/D), or 0
 287         return unpack(primCounts, 0);
 288     }
 289     public boolean hasPrimitives() {
 290         return primCounts != 0;
 291     }
 292     public boolean hasNonVoidPrimitives() {
 293         if (primCounts == 0)  return false;
 294         if (primitiveParameterCount() != 0)  return true;
 295         return (primitiveReturnCount() != 0 && returnCount() != 0);
 296     }
 297     public boolean hasLongPrimitives() {
 298         return (longPrimitiveParameterCount() | longPrimitiveReturnCount()) != 0;
 299     }
 300     public int parameterToArgSlot(int i) {
 301         return argToSlotTable[1+i];
 302     }
 303     public int argSlotToParameter(int argSlot) {
 304         // Note:  Empty slots are represented by zero in this table.
 305         // Valid arguments slots contain incremented entries, so as to be non-zero.
 306         // We return -1 the caller to mean an empty slot.
 307         return slotToArgTable[argSlot] - 1;
 308     }
 309 
 310     static MethodTypeForm findForm(MethodType mt) {
 311         MethodType erased = canonicalize(mt, ERASE, ERASE);
 312         if (erased == null) {
 313             // It is already erased.  Make a new MethodTypeForm.
 314             return new MethodTypeForm(mt);
 315         } else {
 316             // Share the MethodTypeForm with the erased version.
 317             return erased.form();
 318         }
 319     }
 320 
 321     /** Codes for {@link #canonicalize(java.lang.Class, int)}.
 322      * ERASE means change every reference to {@code Object}.
 323      * WRAP means convert primitives (including {@code void} to their
 324      * corresponding wrapper types.  UNWRAP means the reverse of WRAP.
 325      * INTS means convert all non-void primitive types to int or long,
 326      * according to size.  LONGS means convert all non-void primitives
 327      * to long, regardless of size.  RAW_RETURN means convert a type
 328      * (assumed to be a return type) to int if it is smaller than an int,
 329      * or if it is void.
 330      */
 331     public static final int NO_CHANGE = 0, ERASE = 1, WRAP = 2, UNWRAP = 3, INTS = 4, LONGS = 5, RAW_RETURN = 6;
 332 
 333     /** Canonicalize the types in the given method type.
 334      * If any types change, intern the new type, and return it.
 335      * Otherwise return null.
 336      */
 337     public static MethodType canonicalize(MethodType mt, int howRet, int howArgs) {
 338         Class<?>[] ptypes = mt.ptypes();
 339         Class<?>[] ptc = MethodTypeForm.canonicalizeAll(ptypes, howArgs);
 340         Class<?> rtype = mt.returnType();
 341         Class<?> rtc = MethodTypeForm.canonicalize(rtype, howRet);
 342         if (ptc == null && rtc == null) {
 343             // It is already canonical.
 344             return null;
 345         }
 346         // Find the erased version of the method type:
 347         if (rtc == null)  rtc = rtype;
 348         if (ptc == null)  ptc = ptypes;
 349         return MethodType.makeImpl(rtc, ptc, true);
 350     }
 351 
 352     /** Canonicalize the given return or param type.
 353      *  Return null if the type is already canonicalized.
 354      */
 355     static Class<?> canonicalize(Class<?> t, int how) {
 356         Class<?> ct;
 357         if (t == Object.class) {
 358             // no change, ever
 359         } else if (!t.isPrimitive()) {
 360             switch (how) {
 361                 case UNWRAP:
 362                     ct = Wrapper.asPrimitiveType(t);
 363                     if (ct != t)  return ct;
 364                     break;
 365                 case RAW_RETURN:
 366                 case ERASE:
 367                     return Object.class;
 368             }
 369         } else if (t == void.class) {
 370             // no change, usually
 371             switch (how) {
 372                 case RAW_RETURN:
 373                     return int.class;
 374                 case WRAP:
 375                     return Void.class;
 376             }
 377         } else {
 378             // non-void primitive
 379             switch (how) {
 380                 case WRAP:
 381                     return Wrapper.asWrapperType(t);
 382                 case INTS:
 383                     if (t == int.class || t == long.class)
 384                         return null;  // no change
 385                     if (t == double.class)
 386                         return long.class;
 387                     return int.class;
 388                 case LONGS:
 389                     if (t == long.class)
 390                         return null;  // no change
 391                     return long.class;
 392                 case RAW_RETURN:
 393                     if (t == int.class || t == long.class ||
 394                         t == float.class || t == double.class)
 395                         return null;  // no change
 396                     // everything else returns as an int
 397                     return int.class;
 398             }
 399         }
 400         // no change; return null to signify
 401         return null;
 402     }
 403 
 404     /** Canonicalize each param type in the given array.
 405      *  Return null if all types are already canonicalized.
 406      */
 407     static Class<?>[] canonicalizeAll(Class<?>[] ts, int how) {
 408         Class<?>[] cs = null;
 409         for (int imax = ts.length, i = 0; i < imax; i++) {
 410             Class<?> c = canonicalize(ts[i], how);
 411             if (c == void.class)
 412                 c = null;  // a Void parameter was unwrapped to void; ignore
 413             if (c != null) {
 414                 if (cs == null)
 415                     cs = ts.clone();
 416                 cs[i] = c;
 417             }
 418         }
 419         return cs;
 420     }
 421 
 422     @Override
 423     public String toString() {
 424         return "Form"+erasedType;
 425     }
 426 }