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.misc.Unsafe;
  29 import java.lang.reflect.Method;
  30 import java.util.Arrays;
  31 import sun.invoke.util.VerifyAccess;
  32 import static java.lang.invoke.MethodHandleNatives.Constants.*;
  33 import static java.lang.invoke.LambdaForm.*;
  34 import static java.lang.invoke.LambdaForm.BasicType.*;
  35 import static java.lang.invoke.MethodTypeForm.*;
  36 import static java.lang.invoke.MethodHandleStatics.*;
  37 import java.lang.ref.WeakReference;
  38 import java.lang.reflect.Field;
  39 import sun.invoke.util.ValueConversions;
  40 import sun.invoke.util.VerifyType;
  41 import sun.invoke.util.Wrapper;
  42 
  43 /**
  44  * The flavor of method handle which implements a constant reference
  45  * to a class member.
  46  * @author jrose
  47  */
  48 class DirectMethodHandle extends MethodHandle {
  49     final MemberName member;
  50 
  51     // Constructors and factory methods in this class *must* be package scoped or private.
  52     private DirectMethodHandle(MethodType mtype, LambdaForm form, MemberName member) {
  53         super(mtype, form);
  54         if (!member.isResolved())  throw new InternalError();
  55 
  56         if (member.getDeclaringClass().isInterface() &&
  57                 member.isMethod() && !member.isAbstract()) {
  58             // Check for corner case: invokeinterface of Object method
  59             MemberName m = new MemberName(Object.class, member.getName(), member.getMethodType(), member.getReferenceKind());
  60             m = MemberName.getFactory().resolveOrNull(m.getReferenceKind(), m, null);
  61             if (m != null && m.isPublic()) {
  62                 member = m;
  63             }
  64         }
  65 
  66         this.member = member;
  67     }
  68 
  69     // Factory methods:
  70     static DirectMethodHandle make(byte refKind, Class<?> receiver, MemberName member) {
  71         MethodType mtype = member.getMethodOrFieldType();
  72         if (!member.isStatic()) {
  73             if (!member.getDeclaringClass().isAssignableFrom(receiver) || member.isConstructor())
  74                 throw new InternalError(member.toString());
  75             mtype = mtype.insertParameterTypes(0, receiver);
  76         }
  77         if (!member.isField()) {
  78             if (refKind == REF_invokeSpecial) {
  79                 member = member.asSpecial();
  80                 LambdaForm lform = preparedLambdaForm(member);
  81                 return new Special(mtype, lform, member);
  82             } else {
  83                 LambdaForm lform = preparedLambdaForm(member);
  84                 return new DirectMethodHandle(mtype, lform, member);
  85             }
  86         } else {
  87             LambdaForm lform = preparedFieldLambdaForm(member);
  88             if (member.isStatic()) {
  89                 long offset = MethodHandleNatives.staticFieldOffset(member);
  90                 Object base = MethodHandleNatives.staticFieldBase(member);
  91                 return new StaticAccessor(mtype, lform, member, base, offset);
  92             } else {
  93                 long offset = MethodHandleNatives.objectFieldOffset(member);
  94                 assert(offset == (int)offset);
  95                 return new Accessor(mtype, lform, member, (int)offset);
  96             }
  97         }
  98     }
  99     static DirectMethodHandle make(Class<?> receiver, MemberName member) {
 100         byte refKind = member.getReferenceKind();
 101         if (refKind == REF_invokeSpecial)
 102             refKind =  REF_invokeVirtual;
 103         return make(refKind, receiver, member);
 104     }
 105     static DirectMethodHandle make(MemberName member) {
 106         if (member.isConstructor())
 107             return makeAllocator(member);
 108         return make(member.getDeclaringClass(), member);
 109     }
 110     static DirectMethodHandle make(Method method) {
 111         return make(method.getDeclaringClass(), new MemberName(method));
 112     }
 113     static DirectMethodHandle make(Field field) {
 114         return make(field.getDeclaringClass(), new MemberName(field));
 115     }
 116     private static DirectMethodHandle makeAllocator(MemberName ctor) {
 117         assert(ctor.isConstructor() && ctor.getName().equals("<init>"));
 118         Class<?> instanceClass = ctor.getDeclaringClass();
 119         ctor = ctor.asConstructor();
 120         assert(ctor.isConstructor() && ctor.getReferenceKind() == REF_newInvokeSpecial) : ctor;
 121         MethodType mtype = ctor.getMethodType().changeReturnType(instanceClass);
 122         LambdaForm lform = preparedLambdaForm(ctor);
 123         MemberName init = ctor.asSpecial();
 124         assert(init.getMethodType().returnType() == void.class);
 125         return new Constructor(mtype, lform, ctor, init, instanceClass);
 126     }
 127 
 128     @Override
 129     MethodHandle copyWith(MethodType mt, LambdaForm lf) {
 130         return new DirectMethodHandle(mt, lf, member);
 131     }
 132 
 133     @Override
 134     String internalProperties() {
 135         return "/DMH="+member.toString();
 136     }
 137 
 138     //// Implementation methods.
 139     @Override
 140     MethodHandle viewAsType(MethodType newType) {
 141         return new DirectMethodHandle(newType, form, member);
 142     }
 143     @Override
 144     @ForceInline
 145     MemberName internalMemberName() {
 146         return member;
 147     }
 148 
 149     @Override
 150     MethodHandle bindArgument(int pos, BasicType basicType, Object value) {
 151         // If the member needs dispatching, do so.
 152         if (pos == 0 && basicType == L_TYPE) {
 153             DirectMethodHandle concrete = maybeRebind(value);
 154             if (concrete != null)
 155                 return concrete.bindReceiver(value);
 156         }
 157         return super.bindArgument(pos, basicType, value);
 158     }
 159 
 160     @Override
 161     MethodHandle bindReceiver(Object receiver) {
 162         // If the member needs dispatching, do so.
 163         DirectMethodHandle concrete = maybeRebind(receiver);
 164         if (concrete != null)
 165             return concrete.bindReceiver(receiver);
 166         return super.bindReceiver(receiver);
 167     }
 168 
 169     private static final MemberName.Factory IMPL_NAMES = MemberName.getFactory();
 170 
 171     private DirectMethodHandle maybeRebind(Object receiver) {
 172         if (receiver != null) {
 173             switch (member.getReferenceKind()) {
 174             case REF_invokeInterface:
 175             case REF_invokeVirtual:
 176                 // Pre-dispatch the member.
 177                 Class<?> concreteClass = receiver.getClass();
 178                 MemberName concrete = new MemberName(concreteClass, member.getName(), member.getMethodType(), REF_invokeSpecial);
 179                 concrete = IMPL_NAMES.resolveOrNull(REF_invokeSpecial, concrete, concreteClass);
 180                 if (concrete != null)
 181                     return new DirectMethodHandle(type(), preparedLambdaForm(concrete), concrete);
 182                 break;
 183             }
 184         }
 185         return null;
 186     }
 187 
 188     /**
 189      * Create a LF which can invoke the given method.
 190      * Cache and share this structure among all methods with
 191      * the same basicType and refKind.
 192      */
 193     private static LambdaForm preparedLambdaForm(MemberName m) {
 194         assert(m.isInvocable()) : m;  // call preparedFieldLambdaForm instead
 195         MethodType mtype = m.getInvocationType().basicType();
 196         assert(!m.isMethodHandleInvoke() || "invokeBasic".equals(m.getName())) : m;
 197         int which;
 198         switch (m.getReferenceKind()) {
 199         case REF_invokeVirtual:    which = LF_INVVIRTUAL;    break;
 200         case REF_invokeStatic:     which = LF_INVSTATIC;     break;
 201         case REF_invokeSpecial:    which = LF_INVSPECIAL;    break;
 202         case REF_invokeInterface:  which = LF_INVINTERFACE;  break;
 203         case REF_newInvokeSpecial: which = LF_NEWINVSPECIAL; break;
 204         default:  throw new InternalError(m.toString());
 205         }
 206         if (which == LF_INVSTATIC && shouldBeInitialized(m)) {
 207             // precompute the barrier-free version:
 208             preparedLambdaForm(mtype, which);
 209             which = LF_INVSTATIC_INIT;
 210         }
 211         LambdaForm lform = preparedLambdaForm(mtype, which);
 212         maybeCompile(lform, m);
 213         assert(lform.methodType().dropParameterTypes(0, 1)
 214                 .equals(m.getInvocationType().basicType()))
 215                 : Arrays.asList(m, m.getInvocationType().basicType(), lform, lform.methodType());
 216         return lform;
 217     }
 218 
 219     private static LambdaForm preparedLambdaForm(MethodType mtype, int which) {
 220         LambdaForm lform = mtype.form().cachedLambdaForm(which);
 221         if (lform != null)  return lform;
 222         lform = makePreparedLambdaForm(mtype, which);
 223         return mtype.form().setCachedLambdaForm(which, lform);
 224     }
 225 
 226     private static LambdaForm makePreparedLambdaForm(MethodType mtype, int which) {
 227         boolean needsInit = (which == LF_INVSTATIC_INIT);
 228         boolean doesAlloc = (which == LF_NEWINVSPECIAL);
 229         String linkerName, lambdaName;
 230         switch (which) {
 231         case LF_INVVIRTUAL:    linkerName = "linkToVirtual";    lambdaName = "DMH.invokeVirtual";    break;
 232         case LF_INVSTATIC:     linkerName = "linkToStatic";     lambdaName = "DMH.invokeStatic";     break;
 233         case LF_INVSTATIC_INIT:linkerName = "linkToStatic";     lambdaName = "DMH.invokeStaticInit"; break;
 234         case LF_INVSPECIAL:    linkerName = "linkToSpecial";    lambdaName = "DMH.invokeSpecial";    break;
 235         case LF_INVINTERFACE:  linkerName = "linkToInterface";  lambdaName = "DMH.invokeInterface";  break;
 236         case LF_NEWINVSPECIAL: linkerName = "linkToSpecial";    lambdaName = "DMH.newInvokeSpecial"; break;
 237         default:  throw new InternalError("which="+which);
 238         }
 239         MethodType mtypeWithArg = mtype.appendParameterTypes(MemberName.class);
 240         if (doesAlloc)
 241             mtypeWithArg = mtypeWithArg
 242                     .insertParameterTypes(0, Object.class)  // insert newly allocated obj
 243                     .changeReturnType(void.class);          // <init> returns void
 244         MemberName linker = new MemberName(MethodHandle.class, linkerName, mtypeWithArg, REF_invokeStatic);
 245         try {
 246             linker = IMPL_NAMES.resolveOrFail(REF_invokeStatic, linker, null, NoSuchMethodException.class);
 247         } catch (ReflectiveOperationException ex) {
 248             throw newInternalError(ex);
 249         }
 250         final int DMH_THIS    = 0;
 251         final int ARG_BASE    = 1;
 252         final int ARG_LIMIT   = ARG_BASE + mtype.parameterCount();
 253         int nameCursor = ARG_LIMIT;
 254         final int NEW_OBJ     = (doesAlloc ? nameCursor++ : -1);
 255         final int GET_MEMBER  = nameCursor++;
 256         final int LINKER_CALL = nameCursor++;
 257         Name[] names = arguments(nameCursor - ARG_LIMIT, mtype.invokerType());
 258         assert(names.length == nameCursor);
 259         if (doesAlloc) {
 260             // names = { argx,y,z,... new C, init method }
 261             names[NEW_OBJ] = new Name(Lazy.NF_allocateInstance, names[DMH_THIS]);
 262             names[GET_MEMBER] = new Name(Lazy.NF_constructorMethod, names[DMH_THIS]);
 263         } else if (needsInit) {
 264             names[GET_MEMBER] = new Name(Lazy.NF_internalMemberNameEnsureInit, names[DMH_THIS]);
 265         } else {
 266             names[GET_MEMBER] = new Name(Lazy.NF_internalMemberName, names[DMH_THIS]);
 267         }
 268         assert(findDirectMethodHandle(names[GET_MEMBER]) == names[DMH_THIS]);
 269         Object[] outArgs = Arrays.copyOfRange(names, ARG_BASE, GET_MEMBER+1, Object[].class);
 270         assert(outArgs[outArgs.length-1] == names[GET_MEMBER]);  // look, shifted args!
 271         int result = LAST_RESULT;
 272         if (doesAlloc) {
 273             assert(outArgs[outArgs.length-2] == names[NEW_OBJ]);  // got to move this one
 274             System.arraycopy(outArgs, 0, outArgs, 1, outArgs.length-2);
 275             outArgs[0] = names[NEW_OBJ];
 276             result = NEW_OBJ;
 277         }
 278         names[LINKER_CALL] = new Name(linker, outArgs);
 279         lambdaName += "_" + shortenSignature(basicTypeSignature(mtype));
 280         LambdaForm lform = new LambdaForm(lambdaName, ARG_LIMIT, names, result);
 281         // This is a tricky bit of code.  Don't send it through the LF interpreter.
 282         lform.compileToBytecode();
 283         return lform;
 284     }
 285 
 286     static Object findDirectMethodHandle(Name name) {
 287         if (name.function == Lazy.NF_internalMemberName ||
 288             name.function == Lazy.NF_internalMemberNameEnsureInit ||
 289             name.function == Lazy.NF_constructorMethod) {
 290             assert(name.arguments.length == 1);
 291             return name.arguments[0];
 292         }
 293         return null;
 294     }
 295 
 296     private static void maybeCompile(LambdaForm lform, MemberName m) {
 297         if (VerifyAccess.isSamePackage(m.getDeclaringClass(), MethodHandle.class))
 298             // Help along bootstrapping...
 299             lform.compileToBytecode();
 300     }
 301 
 302     /** Static wrapper for DirectMethodHandle.internalMemberName. */
 303     @ForceInline
 304     /*non-public*/ static Object internalMemberName(Object mh) {
 305         return ((DirectMethodHandle)mh).member;
 306     }
 307 
 308     /** Static wrapper for DirectMethodHandle.internalMemberName.
 309      * This one also forces initialization.
 310      */
 311     /*non-public*/ static Object internalMemberNameEnsureInit(Object mh) {
 312         DirectMethodHandle dmh = (DirectMethodHandle)mh;
 313         dmh.ensureInitialized();
 314         return dmh.member;
 315     }
 316 
 317     /*non-public*/ static
 318     boolean shouldBeInitialized(MemberName member) {
 319         switch (member.getReferenceKind()) {
 320         case REF_invokeStatic:
 321         case REF_getStatic:
 322         case REF_putStatic:
 323         case REF_newInvokeSpecial:
 324             break;
 325         default:
 326             // No need to initialize the class on this kind of member.
 327             return false;
 328         }
 329         Class<?> cls = member.getDeclaringClass();
 330         if (cls == ValueConversions.class ||
 331             cls == MethodHandleImpl.class ||
 332             cls == Invokers.class) {
 333             // These guys have lots of <clinit> DMH creation but we know
 334             // the MHs will not be used until the system is booted.
 335             return false;
 336         }
 337         if (VerifyAccess.isSamePackage(MethodHandle.class, cls) ||
 338             VerifyAccess.isSamePackage(ValueConversions.class, cls)) {
 339             // It is a system class.  It is probably in the process of
 340             // being initialized, but we will help it along just to be safe.
 341             if (UNSAFE.shouldBeInitialized(cls)) {
 342                 UNSAFE.ensureClassInitialized(cls);
 343             }
 344             return false;
 345         }
 346         return UNSAFE.shouldBeInitialized(cls);
 347     }
 348 
 349     private static class EnsureInitialized extends ClassValue<WeakReference<Thread>> {
 350         @Override
 351         protected WeakReference<Thread> computeValue(Class<?> type) {
 352             UNSAFE.ensureClassInitialized(type);
 353             if (UNSAFE.shouldBeInitialized(type))
 354                 // If the previous call didn't block, this can happen.
 355                 // We are executing inside <clinit>.
 356                 return new WeakReference<>(Thread.currentThread());
 357             return null;
 358         }
 359         static final EnsureInitialized INSTANCE = new EnsureInitialized();
 360     }
 361 
 362     private void ensureInitialized() {
 363         if (checkInitialized(member)) {
 364             // The coast is clear.  Delete the <clinit> barrier.
 365             if (member.isField())
 366                 updateForm(preparedFieldLambdaForm(member));
 367             else
 368                 updateForm(preparedLambdaForm(member));
 369         }
 370     }
 371     private static boolean checkInitialized(MemberName member) {
 372         Class<?> defc = member.getDeclaringClass();
 373         WeakReference<Thread> ref = EnsureInitialized.INSTANCE.get(defc);
 374         if (ref == null) {
 375             return true;  // the final state
 376         }
 377         Thread clinitThread = ref.get();
 378         // Somebody may still be running defc.<clinit>.
 379         if (clinitThread == Thread.currentThread()) {
 380             // If anybody is running defc.<clinit>, it is this thread.
 381             if (UNSAFE.shouldBeInitialized(defc))
 382                 // Yes, we are running it; keep the barrier for now.
 383                 return false;
 384         } else {
 385             // We are in a random thread.  Block.
 386             UNSAFE.ensureClassInitialized(defc);
 387         }
 388         assert(!UNSAFE.shouldBeInitialized(defc));
 389         // put it into the final state
 390         EnsureInitialized.INSTANCE.remove(defc);
 391         return true;
 392     }
 393 
 394     /*non-public*/ static void ensureInitialized(Object mh) {
 395         ((DirectMethodHandle)mh).ensureInitialized();
 396     }
 397 
 398     /** This subclass represents invokespecial instructions. */
 399     static class Special extends DirectMethodHandle {
 400         private Special(MethodType mtype, LambdaForm form, MemberName member) {
 401             super(mtype, form, member);
 402         }
 403         @Override
 404         boolean isInvokeSpecial() {
 405             return true;
 406         }
 407         @Override
 408         MethodHandle viewAsType(MethodType newType) {
 409             return new Special(newType, form, member);
 410         }
 411     }
 412 
 413     /** This subclass handles constructor references. */
 414     static class Constructor extends DirectMethodHandle {
 415         final MemberName initMethod;
 416         final Class<?>   instanceClass;
 417 
 418         private Constructor(MethodType mtype, LambdaForm form, MemberName constructor,
 419                             MemberName initMethod, Class<?> instanceClass) {
 420             super(mtype, form, constructor);
 421             this.initMethod = initMethod;
 422             this.instanceClass = instanceClass;
 423             assert(initMethod.isResolved());
 424         }
 425         @Override
 426         MethodHandle viewAsType(MethodType newType) {
 427             return new Constructor(newType, form, member, initMethod, instanceClass);
 428         }
 429     }
 430 
 431     /*non-public*/ static Object constructorMethod(Object mh) {
 432         Constructor dmh = (Constructor)mh;
 433         return dmh.initMethod;
 434     }
 435 
 436     /*non-public*/ static Object allocateInstance(Object mh) throws InstantiationException {
 437         Constructor dmh = (Constructor)mh;
 438         return UNSAFE.allocateInstance(dmh.instanceClass);
 439     }
 440 
 441     /** This subclass handles non-static field references. */
 442     static class Accessor extends DirectMethodHandle {
 443         final Class<?> fieldType;
 444         final int      fieldOffset;
 445         private Accessor(MethodType mtype, LambdaForm form, MemberName member,
 446                          int fieldOffset) {
 447             super(mtype, form, member);
 448             this.fieldType   = member.getFieldType();
 449             this.fieldOffset = fieldOffset;
 450         }
 451 
 452         @Override Object checkCast(Object obj) {
 453             return fieldType.cast(obj);
 454         }
 455         @Override
 456         MethodHandle viewAsType(MethodType newType) {
 457             return new Accessor(newType, form, member, fieldOffset);
 458         }
 459     }
 460 
 461     @ForceInline
 462     /*non-public*/ static long fieldOffset(Object accessorObj) {
 463         // Note: We return a long because that is what Unsafe.getObject likes.
 464         // We store a plain int because it is more compact.
 465         return ((Accessor)accessorObj).fieldOffset;
 466     }
 467 
 468     @ForceInline
 469     /*non-public*/ static Object checkBase(Object obj) {
 470         // Note that the object's class has already been verified,
 471         // since the parameter type of the Accessor method handle
 472         // is either member.getDeclaringClass or a subclass.
 473         // This was verified in DirectMethodHandle.make.
 474         // Therefore, the only remaining check is for null.
 475         // Since this check is *not* guaranteed by Unsafe.getInt
 476         // and its siblings, we need to make an explicit one here.
 477         obj.getClass();  // maybe throw NPE
 478         return obj;
 479     }
 480 
 481     /** This subclass handles static field references. */
 482     static class StaticAccessor extends DirectMethodHandle {
 483         final private Class<?> fieldType;
 484         final private Object   staticBase;
 485         final private long     staticOffset;
 486 
 487         private StaticAccessor(MethodType mtype, LambdaForm form, MemberName member,
 488                                Object staticBase, long staticOffset) {
 489             super(mtype, form, member);
 490             this.fieldType    = member.getFieldType();
 491             this.staticBase   = staticBase;
 492             this.staticOffset = staticOffset;
 493         }
 494 
 495         @Override Object checkCast(Object obj) {
 496             return fieldType.cast(obj);
 497         }
 498         @Override
 499         MethodHandle viewAsType(MethodType newType) {
 500             return new StaticAccessor(newType, form, member, staticBase, staticOffset);
 501         }
 502     }
 503 
 504     @ForceInline
 505     /*non-public*/ static Object nullCheck(Object obj) {
 506         obj.getClass();
 507         return obj;
 508     }
 509 
 510     @ForceInline
 511     /*non-public*/ static Object staticBase(Object accessorObj) {
 512         return ((StaticAccessor)accessorObj).staticBase;
 513     }
 514 
 515     @ForceInline
 516     /*non-public*/ static long staticOffset(Object accessorObj) {
 517         return ((StaticAccessor)accessorObj).staticOffset;
 518     }
 519 
 520     @ForceInline
 521     /*non-public*/ static Object checkCast(Object mh, Object obj) {
 522         return ((DirectMethodHandle) mh).checkCast(obj);
 523     }
 524 
 525     Object checkCast(Object obj) {
 526         return member.getReturnType().cast(obj);
 527     }
 528 
 529     // Caching machinery for field accessors:
 530     private static byte
 531             AF_GETFIELD        = 0,
 532             AF_PUTFIELD        = 1,
 533             AF_GETSTATIC       = 2,
 534             AF_PUTSTATIC       = 3,
 535             AF_GETSTATIC_INIT  = 4,
 536             AF_PUTSTATIC_INIT  = 5,
 537             AF_LIMIT           = 6;
 538     // Enumerate the different field kinds using Wrapper,
 539     // with an extra case added for checked references.
 540     private static int
 541             FT_LAST_WRAPPER    = Wrapper.values().length-1,
 542             FT_UNCHECKED_REF   = Wrapper.OBJECT.ordinal(),
 543             FT_CHECKED_REF     = FT_LAST_WRAPPER+1,
 544             FT_LIMIT           = FT_LAST_WRAPPER+2;
 545     private static int afIndex(byte formOp, boolean isVolatile, int ftypeKind) {
 546         return ((formOp * FT_LIMIT * 2)
 547                 + (isVolatile ? FT_LIMIT : 0)
 548                 + ftypeKind);
 549     }
 550     private static final LambdaForm[] ACCESSOR_FORMS
 551             = new LambdaForm[afIndex(AF_LIMIT, false, 0)];
 552     private static int ftypeKind(Class<?> ftype) {
 553         if (ftype.isPrimitive())
 554             return Wrapper.forPrimitiveType(ftype).ordinal();
 555         else if (VerifyType.isNullReferenceConversion(Object.class, ftype))
 556             return FT_UNCHECKED_REF;
 557         else
 558             return FT_CHECKED_REF;
 559     }
 560 
 561     /**
 562      * Create a LF which can access the given field.
 563      * Cache and share this structure among all fields with
 564      * the same basicType and refKind.
 565      */
 566     private static LambdaForm preparedFieldLambdaForm(MemberName m) {
 567         Class<?> ftype = m.getFieldType();
 568         boolean isVolatile = m.isVolatile();
 569         byte formOp;
 570         switch (m.getReferenceKind()) {
 571         case REF_getField:      formOp = AF_GETFIELD;    break;
 572         case REF_putField:      formOp = AF_PUTFIELD;    break;
 573         case REF_getStatic:     formOp = AF_GETSTATIC;   break;
 574         case REF_putStatic:     formOp = AF_PUTSTATIC;   break;
 575         default:  throw new InternalError(m.toString());
 576         }
 577         if (shouldBeInitialized(m)) {
 578             // precompute the barrier-free version:
 579             preparedFieldLambdaForm(formOp, isVolatile, ftype);
 580             assert((AF_GETSTATIC_INIT - AF_GETSTATIC) ==
 581                    (AF_PUTSTATIC_INIT - AF_PUTSTATIC));
 582             formOp += (AF_GETSTATIC_INIT - AF_GETSTATIC);
 583         }
 584         LambdaForm lform = preparedFieldLambdaForm(formOp, isVolatile, ftype);
 585         maybeCompile(lform, m);
 586         assert(lform.methodType().dropParameterTypes(0, 1)
 587                 .equals(m.getInvocationType().basicType()))
 588                 : Arrays.asList(m, m.getInvocationType().basicType(), lform, lform.methodType());
 589         return lform;
 590     }
 591     private static LambdaForm preparedFieldLambdaForm(byte formOp, boolean isVolatile, Class<?> ftype) {
 592         int afIndex = afIndex(formOp, isVolatile, ftypeKind(ftype));
 593         LambdaForm lform = ACCESSOR_FORMS[afIndex];
 594         if (lform != null)  return lform;
 595         lform = makePreparedFieldLambdaForm(formOp, isVolatile, ftypeKind(ftype));
 596         ACCESSOR_FORMS[afIndex] = lform;  // don't bother with a CAS
 597         return lform;
 598     }
 599 
 600     private static LambdaForm makePreparedFieldLambdaForm(byte formOp, boolean isVolatile, int ftypeKind) {
 601         boolean isGetter  = (formOp & 1) == (AF_GETFIELD & 1);
 602         boolean isStatic  = (formOp >= AF_GETSTATIC);
 603         boolean needsInit = (formOp >= AF_GETSTATIC_INIT);
 604         boolean needsCast = (ftypeKind == FT_CHECKED_REF);
 605         Wrapper fw = (needsCast ? Wrapper.OBJECT : Wrapper.values()[ftypeKind]);
 606         Class<?> ft = fw.primitiveType();
 607         assert(ftypeKind(needsCast ? String.class : ft) == ftypeKind);
 608         String tname  = fw.primitiveSimpleName();
 609         String ctname = Character.toUpperCase(tname.charAt(0)) + tname.substring(1);
 610         if (isVolatile)  ctname += "Volatile";
 611         String getOrPut = (isGetter ? "get" : "put");
 612         String linkerName = (getOrPut + ctname);  // getObject, putIntVolatile, etc.
 613         MethodType linkerType;
 614         if (isGetter)
 615             linkerType = MethodType.methodType(ft, Object.class, long.class);
 616         else
 617             linkerType = MethodType.methodType(void.class, Object.class, long.class, ft);
 618         MemberName linker = new MemberName(Unsafe.class, linkerName, linkerType, REF_invokeVirtual);
 619         try {
 620             linker = IMPL_NAMES.resolveOrFail(REF_invokeVirtual, linker, null, NoSuchMethodException.class);
 621         } catch (ReflectiveOperationException ex) {
 622             throw newInternalError(ex);
 623         }
 624 
 625         // What is the external type of the lambda form?
 626         MethodType mtype;
 627         if (isGetter)
 628             mtype = MethodType.methodType(ft);
 629         else
 630             mtype = MethodType.methodType(void.class, ft);
 631         mtype = mtype.basicType();  // erase short to int, etc.
 632         if (!isStatic)
 633             mtype = mtype.insertParameterTypes(0, Object.class);
 634         final int DMH_THIS  = 0;
 635         final int ARG_BASE  = 1;
 636         final int ARG_LIMIT = ARG_BASE + mtype.parameterCount();
 637         // if this is for non-static access, the base pointer is stored at this index:
 638         final int OBJ_BASE  = isStatic ? -1 : ARG_BASE;
 639         // if this is for write access, the value to be written is stored at this index:
 640         final int SET_VALUE  = isGetter ? -1 : ARG_LIMIT - 1;
 641         int nameCursor = ARG_LIMIT;
 642         final int F_HOLDER  = (isStatic ? nameCursor++ : -1);  // static base if any
 643         final int F_OFFSET  = nameCursor++;  // Either static offset or field offset.
 644         final int OBJ_CHECK = (OBJ_BASE >= 0 ? nameCursor++ : -1);
 645         final int INIT_BAR  = (needsInit ? nameCursor++ : -1);
 646         final int PRE_CAST  = (needsCast && !isGetter ? nameCursor++ : -1);
 647         final int LINKER_CALL = nameCursor++;
 648         final int POST_CAST = (needsCast && isGetter ? nameCursor++ : -1);
 649         final int RESULT    = nameCursor-1;  // either the call or the cast
 650         Name[] names = arguments(nameCursor - ARG_LIMIT, mtype.invokerType());
 651         if (needsInit)
 652             names[INIT_BAR] = new Name(Lazy.NF_ensureInitialized, names[DMH_THIS]);
 653         if (needsCast && !isGetter)
 654             names[PRE_CAST] = new Name(Lazy.NF_checkCast, names[DMH_THIS], names[SET_VALUE]);
 655         Object[] outArgs = new Object[1 + linkerType.parameterCount()];
 656         assert(outArgs.length == (isGetter ? 3 : 4));
 657         outArgs[0] = UNSAFE;
 658         if (isStatic) {
 659             outArgs[1] = names[F_HOLDER]  = new Name(Lazy.NF_staticBase, names[DMH_THIS]);
 660             outArgs[2] = names[F_OFFSET]  = new Name(Lazy.NF_staticOffset, names[DMH_THIS]);
 661         } else {
 662             outArgs[1] = names[OBJ_CHECK] = new Name(Lazy.NF_checkBase, names[OBJ_BASE]);
 663             outArgs[2] = names[F_OFFSET]  = new Name(Lazy.NF_fieldOffset, names[DMH_THIS]);
 664         }
 665         if (!isGetter) {
 666             outArgs[3] = (needsCast ? names[PRE_CAST] : names[SET_VALUE]);
 667         }
 668         for (Object a : outArgs)  assert(a != null);
 669         names[LINKER_CALL] = new Name(linker, outArgs);
 670         if (needsCast && isGetter)
 671             names[POST_CAST] = new Name(Lazy.NF_checkCast, names[DMH_THIS], names[LINKER_CALL]);
 672         for (Name n : names)  assert(n != null);
 673         String fieldOrStatic = (isStatic ? "Static" : "Field");
 674         String lambdaName = (linkerName + fieldOrStatic);  // significant only for debugging
 675         if (needsCast)  lambdaName += "Cast";
 676         if (needsInit)  lambdaName += "Init";
 677         return new LambdaForm(lambdaName, ARG_LIMIT, names, RESULT);
 678     }
 679 
 680     /**
 681      * Pre-initialized NamedFunctions for bootstrapping purposes.
 682      * Factored in an inner class to delay initialization until first usage.
 683      */
 684     private static class Lazy {
 685         static final NamedFunction
 686                 NF_internalMemberName,
 687                 NF_internalMemberNameEnsureInit,
 688                 NF_ensureInitialized,
 689                 NF_fieldOffset,
 690                 NF_checkBase,
 691                 NF_staticBase,
 692                 NF_staticOffset,
 693                 NF_checkCast,
 694                 NF_allocateInstance,
 695                 NF_constructorMethod;
 696         static {
 697             try {
 698                 NamedFunction nfs[] = {
 699                         NF_internalMemberName = new NamedFunction(DirectMethodHandle.class
 700                                 .getDeclaredMethod("internalMemberName", Object.class)),
 701                         NF_internalMemberNameEnsureInit = new NamedFunction(DirectMethodHandle.class
 702                                 .getDeclaredMethod("internalMemberNameEnsureInit", Object.class)),
 703                         NF_ensureInitialized = new NamedFunction(DirectMethodHandle.class
 704                                 .getDeclaredMethod("ensureInitialized", Object.class)),
 705                         NF_fieldOffset = new NamedFunction(DirectMethodHandle.class
 706                                 .getDeclaredMethod("fieldOffset", Object.class)),
 707                         NF_checkBase = new NamedFunction(DirectMethodHandle.class
 708                                 .getDeclaredMethod("checkBase", Object.class)),
 709                         NF_staticBase = new NamedFunction(DirectMethodHandle.class
 710                                 .getDeclaredMethod("staticBase", Object.class)),
 711                         NF_staticOffset = new NamedFunction(DirectMethodHandle.class
 712                                 .getDeclaredMethod("staticOffset", Object.class)),
 713                         NF_checkCast = new NamedFunction(DirectMethodHandle.class
 714                                 .getDeclaredMethod("checkCast", Object.class, Object.class)),
 715                         NF_allocateInstance = new NamedFunction(DirectMethodHandle.class
 716                                 .getDeclaredMethod("allocateInstance", Object.class)),
 717                         NF_constructorMethod = new NamedFunction(DirectMethodHandle.class
 718                                 .getDeclaredMethod("constructorMethod", Object.class))
 719                 };
 720                 for (NamedFunction nf : nfs) {
 721                     // Each nf must be statically invocable or we get tied up in our bootstraps.
 722                     assert(InvokerBytecodeGenerator.isStaticallyInvocable(nf.member)) : nf;
 723                     nf.resolve();
 724                 }
 725             } catch (ReflectiveOperationException ex) {
 726                 throw newInternalError(ex);
 727             }
 728         }
 729     }
 730 }