NashornCallSiteDescriptor.java revision 1483:7cb19fa78763
1/*
2 * Copyright (c) 2010, 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
26package jdk.nashorn.internal.runtime.linker;
27
28import java.lang.invoke.MethodHandles;
29import java.lang.invoke.MethodHandles.Lookup;
30import java.lang.invoke.MethodType;
31import java.security.AccessControlContext;
32import java.security.AccessController;
33import java.security.PrivilegedAction;
34import java.util.concurrent.ConcurrentHashMap;
35import java.util.concurrent.ConcurrentMap;
36import jdk.internal.dynalink.CallSiteDescriptor;
37import jdk.internal.dynalink.CompositeOperation;
38import jdk.internal.dynalink.NamedOperation;
39import jdk.internal.dynalink.Operation;
40import jdk.internal.dynalink.StandardOperation;
41import jdk.internal.dynalink.support.NameCodec;
42import jdk.nashorn.internal.ir.debug.NashornTextifier;
43import jdk.nashorn.internal.runtime.AccessControlContextFactory;
44import jdk.nashorn.internal.runtime.ScriptRuntime;
45
46/**
47 * Nashorn-specific implementation of Dynalink's {@link CallSiteDescriptor}.
48 * The reason we have our own subclass is that we're storing flags in an
49 * additional primitive field. The class also exposes some useful utilities in
50 * form of static methods.
51 */
52public final class NashornCallSiteDescriptor extends CallSiteDescriptor {
53    // Lowest three bits describe the operation
54    /** Property getter operation {@code obj.prop} */
55    public static final int GET_PROPERTY        = 0;
56    /** Element getter operation {@code obj[index]} */
57    public static final int GET_ELEMENT         = 1;
58    /** Property getter operation, subsequently invoked {@code obj.prop()} */
59    public static final int GET_METHOD_PROPERTY = 2;
60    /** Element getter operation, subsequently invoked {@code obj[index]()} */
61    public static final int GET_METHOD_ELEMENT  = 3;
62    /** Property setter operation {@code obj.prop = value} */
63    public static final int SET_PROPERTY        = 4;
64    /** Element setter operation {@code obj[index] = value} */
65    public static final int SET_ELEMENT         = 5;
66    /** Call operation {@code fn(args...)} */
67    public static final int CALL                = 6;
68    /** New operation {@code new Constructor(args...)} */
69    public static final int NEW                 = 7;
70
71    private static final int OPERATION_MASK = 7;
72
73    // Correspond to the operation indices above.
74    private static final Operation[] OPERATIONS = new Operation[] {
75        new CompositeOperation(StandardOperation.GET_PROPERTY, StandardOperation.GET_ELEMENT, StandardOperation.GET_METHOD),
76        new CompositeOperation(StandardOperation.GET_ELEMENT, StandardOperation.GET_PROPERTY, StandardOperation.GET_METHOD),
77        new CompositeOperation(StandardOperation.GET_METHOD, StandardOperation.GET_PROPERTY, StandardOperation.GET_ELEMENT),
78        new CompositeOperation(StandardOperation.GET_METHOD, StandardOperation.GET_ELEMENT, StandardOperation.GET_PROPERTY),
79        new CompositeOperation(StandardOperation.SET_PROPERTY, StandardOperation.SET_ELEMENT),
80        new CompositeOperation(StandardOperation.SET_ELEMENT, StandardOperation.SET_PROPERTY),
81        StandardOperation.CALL,
82        StandardOperation.NEW
83    };
84
85    /** Flags that the call site references a scope variable (it's an identifier reference or a var declaration, not a
86     * property access expression. */
87    public static final int CALLSITE_SCOPE         = 1 << 3;
88    /** Flags that the call site is in code that uses ECMAScript strict mode. */
89    public static final int CALLSITE_STRICT        = 1 << 4;
90    /** Flags that a property getter or setter call site references a scope variable that is located at a known distance
91     * in the scope chain. Such getters and setters can often be linked more optimally using these assumptions. */
92    public static final int CALLSITE_FAST_SCOPE    = 1 << 5;
93    /** Flags that a callsite type is optimistic, i.e. we might get back a wider return value than encoded in the
94     * descriptor, and in that case we have to throw an UnwarrantedOptimismException */
95    public static final int CALLSITE_OPTIMISTIC    = 1 << 6;
96    /** Is this really an apply that we try to call as a call? */
97    public static final int CALLSITE_APPLY_TO_CALL = 1 << 7;
98    /** Does this a callsite for a variable declaration? */
99    public static final int CALLSITE_DECLARE       = 1 << 8;
100
101    /** Flags that the call site is profiled; Contexts that have {@code "profile.callsites"} boolean property set emit
102     * code where call sites have this flag set. */
103    public static final int CALLSITE_PROFILE         = 1 << 9;
104    /** Flags that the call site is traced; Contexts that have {@code "trace.callsites"} property set emit code where
105     * call sites have this flag set. */
106    public static final int CALLSITE_TRACE           = 1 << 10;
107    /** Flags that the call site linkage miss (and thus, relinking) is traced; Contexts that have the keyword
108     * {@code "miss"} in their {@code "trace.callsites"} property emit code where call sites have this flag set. */
109    public static final int CALLSITE_TRACE_MISSES    = 1 << 11;
110    /** Flags that entry/exit to/from the method linked at call site are traced; Contexts that have the keyword
111     * {@code "enterexit"} in their {@code "trace.callsites"} property emit code where call sites have this flag set. */
112    public static final int CALLSITE_TRACE_ENTEREXIT = 1 << 12;
113    /** Flags that values passed as arguments to and returned from the method linked at call site are traced; Contexts
114     * that have the keyword {@code "values"} in their {@code "trace.callsites"} property emit code where call sites
115     * have this flag set. */
116    public static final int CALLSITE_TRACE_VALUES    = 1 << 13;
117
118    //we could have more tracing flags here, for example CALLSITE_TRACE_SCOPE, but bits are a bit precious
119    //right now given the program points
120
121    /**
122     * Number of bits the program point is shifted to the left in the flags (lowest bit containing a program point).
123     * Always one larger than the largest flag shift. Note that introducing a new flag halves the number of program
124     * points we can have.
125     * TODO: rethink if we need the various profile/trace flags or the linker can use the Context instead to query its
126     * trace/profile settings.
127     */
128    public static final int CALLSITE_PROGRAM_POINT_SHIFT = 14;
129
130    /**
131     * Maximum program point value. We have 18 bits left over after flags, and
132     * it should be plenty. Program points are local to a single function. Every
133     * function maps to a single JVM bytecode method that can have at most 65535
134     * bytes. (Large functions are synthetically split into smaller functions.)
135     * A single invokedynamic is 5 bytes; even if a method consists of only
136     * invokedynamic instructions that leaves us with at most 65535/5 = 13107
137     * program points for the largest single method; those can be expressed on
138     * 14 bits. It is true that numbering of program points is independent of
139     * bytecode representation, but if a function would need more than ~14 bits
140     * for the program points, then it is reasonable to presume splitter
141     * would've split it into several smaller functions already.
142     */
143    public static final int MAX_PROGRAM_POINT_VALUE = (1 << 32 - CALLSITE_PROGRAM_POINT_SHIFT) - 1;
144
145    /**
146     * Flag mask to get the program point flags
147     */
148    public static final int FLAGS_MASK = (1 << CALLSITE_PROGRAM_POINT_SHIFT) - 1;
149
150    private static final ClassValue<ConcurrentMap<NashornCallSiteDescriptor, NashornCallSiteDescriptor>> canonicals =
151            new ClassValue<ConcurrentMap<NashornCallSiteDescriptor,NashornCallSiteDescriptor>>() {
152        @Override
153        protected ConcurrentMap<NashornCallSiteDescriptor, NashornCallSiteDescriptor> computeValue(final Class<?> type) {
154            return new ConcurrentHashMap<>();
155        }
156    };
157
158    private static final AccessControlContext GET_LOOKUP_PERMISSION_CONTEXT =
159            AccessControlContextFactory.createAccessControlContext(CallSiteDescriptor.GET_LOOKUP_PERMISSION_NAME);
160
161    private final int flags;
162
163    /**
164     * Function used by {@link NashornTextifier} to represent call site flags in
165     * human readable form
166     * @param flags call site flags
167     * @return human readable form of this callsite descriptor
168     */
169    public static String toString(final int flags) {
170        final StringBuilder sb = new StringBuilder();
171        if ((flags & CALLSITE_SCOPE) != 0) {
172            if ((flags & CALLSITE_FAST_SCOPE) != 0) {
173                sb.append("fastscope ");
174            } else {
175                assert (flags & CALLSITE_FAST_SCOPE) == 0 : "can't be fastscope without scope";
176                sb.append("scope ");
177            }
178            if ((flags & CALLSITE_DECLARE) != 0) {
179                sb.append("declare ");
180            }
181        }
182        if ((flags & CALLSITE_APPLY_TO_CALL) != 0) {
183            sb.append("apply2call ");
184        }
185        if ((flags & CALLSITE_STRICT) != 0) {
186            sb.append("strict ");
187        }
188        return sb.length() == 0 ? "" : " " + sb.toString().trim();
189    }
190
191    /**
192     * Given call site flags, returns the operation name encoded in them.
193     * @param flags flags
194     * @return the operation name
195     */
196    public static String getOperationName(final int flags) {
197        switch(flags & OPERATION_MASK) {
198        case 0: return "GET_PROPERTY";
199        case 1: return "GET_ELEMENT";
200        case 2: return "GET_METHOD_PROPERTY";
201        case 3: return "GET_METHOD_ELEMENT";
202        case 4: return "SET_PROPERTY";
203        case 5: return "SET_ELEMENT";
204        case 6: return "CALL";
205        case 7: return "NEW";
206        default: throw new AssertionError();
207        }
208    }
209
210    /**
211     * Retrieves a Nashorn call site descriptor with the specified values. Since call site descriptors are immutable
212     * this method is at liberty to retrieve canonicalized instances (although it is not guaranteed it will do so).
213     * @param lookup the lookup describing the script
214     * @param name the name at the call site. Can not be null, but it can be empty.
215     * @param methodType the method type at the call site
216     * @param flags Nashorn-specific call site flags
217     * @return a call site descriptor with the specified values.
218     */
219    public static NashornCallSiteDescriptor get(final MethodHandles.Lookup lookup, final String name,
220            final MethodType methodType, final int flags) {
221        final Operation baseOp = OPERATIONS[flags & OPERATION_MASK];
222        final String decodedName = NameCodec.decode(name);
223        // TODO: introduce caching of NamedOperation
224        final Operation op = decodedName.isEmpty() ? baseOp : new NamedOperation(baseOp, decodedName);
225        return get(lookup, op, methodType, flags);
226    }
227
228    private static NashornCallSiteDescriptor get(final MethodHandles.Lookup lookup, final Operation operation, final MethodType methodType, final int flags) {
229        final NashornCallSiteDescriptor csd = new NashornCallSiteDescriptor(lookup, operation, methodType, flags);
230        // Many of these call site descriptors are identical (e.g. every getter for a property color will be
231        // "GET_PROPERTY:color(Object)Object", so it makes sense canonicalizing them.
232        final ConcurrentMap<NashornCallSiteDescriptor, NashornCallSiteDescriptor> classCanonicals = canonicals.get(lookup.lookupClass());
233        final NashornCallSiteDescriptor canonical = classCanonicals.putIfAbsent(csd, csd);
234        return canonical != null ? canonical : csd;
235    }
236
237    private NashornCallSiteDescriptor(final MethodHandles.Lookup lookup, final Operation operation, final MethodType methodType, final int flags) {
238        super(lookup, operation, methodType);
239        this.flags = flags;
240    }
241
242    static Lookup getLookupInternal(final CallSiteDescriptor csd) {
243        if (csd instanceof NashornCallSiteDescriptor) {
244            return ((NashornCallSiteDescriptor)csd).getLookupPrivileged();
245        }
246        return AccessController.doPrivileged((PrivilegedAction<Lookup>)()->csd.getLookup(), GET_LOOKUP_PERMISSION_CONTEXT);
247    }
248
249    @Override
250    public boolean equals(final Object obj) {
251        return super.equals(obj) && flags == ((NashornCallSiteDescriptor)obj).flags;
252    }
253
254    @Override
255    public int hashCode() {
256        return super.hashCode() ^ flags;
257    }
258
259    /**
260     * Returns the named operand in this descriptor's operation. Equivalent to
261     * {@code ((NamedOperation)getOperation()).getName().toString()} for call
262     * sites with a named operand. For call sites without named operands returns null.
263     * @return the named operand in this descriptor's operation.
264     */
265    public String getOperand() {
266        return getOperand(this);
267    }
268
269    /**
270     * Returns the named operand in the passed descriptor's operation.
271     * Equivalent to
272     * {@code ((NamedOperation)desc.getOperation()).getName().toString()} for
273     * descriptors with a named operand. For descriptors without named operands
274     * returns null.
275     * @param desc the call site descriptors
276     * @return the named operand in this descriptor's operation.
277     */
278    public static String getOperand(final CallSiteDescriptor desc) {
279        final Operation operation = desc.getOperation();
280        return operation instanceof NamedOperation ? ((NamedOperation)operation).getName().toString() : null;
281    }
282
283    /**
284     * Returns the first operation in this call site descriptor's potentially
285     * composite operation. E.g. if this call site descriptor has a composite
286     * operation {@code GET_PROPERTY|GET_METHOD|GET_ELEM}, it will return
287     * {@code GET_PROPERTY}. Nashorn - being a ECMAScript engine - does not
288     * distinguish between property, element, and method namespace; ECMAScript
289     * objects just have one single property namespace for all these, therefore
290     * it is largely irrelevant what the composite operation is structured like;
291     * if the first operation can't be satisfied, neither can the others. The
292     * first operation is however sometimes used to slightly alter the
293     * semantics; for example, a distinction between {@code GET_PROPERTY} and
294     * {@code GET_METHOD} being the first operation can translate into whether
295     * {@code "__noSuchProperty__"} or {@code "__noSuchMethod__"} will be
296     * executed in case the property is not found. Note that if a call site
297     * descriptor comes from outside of Nashorn, its class will be different,
298     * and there is no guarantee about the way it composes its operations. For
299     * that reason, for potentially foreign call site descriptors you should use
300     * {@link #getFirstStandardOperation(CallSiteDescriptor)} instead.
301     * @return the first operation in this call site descriptor. Note this will
302     * always be a {@code StandardOperation} as Nashorn internally only uses
303     * standard operations.
304     */
305    public StandardOperation getFirstOperation() {
306        final Operation base = NamedOperation.getBaseOperation(getOperation());
307        if (base instanceof CompositeOperation) {
308            return (StandardOperation)((CompositeOperation)base).getOperation(0);
309        }
310        return (StandardOperation)base;
311    }
312
313    /**
314     * Returns the first standard operation in the (potentially composite)
315     * operation of the passed call site descriptor.
316     * @param desc the call site descriptor.
317     * @return Returns the first standard operation in the (potentially
318     * composite) operation of the passed call site descriptor. Can return null
319     * if the call site contains no standard operations.
320     */
321    public static StandardOperation getFirstStandardOperation(final CallSiteDescriptor desc) {
322        final Operation base = NamedOperation.getBaseOperation(desc.getOperation());
323        if (base instanceof StandardOperation) {
324            return (StandardOperation)base;
325        } else if (base instanceof CompositeOperation) {
326            final CompositeOperation cop = (CompositeOperation)base;
327            for(int i = 0; i < cop.getOperationCount(); ++i) {
328                final Operation op = cop.getOperation(i);
329                if (op instanceof StandardOperation) {
330                    return (StandardOperation)op;
331                }
332            }
333        }
334        return null;
335    }
336
337    /**
338     * Returns the error message to be used when CALL or NEW is used on a non-function.
339     *
340     * @param obj object on which CALL or NEW is used
341     * @return error message
342     */
343    public String getFunctionErrorMessage(final Object obj) {
344        final String funcDesc = getOperand();
345        return funcDesc != null? funcDesc : ScriptRuntime.safeToString(obj);
346    }
347
348    /**
349     * Returns the error message to be used when CALL or NEW is used on a non-function.
350     *
351     * @param desc call site descriptor
352     * @param obj object on which CALL or NEW is used
353     * @return error message
354     */
355    public static String getFunctionErrorMessage(final CallSiteDescriptor desc, final Object obj) {
356        return desc instanceof NashornCallSiteDescriptor ?
357                ((NashornCallSiteDescriptor)desc).getFunctionErrorMessage(obj) :
358                ScriptRuntime.safeToString(obj);
359    }
360
361    /**
362     * Returns the Nashorn-specific flags for this call site descriptor.
363     * @param desc the descriptor. It can be any kind of a call site descriptor, not necessarily a
364     * {@code NashornCallSiteDescriptor}. This allows for graceful interoperability when linking Nashorn with code
365     * generated outside of Nashorn.
366     * @return the Nashorn-specific flags for the call site, or 0 if the passed descriptor is not a Nashorn call site
367     * descriptor.
368     */
369    public static int getFlags(final CallSiteDescriptor desc) {
370        return desc instanceof NashornCallSiteDescriptor ? ((NashornCallSiteDescriptor)desc).flags : 0;
371    }
372
373    /**
374     * Returns true if this descriptor has the specified flag set, see {@code CALLSITE_*} constants in this class.
375     * @param flag the tested flag
376     * @return true if the flag is set, false otherwise
377     */
378    private boolean isFlag(final int flag) {
379        return (flags & flag) != 0;
380    }
381
382    /**
383     * Returns true if this descriptor has the specified flag set, see {@code CALLSITE_*} constants in this class.
384     * @param desc the descriptor. It can be any kind of a call site descriptor, not necessarily a
385     * {@code NashornCallSiteDescriptor}. This allows for graceful interoperability when linking Nashorn with code
386     * generated outside of Nashorn.
387     * @param flag the tested flag
388     * @return true if the flag is set, false otherwise (it will be false if the descriptor is not a Nashorn call site
389     * descriptor).
390     */
391    private static boolean isFlag(final CallSiteDescriptor desc, final int flag) {
392        return (getFlags(desc) & flag) != 0;
393    }
394
395    /**
396     * Returns true if this descriptor is a Nashorn call site descriptor and has the {@link  #CALLSITE_SCOPE} flag set.
397     * @param desc the descriptor. It can be any kind of a call site descriptor, not necessarily a
398     * {@code NashornCallSiteDescriptor}. This allows for graceful interoperability when linking Nashorn with code
399     * generated outside of Nashorn.
400     * @return true if the descriptor is a Nashorn call site descriptor, and the flag is set, false otherwise.
401     */
402    public static boolean isScope(final CallSiteDescriptor desc) {
403        return isFlag(desc, CALLSITE_SCOPE);
404    }
405
406    /**
407     * Returns true if this descriptor is a Nashorn call site descriptor and has the {@link  #CALLSITE_FAST_SCOPE} flag set.
408     * @param desc the descriptor. It can be any kind of a call site descriptor, not necessarily a
409     * {@code NashornCallSiteDescriptor}. This allows for graceful interoperability when linking Nashorn with code
410     * generated outside of Nashorn.
411     * @return true if the descriptor is a Nashorn call site descriptor, and the flag is set, false otherwise.
412     */
413    public static boolean isFastScope(final CallSiteDescriptor desc) {
414        return isFlag(desc, CALLSITE_FAST_SCOPE);
415    }
416
417    /**
418     * Returns true if this descriptor is a Nashorn call site descriptor and has the {@link  #CALLSITE_STRICT} flag set.
419     * @param desc the descriptor. It can be any kind of a call site descriptor, not necessarily a
420     * {@code NashornCallSiteDescriptor}. This allows for graceful interoperability when linking Nashorn with code
421     * generated outside of Nashorn.
422     * @return true if the descriptor is a Nashorn call site descriptor, and the flag is set, false otherwise.
423     */
424    public static boolean isStrict(final CallSiteDescriptor desc) {
425        return isFlag(desc, CALLSITE_STRICT);
426    }
427
428    /**
429     * Returns true if this is an apply call that we try to call as
430     * a "call"
431     * @param desc descriptor
432     * @return true if apply to call
433     */
434    public static boolean isApplyToCall(final CallSiteDescriptor desc) {
435        return isFlag(desc, CALLSITE_APPLY_TO_CALL);
436    }
437
438    /**
439     * Is this an optimistic call site
440     * @param desc descriptor
441     * @return true if optimistic
442     */
443    public static boolean isOptimistic(final CallSiteDescriptor desc) {
444        return isFlag(desc, CALLSITE_OPTIMISTIC);
445    }
446
447    /**
448     * Does this callsite contain a declaration for its target?
449     * @param desc descriptor
450     * @return true if contains declaration
451     */
452    public static boolean isDeclaration(final CallSiteDescriptor desc) {
453        return isFlag(desc, CALLSITE_DECLARE);
454    }
455
456    /**
457     * Returns true if {@code flags} has the {@link  #CALLSITE_STRICT} bit set.
458     * @param flags the flags
459     * @return true if the flag is set, false otherwise.
460     */
461    public static boolean isStrictFlag(final int flags) {
462        return (flags & CALLSITE_STRICT) != 0;
463    }
464
465    /**
466     * Returns true if {@code flags} has the {@link  #CALLSITE_SCOPE} bit set.
467     * @param flags the flags
468     * @return true if the flag is set, false otherwise.
469     */
470    public static boolean isScopeFlag(final int flags) {
471        return (flags & CALLSITE_SCOPE) != 0;
472    }
473
474    /**
475     * Get a program point from a descriptor (must be optimistic)
476     * @param desc descriptor
477     * @return program point
478     */
479    public static int getProgramPoint(final CallSiteDescriptor desc) {
480        assert isOptimistic(desc) : "program point requested from non-optimistic descriptor " + desc;
481        return getFlags(desc) >> CALLSITE_PROGRAM_POINT_SHIFT;
482    }
483
484    boolean isProfile() {
485        return isFlag(CALLSITE_PROFILE);
486    }
487
488    boolean isTrace() {
489        return isFlag(CALLSITE_TRACE);
490    }
491
492    boolean isTraceMisses() {
493        return isFlag(CALLSITE_TRACE_MISSES);
494    }
495
496    boolean isTraceEnterExit() {
497        return isFlag(CALLSITE_TRACE_ENTEREXIT);
498    }
499
500    boolean isTraceObjects() {
501        return isFlag(CALLSITE_TRACE_VALUES);
502    }
503
504    boolean isOptimistic() {
505        return isFlag(CALLSITE_OPTIMISTIC);
506    }
507
508    @Override
509    public CallSiteDescriptor changeMethodTypeInternal(final MethodType newMethodType) {
510        return get(getLookupPrivileged(), getOperation(), newMethodType, flags);
511    }
512}
513