1 /*
   2  * Copyright (c) 2010, 2014, 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 jdk.nashorn.internal.runtime;
  27 
  28 import static jdk.nashorn.internal.lookup.Lookup.MH;
  29 import java.io.IOException;
  30 import java.lang.invoke.MethodHandle;
  31 import java.lang.invoke.MethodHandles;
  32 import java.lang.invoke.MethodType;
  33 import java.util.Collection;
  34 import java.util.Collections;
  35 import java.util.HashSet;
  36 import java.util.Map;
  37 import java.util.Set;
  38 import java.util.TreeMap;
  39 import jdk.internal.dynalink.support.NameCodec;
  40 import jdk.nashorn.internal.codegen.Compiler;
  41 import jdk.nashorn.internal.codegen.Compiler.CompilationPhases;
  42 import jdk.nashorn.internal.codegen.CompilerConstants;
  43 import jdk.nashorn.internal.codegen.FunctionSignature;
  44 import jdk.nashorn.internal.codegen.Namespace;
  45 import jdk.nashorn.internal.codegen.OptimisticTypesPersistence;
  46 import jdk.nashorn.internal.codegen.TypeMap;
  47 import jdk.nashorn.internal.codegen.types.Type;
  48 import jdk.nashorn.internal.ir.FunctionNode;
  49 import jdk.nashorn.internal.ir.LexicalContext;
  50 import jdk.nashorn.internal.ir.visitor.NodeVisitor;
  51 import jdk.nashorn.internal.objects.Global;
  52 import jdk.nashorn.internal.parser.Parser;
  53 import jdk.nashorn.internal.parser.Token;
  54 import jdk.nashorn.internal.parser.TokenType;
  55 import jdk.nashorn.internal.runtime.logging.DebugLogger;
  56 import jdk.nashorn.internal.runtime.logging.Loggable;
  57 import jdk.nashorn.internal.runtime.logging.Logger;
  58 /**
  59  * This is a subclass that represents a script function that may be regenerated,
  60  * for example with specialization based on call site types, or lazily generated.
  61  * The common denominator is that it can get new invokers during its lifespan,
  62  * unlike {@code FinalScriptFunctionData}
  63  */
  64 @Logger(name="recompile")
  65 public final class RecompilableScriptFunctionData extends ScriptFunctionData implements Loggable {
  66     /** Prefix used for all recompiled script classes */
  67     public static final String RECOMPILATION_PREFIX = "Recompilation$";
  68 
  69     /** Unique function node id for this function node */
  70     private final int functionNodeId;
  71 
  72     private final String functionName;
  73 
  74     /** The line number where this function begins. */
  75     private final int lineNumber;
  76 
  77     /** Source from which FunctionNode was parsed. */
  78     private transient Source source;
  79 
  80     /** Serialized, compressed form of the AST. Used by split functions as they can't be reparsed from source. */
  81     private final byte[] serializedAst;
  82 
  83     /** Token of this function within the source. */
  84     private final long token;
  85 
  86     /**
  87      * Represents the allocation strategy (property map, script object class, and method handle) for when
  88      * this function is used as a constructor. Note that majority of functions (those not setting any this.*
  89      * properties) will share a single canonical "default strategy" instance.
  90      */
  91     private final AllocationStrategy allocationStrategy;
  92 
  93     /**
  94      * Opaque object representing parser state at the end of the function. Used when reparsing outer function
  95      * to help with skipping parsing inner functions.
  96      */
  97     private final Object endParserState;
  98 
  99     /** Code installer used for all further recompilation/specialization of this ScriptFunction */
 100     private transient CodeInstaller<ScriptEnvironment> installer;
 101 
 102     private final Map<Integer, RecompilableScriptFunctionData> nestedFunctions;
 103 
 104     /** Id to parent function if one exists */
 105     private RecompilableScriptFunctionData parent;
 106 
 107     /** Copy of the {@link FunctionNode} flags. */
 108     private final int functionFlags;
 109 
 110     private static final MethodHandles.Lookup LOOKUP = MethodHandles.lookup();
 111 
 112     private transient DebugLogger log;
 113 
 114     private final Map<String, Integer> externalScopeDepths;
 115 
 116     private final Set<String> internalSymbols;
 117 
 118     private static final int GET_SET_PREFIX_LENGTH = "*et ".length();
 119 
 120     private static final long serialVersionUID = 4914839316174633726L;
 121 
 122     /**
 123      * Constructor - public as scripts use it
 124      *
 125      * @param functionNode        functionNode that represents this function code
 126      * @param installer           installer for code regeneration versions of this function
 127      * @param allocationStrategy  strategy for the allocation behavior when this function is used as a constructor
 128      * @param nestedFunctions     nested function map
 129      * @param externalScopeDepths external scope depths
 130      * @param internalSymbols     internal symbols to method, defined in its scope
 131      * @param serializedAst       a serialized AST representation. Normally only used for split functions.
 132      */
 133     public RecompilableScriptFunctionData(
 134         final FunctionNode functionNode,
 135         final CodeInstaller<ScriptEnvironment> installer,
 136         final AllocationStrategy allocationStrategy,
 137         final Map<Integer, RecompilableScriptFunctionData> nestedFunctions,
 138         final Map<String, Integer> externalScopeDepths,
 139         final Set<String> internalSymbols,
 140         final byte[] serializedAst) {
 141 
 142         super(functionName(functionNode),
 143               Math.min(functionNode.getParameters().size(), MAX_ARITY),
 144               getDataFlags(functionNode));
 145 
 146         this.functionName        = functionNode.getName();
 147         this.lineNumber          = functionNode.getLineNumber();
 148         this.functionFlags       = functionNode.getFlags() | (functionNode.needsCallee() ? FunctionNode.NEEDS_CALLEE : 0);
 149         this.functionNodeId      = functionNode.getId();
 150         this.source              = functionNode.getSource();
 151         this.endParserState      = functionNode.getEndParserState();
 152         this.token               = tokenFor(functionNode);
 153         this.installer           = installer;
 154         this.allocationStrategy  = allocationStrategy;
 155         this.nestedFunctions     = smallMap(nestedFunctions);
 156         this.externalScopeDepths = smallMap(externalScopeDepths);
 157         this.internalSymbols     = smallSet(new HashSet<>(internalSymbols));
 158 
 159         for (final RecompilableScriptFunctionData nfn : nestedFunctions.values()) {
 160             assert nfn.getParent() == null;
 161             nfn.setParent(this);
 162         }
 163 
 164         this.serializedAst = serializedAst;
 165         createLogger();
 166     }
 167 
 168     private static <K, V> Map<K, V> smallMap(final Map<K, V> map) {
 169         if (map == null || map.isEmpty()) {
 170             return Collections.emptyMap();
 171         } else if (map.size() == 1) {
 172             final Map.Entry<K, V> entry = map.entrySet().iterator().next();
 173             return Collections.singletonMap(entry.getKey(), entry.getValue());
 174         } else {
 175             return map;
 176         }
 177     }
 178 
 179     private static <T> Set<T> smallSet(final Set<T> set) {
 180         if (set == null || set.isEmpty()) {
 181             return Collections.emptySet();
 182         } else if (set.size() == 1) {
 183             return Collections.singleton(set.iterator().next());
 184         } else {
 185             return set;
 186         }
 187     }
 188 
 189     @Override
 190     public DebugLogger getLogger() {
 191         return log;
 192     }
 193 
 194     @Override
 195     public DebugLogger initLogger(final Context ctxt) {
 196         return ctxt.getLogger(this.getClass());
 197     }
 198 
 199     /**
 200      * Check if a symbol is internally defined in a function. For example
 201      * if "undefined" is internally defined in the outermost program function,
 202      * it has not been reassigned or overridden and can be optimized
 203      *
 204      * @param symbolName symbol name
 205      * @return true if symbol is internal to this ScriptFunction
 206      */
 207 
 208     public boolean hasInternalSymbol(final String symbolName) {
 209         return internalSymbols.contains(symbolName);
 210     }
 211 
 212     /**
 213      * Return the external symbol table
 214      * @param symbolName symbol name
 215      * @return the external symbol table with proto depths
 216      */
 217     public int getExternalSymbolDepth(final String symbolName) {
 218         final Integer depth = externalScopeDepths.get(symbolName);
 219         return depth == null ? -1 : depth;
 220     }
 221 
 222     /**
 223      * Returns the names of all external symbols this function uses.
 224      * @return the names of all external symbols this function uses.
 225      */
 226     public Set<String> getExternalSymbolNames() {
 227         return Collections.unmodifiableSet(externalScopeDepths.keySet());
 228     }
 229 
 230     /**
 231      * Returns the opaque object representing the parser state at the end of this function's body, used to
 232      * skip parsing this function when reparsing its containing outer function.
 233      * @return the object representing the end parser state
 234      */
 235     public Object getEndParserState() {
 236         return endParserState;
 237     }
 238 
 239     /**
 240      * Get the parent of this RecompilableScriptFunctionData. If we are
 241      * a nested function, we have a parent. Note that "null" return value
 242      * can also mean that we have a parent but it is unknown, so this can
 243      * only be used for conservative assumptions.
 244      * @return parent data, or null if non exists and also null IF UNKNOWN.
 245      */
 246     public RecompilableScriptFunctionData getParent() {
 247        return parent;
 248     }
 249 
 250     void setParent(final RecompilableScriptFunctionData parent) {
 251         this.parent = parent;
 252     }
 253 
 254     @Override
 255     String toSource() {
 256         if (source != null && token != 0) {
 257             return source.getString(Token.descPosition(token), Token.descLength(token));
 258         }
 259 
 260         return "function " + (name == null ? "" : name) + "() { [native code] }";
 261     }
 262 
 263     /**
 264      * Initialize transient fields on deserialized instances
 265      *
 266      * @param src source
 267      * @param inst code installer
 268      */
 269     public void initTransients(final Source src, final CodeInstaller<ScriptEnvironment> inst) {
 270         if (this.source == null && this.installer == null) {
 271             this.source    = src;
 272             this.installer = inst;
 273         } else if (this.source != src || !this.installer.isCompatibleWith(inst)) {
 274             // Existing values must be same as those passed as parameters
 275             throw new IllegalArgumentException();
 276         }
 277     }
 278 
 279     @Override
 280     public String toString() {
 281         return super.toString() + '@' + functionNodeId;
 282     }
 283 
 284     @Override
 285     public String toStringVerbose() {
 286         final StringBuilder sb = new StringBuilder();
 287 
 288         sb.append("fnId=").append(functionNodeId).append(' ');
 289 
 290         if (source != null) {
 291             sb.append(source.getName())
 292                 .append(':')
 293                 .append(lineNumber)
 294                 .append(' ');
 295         }
 296 
 297         return sb.toString() + super.toString();
 298     }
 299 
 300     @Override
 301     public String getFunctionName() {
 302         return functionName;
 303     }
 304 
 305     @Override
 306     public boolean inDynamicContext() {
 307         return getFunctionFlag(FunctionNode.IN_DYNAMIC_CONTEXT);
 308     }
 309 
 310     private static String functionName(final FunctionNode fn) {
 311         if (fn.isAnonymous()) {
 312             return "";
 313         }
 314         final FunctionNode.Kind kind = fn.getKind();
 315         if (kind == FunctionNode.Kind.GETTER || kind == FunctionNode.Kind.SETTER) {
 316             final String name = NameCodec.decode(fn.getIdent().getName());
 317             return name.substring(GET_SET_PREFIX_LENGTH);
 318         }
 319         return fn.getIdent().getName();
 320     }
 321 
 322     private static long tokenFor(final FunctionNode fn) {
 323         final int  position  = Token.descPosition(fn.getFirstToken());
 324         final long lastToken = Token.withDelimiter(fn.getLastToken());
 325         // EOL uses length field to store the line number
 326         final int  length    = Token.descPosition(lastToken) - position + (Token.descType(lastToken) == TokenType.EOL ? 0 : Token.descLength(lastToken));
 327 
 328         return Token.toDesc(TokenType.FUNCTION, position, length);
 329     }
 330 
 331     private static int getDataFlags(final FunctionNode functionNode) {
 332         int flags = IS_CONSTRUCTOR;
 333         if (functionNode.isStrict()) {
 334             flags |= IS_STRICT;
 335         }
 336         if (functionNode.needsCallee()) {
 337             flags |= NEEDS_CALLEE;
 338         }
 339         if (functionNode.usesThis() || functionNode.hasEval()) {
 340             flags |= USES_THIS;
 341         }
 342         if (functionNode.isVarArg()) {
 343             flags |= IS_VARIABLE_ARITY;
 344         }
 345         return flags;
 346     }
 347 
 348     @Override
 349     PropertyMap getAllocatorMap() {
 350         return allocationStrategy.getAllocatorMap();
 351     }
 352 
 353     @Override
 354     ScriptObject allocate(final PropertyMap map) {
 355         return allocationStrategy.allocate(map);
 356     }
 357 
 358     boolean isSerialized() {
 359         return serializedAst != null;
 360     }
 361 
 362     FunctionNode reparse() {
 363         if (isSerialized()) {
 364             return deserialize();
 365         }
 366 
 367         final int descPosition = Token.descPosition(token);
 368         final Context context = Context.getContextTrusted();
 369         final Parser parser = new Parser(
 370             context.getEnv(),
 371             source,
 372             new Context.ThrowErrorManager(),
 373             isStrict(),
 374             // source starts at line 0, so even though lineNumber is the correct declaration line, back off
 375             // one to make it exclusive
 376             lineNumber - 1,
 377             context.getLogger(Parser.class));
 378 
 379         if (getFunctionFlag(FunctionNode.IS_ANONYMOUS)) {
 380             parser.setFunctionName(functionName);
 381         }
 382         parser.setReparsedFunction(this);
 383 
 384         final FunctionNode program = parser.parse(CompilerConstants.PROGRAM.symbolName(), descPosition,
 385                 Token.descLength(token), true);
 386         // Parser generates a program AST even if we're recompiling a single function, so when we are only
 387         // recompiling a single function, extract it from the program.
 388         return (isProgram() ? program : extractFunctionFromScript(program)).setName(null, functionName);
 389     }
 390 
 391     private FunctionNode deserialize() {
 392         final ScriptEnvironment env = installer.getOwner();
 393         final Timing timing = env._timing;
 394         final long t1 = System.nanoTime();
 395         try {
 396             return AstDeserializer.deserialize(serializedAst).initializeDeserialized(source, new Namespace(env.getNamespace()));
 397         } finally {
 398             timing.accumulateTime("'Deserialize'", System.nanoTime() - t1);
 399         }
 400     }
 401 
 402     private boolean getFunctionFlag(final int flag) {
 403         return (functionFlags & flag) != 0;
 404     }
 405 
 406     private boolean isProgram() {
 407         return getFunctionFlag(FunctionNode.IS_PROGRAM);
 408     }
 409 
 410     TypeMap typeMap(final MethodType fnCallSiteType) {
 411         if (fnCallSiteType == null) {
 412             return null;
 413         }
 414 
 415         if (CompiledFunction.isVarArgsType(fnCallSiteType)) {
 416             return null;
 417         }
 418 
 419         return new TypeMap(functionNodeId, explicitParams(fnCallSiteType), needsCallee());
 420     }
 421 
 422     private static ScriptObject newLocals(final ScriptObject runtimeScope) {
 423         final ScriptObject locals = Global.newEmptyInstance();
 424         locals.setProto(runtimeScope);
 425         return locals;
 426     }
 427 
 428     private Compiler getCompiler(final FunctionNode fn, final MethodType actualCallSiteType, final ScriptObject runtimeScope) {
 429         return getCompiler(fn, actualCallSiteType, newLocals(runtimeScope), null, null);
 430     }
 431 
 432     /**
 433      * Returns a code installer for installing new code. If we're using either optimistic typing or loader-per-compile,
 434      * then asks for a code installer with a new class loader; otherwise just uses the current installer. We use
 435      * a new class loader with optimistic typing so that deoptimized code can get reclaimed by GC.
 436      * @return a code installer for installing new code.
 437      */
 438     private CodeInstaller<ScriptEnvironment> getInstallerForNewCode() {
 439         final ScriptEnvironment env = installer.getOwner();
 440         return env._optimistic_types || env._loader_per_compile ? installer.withNewLoader() : installer;
 441     }
 442 
 443     Compiler getCompiler(final FunctionNode functionNode, final MethodType actualCallSiteType,
 444             final ScriptObject runtimeScope, final Map<Integer, Type> invalidatedProgramPoints,
 445             final int[] continuationEntryPoints) {
 446         final TypeMap typeMap = typeMap(actualCallSiteType);
 447         final Type[] paramTypes = typeMap == null ? null : typeMap.getParameterTypes(functionNodeId);
 448         final Object typeInformationFile = OptimisticTypesPersistence.getLocationDescriptor(source, functionNodeId, paramTypes);
 449         final Context context = Context.getContextTrusted();
 450         return new Compiler(
 451                 context,
 452                 context.getEnv(),
 453                 getInstallerForNewCode(),
 454                 functionNode.getSource(),  // source
 455                 context.getErrorManager(),
 456                 isStrict() | functionNode.isStrict(), // is strict
 457                 true,       // is on demand
 458                 this,       // compiledFunction, i.e. this RecompilableScriptFunctionData
 459                 typeMap,    // type map
 460                 getEffectiveInvalidatedProgramPoints(invalidatedProgramPoints, typeInformationFile), // invalidated program points
 461                 typeInformationFile,
 462                 continuationEntryPoints, // continuation entry points
 463                 runtimeScope); // runtime scope
 464     }
 465 
 466     /**
 467      * If the function being compiled already has its own invalidated program points map, use it. Otherwise, attempt to
 468      * load invalidated program points map from the persistent type info cache.
 469      * @param invalidatedProgramPoints the function's current invalidated program points map. Null if the function
 470      * doesn't have it.
 471      * @param typeInformationFile the object describing the location of the persisted type information.
 472      * @return either the existing map, or a loaded map from the persistent type info cache, or a new empty map if
 473      * neither an existing map or a persistent cached type info is available.
 474      */
 475     @SuppressWarnings("unused")
 476     private static Map<Integer, Type> getEffectiveInvalidatedProgramPoints(
 477             final Map<Integer, Type> invalidatedProgramPoints, final Object typeInformationFile) {
 478         if(invalidatedProgramPoints != null) {
 479             return invalidatedProgramPoints;
 480         }
 481         final Map<Integer, Type> loadedProgramPoints = OptimisticTypesPersistence.load(typeInformationFile);
 482         return loadedProgramPoints != null ? loadedProgramPoints : new TreeMap<Integer, Type>();
 483     }
 484 
 485     private FunctionInitializer compileTypeSpecialization(final MethodType actualCallSiteType, final ScriptObject runtimeScope, final boolean persist) {
 486         // We're creating an empty script object for holding local variables. AssignSymbols will populate it with
 487         // explicit Undefined values for undefined local variables (see AssignSymbols#defineSymbol() and
 488         // CompilationEnvironment#declareLocalSymbol()).
 489 
 490         if (log.isEnabled()) {
 491             log.info("Parameter type specialization of '", functionName, "' signature: ", actualCallSiteType);
 492         }
 493 
 494         final boolean persistentCache = persist && usePersistentCodeCache();
 495         String cacheKey = null;
 496         if (persistentCache) {
 497             final TypeMap typeMap = typeMap(actualCallSiteType);
 498             final Type[] paramTypes = typeMap == null ? null : typeMap.getParameterTypes(functionNodeId);
 499             cacheKey = CodeStore.getCacheKey(functionNodeId, paramTypes);
 500             final CodeInstaller<ScriptEnvironment> newInstaller = getInstallerForNewCode();
 501             final StoredScript script = newInstaller.loadScript(source, cacheKey);
 502 
 503             if (script != null) {
 504                 Compiler.updateCompilationId(script.getCompilationId());
 505                 return script.installFunction(this, newInstaller);
 506             }
 507         }
 508 
 509         final FunctionNode fn = reparse();
 510         final Compiler compiler = getCompiler(fn, actualCallSiteType, runtimeScope);
 511         final FunctionNode compiledFn = compiler.compile(fn,
 512                 isSerialized() ? CompilationPhases.COMPILE_ALL_SERIALIZED : CompilationPhases.COMPILE_ALL);
 513 
 514         if (persist && !compiledFn.getFlag(FunctionNode.HAS_APPLY_TO_CALL_SPECIALIZATION)) {
 515             compiler.persistClassInfo(cacheKey, compiledFn);
 516         }
 517         return new FunctionInitializer(compiledFn, compiler.getInvalidatedProgramPoints());
 518     }
 519 
 520     boolean usePersistentCodeCache() {
 521         return installer != null && installer.getOwner()._persistent_cache;

 522     }
 523 
 524     private MethodType explicitParams(final MethodType callSiteType) {
 525         if (CompiledFunction.isVarArgsType(callSiteType)) {
 526             return null;
 527         }
 528 
 529         final MethodType noCalleeThisType = callSiteType.dropParameterTypes(0, 2); // (callee, this) is always in call site type
 530         final int callSiteParamCount = noCalleeThisType.parameterCount();
 531 
 532         // Widen parameters of reference types to Object as we currently don't care for specialization among reference
 533         // types. E.g. call site saying (ScriptFunction, Object, String) should still link to (ScriptFunction, Object, Object)
 534         final Class<?>[] paramTypes = noCalleeThisType.parameterArray();
 535         boolean changed = false;
 536         for (int i = 0; i < paramTypes.length; ++i) {
 537             final Class<?> paramType = paramTypes[i];
 538             if (!(paramType.isPrimitive() || paramType == Object.class)) {
 539                 paramTypes[i] = Object.class;
 540                 changed = true;
 541             }
 542         }
 543         final MethodType generalized = changed ? MethodType.methodType(noCalleeThisType.returnType(), paramTypes) : noCalleeThisType;
 544 
 545         if (callSiteParamCount < getArity()) {
 546             return generalized.appendParameterTypes(Collections.<Class<?>>nCopies(getArity() - callSiteParamCount, Object.class));
 547         }
 548         return generalized;
 549     }
 550 
 551     private FunctionNode extractFunctionFromScript(final FunctionNode script) {
 552         final Set<FunctionNode> fns = new HashSet<>();
 553         script.getBody().accept(new NodeVisitor<LexicalContext>(new LexicalContext()) {
 554             @Override
 555             public boolean enterFunctionNode(final FunctionNode fn) {
 556                 fns.add(fn);
 557                 return false;
 558             }
 559         });
 560         assert fns.size() == 1 : "got back more than one method in recompilation";
 561         final FunctionNode f = fns.iterator().next();
 562         assert f.getId() == functionNodeId;
 563         if (!getFunctionFlag(FunctionNode.IS_DECLARED) && f.isDeclared()) {
 564             return f.clearFlag(null, FunctionNode.IS_DECLARED);
 565         }
 566         return f;
 567     }
 568 
 569     private void logLookup(final boolean shouldLog, final MethodType targetType) {
 570         if (shouldLog && log.isEnabled()) {
 571             log.info("Looking up ", DebugLogger.quote(functionName), " type=", targetType);
 572         }
 573     }
 574 
 575     private MethodHandle lookup(final FunctionInitializer fnInit, final boolean shouldLog) {
 576         final MethodType type = fnInit.getMethodType();
 577         logLookup(shouldLog, type);
 578         return lookupCodeMethod(fnInit.getCode(), type);
 579     }
 580 
 581     MethodHandle lookup(final FunctionNode fn) {
 582         final MethodType type = new FunctionSignature(fn).getMethodType();
 583         logLookup(true, type);
 584         return lookupCodeMethod(fn.getCompileUnit().getCode(), type);
 585     }
 586 
 587     MethodHandle lookupCodeMethod(final Class<?> codeClass, final MethodType targetType) {
 588         return MH.findStatic(LOOKUP, codeClass, functionName, targetType);
 589     }
 590 
 591     /**
 592      * Initializes this function data with the eagerly generated version of the code. This method can only be invoked
 593      * by the compiler internals in Nashorn and is public for implementation reasons only. Attempting to invoke it
 594      * externally will result in an exception.
 595      *
 596      * @param functionNode FunctionNode for this data
 597      */
 598     public void initializeCode(final FunctionNode functionNode) {
 599         // Since the method is public, we double-check that we aren't invoked with an inappropriate compile unit.
 600         if (!code.isEmpty() || functionNode.getId() != functionNodeId || !functionNode.getCompileUnit().isInitializing(this, functionNode)) {
 601             throw new IllegalStateException(name);
 602         }
 603         addCode(lookup(functionNode), null, null, functionNode.getFlags());
 604     }
 605 
 606     /**
 607      * Initializes this function with the given function code initializer.
 608      * @param initializer function code initializer
 609      */
 610     void initializeCode(final FunctionInitializer initializer) {
 611         addCode(lookup(initializer, true), null, null, initializer.getFlags());
 612     }
 613 
 614     private CompiledFunction addCode(final MethodHandle target, final Map<Integer, Type> invalidatedProgramPoints,
 615                                      final MethodType callSiteType, final int fnFlags) {
 616         final CompiledFunction cfn = new CompiledFunction(target, this, invalidatedProgramPoints, callSiteType, fnFlags);
 617         code.add(cfn);
 618         return cfn;
 619     }
 620 
 621     /**
 622      * Add code with specific call site type. It will adapt the type of the looked up method handle to fit the call site
 623      * type. This is necessary because even if we request a specialization that takes an "int" parameter, we might end
 624      * up getting one that takes a "double" etc. because of internal function logic causes widening (e.g. assignment of
 625      * a wider value to the parameter variable). However, we use the method handle type for matching subsequent lookups
 626      * for the same specialization, so we must adapt the handle to the expected type.
 627      * @param fnInit the function
 628      * @param callSiteType the call site type
 629      * @return the compiled function object, with its type matching that of the call site type.
 630      */
 631     private CompiledFunction addCode(final FunctionInitializer fnInit, final MethodType callSiteType) {
 632         if (isVariableArity()) {
 633             return addCode(lookup(fnInit, true), fnInit.getInvalidatedProgramPoints(), callSiteType, fnInit.getFlags());
 634         }
 635 
 636         final MethodHandle handle = lookup(fnInit, true);
 637         final MethodType fromType = handle.type();
 638         MethodType toType = needsCallee(fromType) ? callSiteType.changeParameterType(0, ScriptFunction.class) : callSiteType.dropParameterTypes(0, 1);
 639         toType = toType.changeReturnType(fromType.returnType());
 640 
 641         final int toCount = toType.parameterCount();
 642         final int fromCount = fromType.parameterCount();
 643         final int minCount = Math.min(fromCount, toCount);
 644         for(int i = 0; i < minCount; ++i) {
 645             final Class<?> fromParam = fromType.parameterType(i);
 646             final Class<?>   toParam =   toType.parameterType(i);
 647             // If method has an Object parameter, but call site had String, preserve it as Object. No need to narrow it
 648             // artificially. Note that this is related to how CompiledFunction.matchesCallSite() works, specifically
 649             // the fact that various reference types compare to equal (see "fnType.isEquivalentTo(csType)" there).
 650             if (fromParam != toParam && !fromParam.isPrimitive() && !toParam.isPrimitive()) {
 651                 assert fromParam.isAssignableFrom(toParam);
 652                 toType = toType.changeParameterType(i, fromParam);
 653             }
 654         }
 655         if (fromCount > toCount) {
 656             toType = toType.appendParameterTypes(fromType.parameterList().subList(toCount, fromCount));
 657         } else if (fromCount < toCount) {
 658             toType = toType.dropParameterTypes(fromCount, toCount);
 659         }
 660 
 661         return addCode(lookup(fnInit, false).asType(toType), fnInit.getInvalidatedProgramPoints(), callSiteType, fnInit.getFlags());
 662     }
 663 
 664     /**
 665      * Returns the return type of a function specialization for particular parameter types.<br>
 666      * <b>Be aware that the way this is implemented, it forces full materialization (compilation and installation) of
 667      * code for that specialization.</b>
 668      * @param callSiteType the parameter types at the call site. It must include the mandatory {@code callee} and
 669      * {@code this} parameters, so it needs to start with at least {@code ScriptFunction.class} and
 670      * {@code Object.class} class. Since the return type of the function is calculated from the code itself, it is
 671      * irrelevant and should be set to {@code Object.class}.
 672      * @param runtimeScope a current runtime scope. Can be null but when it's present it will be used as a source of
 673      * current runtime values that can improve the compiler's type speculations (and thus reduce the need for later
 674      * recompilations) if the specialization is not already present and thus needs to be freshly compiled.
 675      * @return the return type of the function specialization.
 676      */
 677     public Class<?> getReturnType(final MethodType callSiteType, final ScriptObject runtimeScope) {
 678         return getBest(callSiteType, runtimeScope, CompiledFunction.NO_FUNCTIONS).type().returnType();
 679     }
 680 
 681     @Override
 682     synchronized CompiledFunction getBest(final MethodType callSiteType, final ScriptObject runtimeScope, final Collection<CompiledFunction> forbidden) {
 683         CompiledFunction existingBest = super.getBest(callSiteType, runtimeScope, forbidden);
 684         if (existingBest == null) {
 685             existingBest = addCode(compileTypeSpecialization(callSiteType, runtimeScope, true), callSiteType);
 686         }
 687 
 688         assert existingBest != null;
 689         //we are calling a vararg method with real args
 690         boolean varArgWithRealArgs = existingBest.isVarArg() && !CompiledFunction.isVarArgsType(callSiteType);
 691 
 692         //if the best one is an apply to call, it has to match the callsite exactly
 693         //or we need to regenerate
 694         if (existingBest.isApplyToCall()) {
 695             final CompiledFunction best = lookupExactApplyToCall(callSiteType);
 696             if (best != null) {
 697                 return best;
 698             }
 699             varArgWithRealArgs = true;
 700         }
 701 
 702         if (varArgWithRealArgs) {
 703             // special case: we had an apply to call, but we failed to make it fit.
 704             // Try to generate a specialized one for this callsite. It may
 705             // be another apply to call specialization, or it may not, but whatever
 706             // it is, it is a specialization that is guaranteed to fit
 707             final FunctionInitializer fnInit = compileTypeSpecialization(callSiteType, runtimeScope, false);
 708             existingBest = addCode(fnInit, callSiteType);
 709         }
 710 
 711         return existingBest;
 712     }
 713 
 714     @Override
 715     boolean isRecompilable() {
 716         return true;
 717     }
 718 
 719     @Override
 720     public boolean needsCallee() {
 721         return getFunctionFlag(FunctionNode.NEEDS_CALLEE);
 722     }
 723 
 724     /**
 725      * Returns the {@link FunctionNode} flags associated with this function data.
 726      * @return the {@link FunctionNode} flags associated with this function data.
 727      */
 728     public int getFunctionFlags() {
 729         return functionFlags;
 730     }
 731 
 732     @Override
 733     MethodType getGenericType() {
 734         // 2 is for (callee, this)
 735         if (isVariableArity()) {
 736             return MethodType.genericMethodType(2, true);
 737         }
 738         return MethodType.genericMethodType(2 + getArity());
 739     }
 740 
 741     /**
 742      * Return the function node id.
 743      * @return the function node id
 744      */
 745     public int getFunctionNodeId() {
 746         return functionNodeId;
 747     }
 748 
 749     /**
 750      * Get the source for the script
 751      * @return source
 752      */
 753     public Source getSource() {
 754         return source;
 755     }
 756 
 757     /**
 758      * Return a script function data based on a function id, either this function if
 759      * the id matches or a nested function based on functionId. This goes down into
 760      * nested functions until all leaves are exhausted.
 761      *
 762      * @param functionId function id
 763      * @return script function data or null if invalid id
 764      */
 765     public RecompilableScriptFunctionData getScriptFunctionData(final int functionId) {
 766         if (functionId == functionNodeId) {
 767             return this;
 768         }
 769         RecompilableScriptFunctionData data;
 770 
 771         data = nestedFunctions == null ? null : nestedFunctions.get(functionId);
 772         if (data != null) {
 773             return data;
 774         }
 775         for (final RecompilableScriptFunctionData ndata : nestedFunctions.values()) {
 776             data = ndata.getScriptFunctionData(functionId);
 777             if (data != null) {
 778                 return data;
 779             }
 780         }
 781         return null;
 782     }
 783 
 784     /**
 785      * Check whether a certain name is a global symbol, i.e. only exists as defined
 786      * in outermost scope and not shadowed by being parameter or assignment in inner
 787      * scopes
 788      *
 789      * @param functionNode function node to check
 790      * @param symbolName symbol name
 791      * @return true if global symbol
 792      */
 793     public boolean isGlobalSymbol(final FunctionNode functionNode, final String symbolName) {
 794         RecompilableScriptFunctionData data = getScriptFunctionData(functionNode.getId());
 795         assert data != null;
 796 
 797         do {
 798             if (data.hasInternalSymbol(symbolName)) {
 799                 return false;
 800             }
 801             data = data.getParent();
 802         } while(data != null);
 803 
 804         return true;
 805     }
 806 
 807     /**
 808      * Restores the {@link #getFunctionFlags()} flags to a function node. During on-demand compilation, we might need
 809      * to restore flags to a function node that was otherwise not subjected to a full compile pipeline (e.g. its parse
 810      * was skipped, or it's a nested function of a deserialized function.
 811      * @param lc current lexical context
 812      * @param fn the function node to restore flags onto
 813      * @return the transformed function node
 814      */
 815     public FunctionNode restoreFlags(final LexicalContext lc, final FunctionNode fn) {
 816         assert fn.getId() == functionNodeId;
 817         FunctionNode newFn = fn.setFlags(lc, functionFlags);
 818         // This compensates for missing markEval() in case the function contains an inner function
 819         // that contains eval(), that now we didn't discover since we skipped the inner function.
 820         if (newFn.hasNestedEval()) {
 821             assert newFn.hasScopeBlock();
 822             newFn = newFn.setBody(lc, newFn.getBody().setNeedsScope(null));
 823         }
 824         return newFn;
 825     }
 826 
 827     private void readObject(final java.io.ObjectInputStream in) throws IOException, ClassNotFoundException {
 828         in.defaultReadObject();
 829         createLogger();
 830     }
 831 
 832     private void createLogger() {
 833         log = initLogger(Context.getContextTrusted());
 834     }
 835 }
--- EOF ---