VarHandles.java revision 14075:c337b8a1e467
1/*
2 * Copyright (c) 2014, 2016, 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
26package java.lang.invoke;
27
28import static java.lang.invoke.MethodHandleStatics.UNSAFE;
29
30final class VarHandles {
31
32    static VarHandle makeFieldHandle(MemberName f, Class<?> refc, Class<?> type, boolean isWriteAllowedOnFinalFields) {
33        if (!f.isStatic()) {
34            long foffset = MethodHandleNatives.objectFieldOffset(f);
35            if (!type.isPrimitive()) {
36                return f.isFinal() && !isWriteAllowedOnFinalFields
37                       ? new VarHandleObjects.FieldInstanceReadOnly(refc, foffset, type)
38                       : new VarHandleObjects.FieldInstanceReadWrite(refc, foffset, type);
39            }
40            else if (type == boolean.class) {
41                return f.isFinal() && !isWriteAllowedOnFinalFields
42                       ? new VarHandleBooleans.FieldInstanceReadOnly(refc, foffset)
43                       : new VarHandleBooleans.FieldInstanceReadWrite(refc, foffset);
44            }
45            else if (type == byte.class) {
46                return f.isFinal() && !isWriteAllowedOnFinalFields
47                       ? new VarHandleBytes.FieldInstanceReadOnly(refc, foffset)
48                       : new VarHandleBytes.FieldInstanceReadWrite(refc, foffset);
49            }
50            else if (type == short.class) {
51                return f.isFinal() && !isWriteAllowedOnFinalFields
52                       ? new VarHandleShorts.FieldInstanceReadOnly(refc, foffset)
53                       : new VarHandleShorts.FieldInstanceReadWrite(refc, foffset);
54            }
55            else if (type == char.class) {
56                return f.isFinal() && !isWriteAllowedOnFinalFields
57                       ? new VarHandleChars.FieldInstanceReadOnly(refc, foffset)
58                       : new VarHandleChars.FieldInstanceReadWrite(refc, foffset);
59            }
60            else if (type == int.class) {
61                return f.isFinal() && !isWriteAllowedOnFinalFields
62                       ? new VarHandleInts.FieldInstanceReadOnly(refc, foffset)
63                       : new VarHandleInts.FieldInstanceReadWrite(refc, foffset);
64            }
65            else if (type == long.class) {
66                return f.isFinal() && !isWriteAllowedOnFinalFields
67                       ? new VarHandleLongs.FieldInstanceReadOnly(refc, foffset)
68                       : new VarHandleLongs.FieldInstanceReadWrite(refc, foffset);
69            }
70            else if (type == float.class) {
71                return f.isFinal() && !isWriteAllowedOnFinalFields
72                       ? new VarHandleFloats.FieldInstanceReadOnly(refc, foffset)
73                       : new VarHandleFloats.FieldInstanceReadWrite(refc, foffset);
74            }
75            else if (type == double.class) {
76                return f.isFinal() && !isWriteAllowedOnFinalFields
77                       ? new VarHandleDoubles.FieldInstanceReadOnly(refc, foffset)
78                       : new VarHandleDoubles.FieldInstanceReadWrite(refc, foffset);
79            }
80            else {
81                throw new UnsupportedOperationException();
82            }
83        }
84        else {
85            // TODO This is not lazy on first invocation
86            // and might cause some circular initialization issues
87
88            // Replace with something similar to direct method handles
89            // where a barrier is used then elided after use
90
91            if (UNSAFE.shouldBeInitialized(refc))
92                UNSAFE.ensureClassInitialized(refc);
93
94            Object base = MethodHandleNatives.staticFieldBase(f);
95            long foffset = MethodHandleNatives.staticFieldOffset(f);
96            if (!type.isPrimitive()) {
97                return f.isFinal() && !isWriteAllowedOnFinalFields
98                       ? new VarHandleObjects.FieldStaticReadOnly(base, foffset, type)
99                       : new VarHandleObjects.FieldStaticReadWrite(base, foffset, type);
100            }
101            else if (type == boolean.class) {
102                return f.isFinal() && !isWriteAllowedOnFinalFields
103                       ? new VarHandleBooleans.FieldStaticReadOnly(base, foffset)
104                       : new VarHandleBooleans.FieldStaticReadWrite(base, foffset);
105            }
106            else if (type == byte.class) {
107                return f.isFinal() && !isWriteAllowedOnFinalFields
108                       ? new VarHandleBytes.FieldStaticReadOnly(base, foffset)
109                       : new VarHandleBytes.FieldStaticReadWrite(base, foffset);
110            }
111            else if (type == short.class) {
112                return f.isFinal() && !isWriteAllowedOnFinalFields
113                       ? new VarHandleShorts.FieldStaticReadOnly(base, foffset)
114                       : new VarHandleShorts.FieldStaticReadWrite(base, foffset);
115            }
116            else if (type == char.class) {
117                return f.isFinal() && !isWriteAllowedOnFinalFields
118                       ? new VarHandleChars.FieldStaticReadOnly(base, foffset)
119                       : new VarHandleChars.FieldStaticReadWrite(base, foffset);
120            }
121            else if (type == int.class) {
122                return f.isFinal() && !isWriteAllowedOnFinalFields
123                       ? new VarHandleInts.FieldStaticReadOnly(base, foffset)
124                       : new VarHandleInts.FieldStaticReadWrite(base, foffset);
125            }
126            else if (type == long.class) {
127                return f.isFinal() && !isWriteAllowedOnFinalFields
128                       ? new VarHandleLongs.FieldStaticReadOnly(base, foffset)
129                       : new VarHandleLongs.FieldStaticReadWrite(base, foffset);
130            }
131            else if (type == float.class) {
132                return f.isFinal() && !isWriteAllowedOnFinalFields
133                       ? new VarHandleFloats.FieldStaticReadOnly(base, foffset)
134                       : new VarHandleFloats.FieldStaticReadWrite(base, foffset);
135            }
136            else if (type == double.class) {
137                return f.isFinal() && !isWriteAllowedOnFinalFields
138                       ? new VarHandleDoubles.FieldStaticReadOnly(base, foffset)
139                       : new VarHandleDoubles.FieldStaticReadWrite(base, foffset);
140            }
141            else {
142                throw new UnsupportedOperationException();
143            }
144        }
145    }
146
147    static VarHandle makeArrayElementHandle(Class<?> arrayClass) {
148        if (!arrayClass.isArray())
149            throw new IllegalArgumentException("not an array: " + arrayClass);
150
151        Class<?> componentType = arrayClass.getComponentType();
152
153        int aoffset = UNSAFE.arrayBaseOffset(arrayClass);
154        int ascale = UNSAFE.arrayIndexScale(arrayClass);
155        int ashift = 31 - Integer.numberOfLeadingZeros(ascale);
156
157        if (!componentType.isPrimitive()) {
158            return new VarHandleObjects.Array(aoffset, ashift, arrayClass);
159        }
160        else if (componentType == boolean.class) {
161            return new VarHandleBooleans.Array(aoffset, ashift);
162        }
163        else if (componentType == byte.class) {
164            return new VarHandleBytes.Array(aoffset, ashift);
165        }
166        else if (componentType == short.class) {
167            return new VarHandleShorts.Array(aoffset, ashift);
168        }
169        else if (componentType == char.class) {
170            return new VarHandleChars.Array(aoffset, ashift);
171        }
172        else if (componentType == int.class) {
173            return new VarHandleInts.Array(aoffset, ashift);
174        }
175        else if (componentType == long.class) {
176            return new VarHandleLongs.Array(aoffset, ashift);
177        }
178        else if (componentType == float.class) {
179            return new VarHandleFloats.Array(aoffset, ashift);
180        }
181        else if (componentType == double.class) {
182            return new VarHandleDoubles.Array(aoffset, ashift);
183        }
184        else {
185            throw new UnsupportedOperationException();
186        }
187    }
188
189    static VarHandle byteArrayViewHandle(Class<?> viewArrayClass,
190                                         boolean be) {
191        if (!viewArrayClass.isArray())
192            throw new IllegalArgumentException("not an array: " + viewArrayClass);
193
194        Class<?> viewComponentType = viewArrayClass.getComponentType();
195
196        if (viewComponentType == long.class) {
197            return new VarHandleByteArrayAsLongs.ArrayHandle(be);
198        }
199        else if (viewComponentType == int.class) {
200            return new VarHandleByteArrayAsInts.ArrayHandle(be);
201        }
202        else if (viewComponentType == short.class) {
203            return new VarHandleByteArrayAsShorts.ArrayHandle(be);
204        }
205        else if (viewComponentType == char.class) {
206            return new VarHandleByteArrayAsChars.ArrayHandle(be);
207        }
208        else if (viewComponentType == double.class) {
209            return new VarHandleByteArrayAsDoubles.ArrayHandle(be);
210        }
211        else if (viewComponentType == float.class) {
212            return new VarHandleByteArrayAsFloats.ArrayHandle(be);
213        }
214
215        throw new UnsupportedOperationException();
216    }
217
218    static VarHandle makeByteBufferViewHandle(Class<?> viewArrayClass,
219                                              boolean be) {
220        if (!viewArrayClass.isArray())
221            throw new IllegalArgumentException("not an array: " + viewArrayClass);
222
223        Class<?> viewComponentType = viewArrayClass.getComponentType();
224
225        if (viewComponentType == long.class) {
226            return new VarHandleByteArrayAsLongs.ByteBufferHandle(be);
227        }
228        else if (viewComponentType == int.class) {
229            return new VarHandleByteArrayAsInts.ByteBufferHandle(be);
230        }
231        else if (viewComponentType == short.class) {
232            return new VarHandleByteArrayAsShorts.ByteBufferHandle(be);
233        }
234        else if (viewComponentType == char.class) {
235            return new VarHandleByteArrayAsChars.ByteBufferHandle(be);
236        }
237        else if (viewComponentType == double.class) {
238            return new VarHandleByteArrayAsDoubles.ByteBufferHandle(be);
239        }
240        else if (viewComponentType == float.class) {
241            return new VarHandleByteArrayAsFloats.ByteBufferHandle(be);
242        }
243
244        throw new UnsupportedOperationException();
245    }
246
247//    /**
248//     * A helper program to generate the VarHandleGuards class with a set of
249//     * static guard methods each of which corresponds to a particular shape and
250//     * performs a type check of the symbolic type descriptor with the VarHandle
251//     * type descriptor before linking/invoking to the underlying operation as
252//     * characterized by the operation member name on the VarForm of the
253//     * VarHandle.
254//     * <p>
255//     * The generated class essentially encapsulates pre-compiled LambdaForms,
256//     * one for each method, for the most set of common method signatures.
257//     * This reduces static initialization costs, footprint costs, and circular
258//     * dependencies that may arise if a class is generated per LambdaForm.
259//     * <p>
260//     * A maximum of L*T*S methods will be generated where L is the number of
261//     * access modes kinds (or unique operation signatures) and T is the number
262//     * of variable types and S is the number of shapes (such as instance field,
263//     * static field, or array access).
264//     * If there are 4 unique operation signatures, 5 basic types (Object, int,
265//     * long, float, double), and 3 shapes then a maximum of 60 methods will be
266//     * generated.  However, the number is likely to be less since there
267//     * be duplicate signatures.
268//     * <p>
269//     * Each method is annotated with @LambdaForm.Compiled to inform the runtime
270//     * that such methods should be treated as if a method of a class that is the
271//     * result of compiling a LambdaForm.  Annotation of such methods is
272//     * important for correct evaluation of certain assertions and method return
273//     * type profiling in HotSpot.
274//     */
275//    public static class GuardMethodGenerator {
276//
277//        static final String GUARD_METHOD_SIG_TEMPLATE = "<RETURN> <NAME>_<SIGNATURE>(<PARAMS>)";
278//
279//        static final String GUARD_METHOD_TEMPLATE =
280//                "@ForceInline\n" +
281//                "@LambdaForm.Compiled\n" +
282//                "final static <METHOD> throws Throwable {\n" +
283//                "    MethodType target = VarHandle.AccessType.getMethodType(ad.type, handle);\n" +
284//                "    MethodType symbolic = ad.symbolicMethodType;\n" +
285//                "    if (target == symbolic) {\n" +
286//                "        <RETURN>MethodHandle.linkToStatic(<LINK_TO_STATIC_ARGS>);\n" +
287//                "    }\n" +
288//                "    else if (target.erase() == symbolic.erase()) {\n" +
289//                "        <RESULT_ERASED>MethodHandle.linkToStatic(<LINK_TO_STATIC_ARGS>);<RETURN_ERASED>\n" +
290//                "    }\n" +
291//                "    else {\n" +
292//                "        MethodHandle vh_invoker = MethodHandles.varHandleInvoker(VarHandle.AccessMode.values()[ad.mode], symbolic);\n" +
293//                "        <RETURN>vh_invoker.invokeBasic(<LINK_TO_INVOKER_ARGS>);\n" +
294//                "    }\n" +
295//                "}";
296//
297//        static final String GET_MEMBER_NAME_METHOD =
298//                "@ForceInline\n" +
299//                "final static MemberName getMemberName(VarHandle handle, VarHandle.AccessDescriptor ad) {\n" +
300//                "    MemberName mn = VarHandle.AccessMode.getMemberName(ad.mode, handle.vform);\n" +
301//                "    if (mn == null) {\n" +
302//                "        throw handle.unsupported();\n" +
303//                "    }\n" +
304//                "    return mn;\n" +
305//                "}";
306//
307//        // A template for deriving the operations
308//        // could be supported by annotating VarHandle directly with the
309//        // operation kind and shape
310//        interface VarHandleTemplate {
311//            Object get();
312//
313//            void set(Object value);
314//
315//            boolean compareAndSwap(Object actualValue, Object expectedValue);
316//
317//            Object compareAndExchange(Object actualValue, Object expectedValue);
318//
319//            Object getAndUpdate(Object value);
320//        }
321//
322//        static class HandleType {
323//            final Class<?> receiver;
324//            final Class<?>[] intermediates;
325//            final Class<?> value;
326//
327//            HandleType(Class<?> receiver, Class<?> value, Class<?>... intermediates) {
328//                this.receiver = receiver;
329//                this.intermediates = intermediates;
330//                this.value = value;
331//            }
332//        }
333//
334//        /**
335//         * @param args parameters
336//         */
337//        public static void main(String[] args) {
338//            System.out.println("package java.lang.invoke;");
339//            System.out.println();
340//            System.out.println("import jdk.internal.vm.annotation.ForceInline;");
341//            System.out.println();
342//            System.out.println("// This class is auto-generated by " +
343//                               GuardMethodGenerator.class.getName() +
344//                               ". Do not edit.");
345//            System.out.println("final class VarHandleGuards {");
346//
347//            System.out.println();
348//            System.out.println(GET_MEMBER_NAME_METHOD);
349//            System.out.println();
350//
351//            // Declare the stream of shapes
352//            Stream<HandleType> hts = Stream.of(
353//                    // Object->Object
354//                    new HandleType(Object.class, Object.class),
355//                    // Object->int
356//                    new HandleType(Object.class, int.class),
357//                    // Object->long
358//                    new HandleType(Object.class, long.class),
359//                    // Object->float
360//                    new HandleType(Object.class, float.class),
361//                    // Object->double
362//                    new HandleType(Object.class, double.class),
363//
364//                    // <static>->Object
365//                    new HandleType(null, Object.class),
366//                    // <static>->int
367//                    new HandleType(null, int.class),
368//                    // <static>->long
369//                    new HandleType(null, long.class),
370//                    // <static>->float
371//                    new HandleType(null, float.class),
372//                    // <static>->double
373//                    new HandleType(null, double.class),
374//
375//                    // Array[int]->Object
376//                    new HandleType(Object.class, Object.class, int.class),
377//                    // Array[int]->int
378//                    new HandleType(Object.class, int.class, int.class),
379//                    // Array[int]->long
380//                    new HandleType(Object.class, long.class, int.class),
381//                    // Array[int]->float
382//                    new HandleType(Object.class, float.class, int.class),
383//                    // Array[int]->double
384//                    new HandleType(Object.class, double.class, int.class),
385//
386//                    // Array[long]->int
387//                    new HandleType(Object.class, int.class, long.class),
388//                    // Array[long]->long
389//                    new HandleType(Object.class, long.class, long.class)
390//            );
391//
392//            hts.flatMap(ht -> Stream.of(VarHandleTemplate.class.getMethods()).
393//                    map(m -> generateMethodType(m, ht.receiver, ht.value, ht.intermediates))).
394//                    distinct().
395//                    map(mt -> generateMethod(mt)).
396//                    forEach(s -> {
397//                        System.out.println(s);
398//                        System.out.println();
399//                    });
400//
401//            System.out.println("}");
402//        }
403//
404//        static MethodType generateMethodType(Method m, Class<?> receiver, Class<?> value, Class<?>... intermediates) {
405//            Class<?> returnType = m.getReturnType() == Object.class
406//                                  ? value : m.getReturnType();
407//
408//            List<Class<?>> params = new ArrayList<>();
409//            if (receiver != null)
410//                params.add(receiver);
411//            for (int i = 0; i < intermediates.length; i++) {
412//                params.add(intermediates[i]);
413//            }
414//            for (Parameter p : m.getParameters()) {
415//                params.add(value);
416//            }
417//            return MethodType.methodType(returnType, params);
418//        }
419//
420//        static String generateMethod(MethodType mt) {
421//            Class<?> returnType = mt.returnType();
422//
423//            LinkedHashMap<String, Class<?>> params = new LinkedHashMap<>();
424//            params.put("handle", VarHandle.class);
425//            for (int i = 0; i < mt.parameterCount(); i++) {
426//                params.put("arg" + i, mt.parameterType(i));
427//            }
428//            params.put("ad", VarHandle.AccessDescriptor.class);
429//
430//            // Generate method signature line
431//            String RETURN = className(returnType);
432//            String NAME = "guard";
433//            String SIGNATURE = getSignature(mt);
434//            String PARAMS = params.entrySet().stream().
435//                    map(e -> className(e.getValue()) + " " + e.getKey()).
436//                    collect(joining(", "));
437//            String METHOD = GUARD_METHOD_SIG_TEMPLATE.
438//                    replace("<RETURN>", RETURN).
439//                    replace("<NAME>", NAME).
440//                    replace("<SIGNATURE>", SIGNATURE).
441//                    replace("<PARAMS>", PARAMS);
442//
443//            // Generate method
444//            params.remove("ad");
445//
446//            List<String> LINK_TO_STATIC_ARGS = params.keySet().stream().
447//                    collect(toList());
448//            LINK_TO_STATIC_ARGS.add("getMemberName(handle, ad)");
449//
450//            List<String> LINK_TO_INVOKER_ARGS = params.keySet().stream().
451//                    collect(toList());
452//
453//            RETURN = returnType == void.class
454//                     ? ""
455//                     : returnType == Object.class
456//                       ? "return "
457//                       : "return (" + returnType.getName() + ") ";
458//
459//            String RESULT_ERASED = returnType == void.class
460//                                   ? ""
461//                                   : returnType != Object.class
462//                                     ? "return (" + returnType.getName() + ") "
463//                                     : "Object r = ";
464//
465//            String RETURN_ERASED = returnType != Object.class
466//                                   ? ""
467//                                   : " return symbolic.returnType().cast(r);";
468//
469//            return GUARD_METHOD_TEMPLATE.
470//                    replace("<METHOD>", METHOD).
471//                    replace("<NAME>", NAME).
472//                    replaceAll("<RETURN>", RETURN).
473//                    replace("<RESULT_ERASED>", RESULT_ERASED).
474//                    replace("<RETURN_ERASED>", RETURN_ERASED).
475//                    replaceAll("<LINK_TO_STATIC_ARGS>", LINK_TO_STATIC_ARGS.stream().
476//                            collect(joining(", "))).
477//                    replace("<LINK_TO_INVOKER_ARGS>", LINK_TO_INVOKER_ARGS.stream().
478//                            collect(joining(", ")))
479//                    ;
480//        }
481//
482//        static String className(Class<?> c) {
483//            String n = c.getName();
484//            if (n.startsWith("java.lang.")) {
485//                n = n.replace("java.lang.", "");
486//                if (n.startsWith("invoke.")) {
487//                    n = n.replace("invoke.", "");
488//                }
489//            }
490//            return n.replace('$', '.');
491//        }
492//
493//        static String getSignature(MethodType m) {
494//            StringBuilder sb = new StringBuilder(m.parameterCount() + 1);
495//
496//            for (int i = 0; i < m.parameterCount(); i++) {
497//                Class<?> pt = m.parameterType(i);
498//                sb.append(getCharType(pt));
499//            }
500//
501//            sb.append('_').append(getCharType(m.returnType()));
502//
503//            return sb.toString();
504//        }
505//
506//        static char getCharType(Class<?> pt) {
507//            if (pt == void.class) {
508//                return 'V';
509//            }
510//            else if (!pt.isPrimitive()) {
511//                return 'L';
512//            }
513//            else if (pt == boolean.class) {
514//                return 'Z';
515//            }
516//            else if (pt == int.class) {
517//                return 'I';
518//            }
519//            else if (pt == long.class) {
520//                return 'J';
521//            }
522//            else if (pt == float.class) {
523//                return 'F';
524//            }
525//            else if (pt == double.class) {
526//                return 'D';
527//            }
528//            else {
529//                throw new IllegalStateException(pt.getName());
530//            }
531//        }
532//    }
533}
534