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