JavaScriptCore should discard baseline code after some time
[WebKit-https.git] / Source / JavaScriptCore / runtime / Executable.cpp
1 /*
2  * Copyright (C) 2009, 2010, 2013, 2015 Apple Inc. All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  * 1. Redistributions of source code must retain the above copyright
8  *    notice, this list of conditions and the following disclaimer.
9  * 2. Redistributions in binary form must reproduce the above copyright
10  *    notice, this list of conditions and the following disclaimer in the
11  *    documentation and/or other materials provided with the distribution.
12  *
13  * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
14  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
15  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
16  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE INC. OR
17  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
18  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
19  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
20  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
21  * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
22  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
23  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 
24  */
25
26 #include "config.h"
27 #include "Executable.h"
28
29 #include "BatchedTransitionOptimizer.h"
30 #include "CodeBlock.h"
31 #include "DFGDriver.h"
32 #include "JIT.h"
33 #include "JSCInlines.h"
34 #include "JSWASMModule.h"
35 #include "LLIntEntrypoint.h"
36 #include "Parser.h"
37 #include "ProfilerDatabase.h"
38 #include "TypeProfiler.h"
39 #include "WASMFunctionParser.h"
40 #include <wtf/CommaPrinter.h>
41 #include <wtf/Vector.h>
42 #include <wtf/text/StringBuilder.h>
43
44 namespace JSC {
45
46 const ClassInfo ExecutableBase::s_info = { "Executable", 0, 0, CREATE_METHOD_TABLE(ExecutableBase) };
47
48 void ExecutableBase::destroy(JSCell* cell)
49 {
50     static_cast<ExecutableBase*>(cell)->ExecutableBase::~ExecutableBase();
51 }
52
53 void ExecutableBase::clearCode()
54 {
55 #if ENABLE(JIT)
56     m_jitCodeForCall = nullptr;
57     m_jitCodeForConstruct = nullptr;
58     m_jitCodeForCallWithArityCheck = MacroAssemblerCodePtr();
59     m_jitCodeForConstructWithArityCheck = MacroAssemblerCodePtr();
60     m_jitCodeForCallWithArityCheckAndPreserveRegs = MacroAssemblerCodePtr();
61     m_jitCodeForConstructWithArityCheckAndPreserveRegs = MacroAssemblerCodePtr();
62 #endif
63     m_numParametersForCall = NUM_PARAMETERS_NOT_COMPILED;
64     m_numParametersForConstruct = NUM_PARAMETERS_NOT_COMPILED;
65 }
66
67 #if ENABLE(DFG_JIT)
68 Intrinsic ExecutableBase::intrinsic() const
69 {
70     if (const NativeExecutable* nativeExecutable = jsDynamicCast<const NativeExecutable*>(this))
71         return nativeExecutable->intrinsic();
72     return NoIntrinsic;
73 }
74 #else
75 Intrinsic ExecutableBase::intrinsic() const
76 {
77     return NoIntrinsic;
78 }
79 #endif
80
81 const ClassInfo NativeExecutable::s_info = { "NativeExecutable", &ExecutableBase::s_info, 0, CREATE_METHOD_TABLE(NativeExecutable) };
82
83 void NativeExecutable::destroy(JSCell* cell)
84 {
85     static_cast<NativeExecutable*>(cell)->NativeExecutable::~NativeExecutable();
86 }
87
88 #if ENABLE(DFG_JIT)
89 Intrinsic NativeExecutable::intrinsic() const
90 {
91     return m_intrinsic;
92 }
93 #endif
94
95 const ClassInfo ScriptExecutable::s_info = { "ScriptExecutable", &ExecutableBase::s_info, 0, CREATE_METHOD_TABLE(ScriptExecutable) };
96
97 ScriptExecutable::ScriptExecutable(Structure* structure, VM& vm, const SourceCode& source, bool isInStrictContext)
98     : ExecutableBase(vm, structure, NUM_PARAMETERS_NOT_COMPILED)
99     , m_source(source)
100     , m_features(isInStrictContext ? StrictModeFeature : 0)
101     , m_hasCapturedVariables(false)
102     , m_neverInline(false)
103     , m_didTryToEnterInLoop(false)
104     , m_overrideLineNumber(-1)
105     , m_firstLine(-1)
106     , m_lastLine(-1)
107     , m_startColumn(UINT_MAX)
108     , m_endColumn(UINT_MAX)
109     , m_typeProfilingStartOffset(UINT_MAX)
110     , m_typeProfilingEndOffset(UINT_MAX)
111 {
112 }
113
114 void ScriptExecutable::destroy(JSCell* cell)
115 {
116     static_cast<ScriptExecutable*>(cell)->ScriptExecutable::~ScriptExecutable();
117 }
118
119 void ScriptExecutable::installCode(CodeBlock* codeBlock)
120 {
121     installCode(*codeBlock->vm(), codeBlock, codeBlock->codeType(), codeBlock->specializationKind());
122 }
123
124 void ScriptExecutable::installCode(VM& vm, CodeBlock* genericCodeBlock, CodeType codeType, CodeSpecializationKind kind)
125 {
126     ASSERT(vm.heap.isDeferred());
127     
128     RefPtr<CodeBlock> oldCodeBlock;
129     
130     switch (codeType) {
131     case GlobalCode: {
132         ProgramExecutable* executable = jsCast<ProgramExecutable*>(this);
133         ProgramCodeBlock* codeBlock = static_cast<ProgramCodeBlock*>(genericCodeBlock);
134         
135         ASSERT(kind == CodeForCall);
136         
137         oldCodeBlock = executable->m_programCodeBlock;
138         executable->m_programCodeBlock = codeBlock;
139         break;
140     }
141
142     case ModuleCode: {
143         ModuleProgramExecutable* executable = jsCast<ModuleProgramExecutable*>(this);
144         ModuleProgramCodeBlock* codeBlock = static_cast<ModuleProgramCodeBlock*>(genericCodeBlock);
145
146         ASSERT(kind == CodeForCall);
147
148         oldCodeBlock = executable->m_moduleProgramCodeBlock;
149         executable->m_moduleProgramCodeBlock = codeBlock;
150         break;
151     }
152
153     case EvalCode: {
154         EvalExecutable* executable = jsCast<EvalExecutable*>(this);
155         EvalCodeBlock* codeBlock = static_cast<EvalCodeBlock*>(genericCodeBlock);
156         
157         ASSERT(kind == CodeForCall);
158         
159         oldCodeBlock = executable->m_evalCodeBlock;
160         executable->m_evalCodeBlock = codeBlock;
161         break;
162     }
163         
164     case FunctionCode: {
165         FunctionExecutable* executable = jsCast<FunctionExecutable*>(this);
166         FunctionCodeBlock* codeBlock = static_cast<FunctionCodeBlock*>(genericCodeBlock);
167         
168         switch (kind) {
169         case CodeForCall:
170             oldCodeBlock = executable->m_codeBlockForCall;
171             executable->m_codeBlockForCall = codeBlock;
172             break;
173         case CodeForConstruct:
174             oldCodeBlock = executable->m_codeBlockForConstruct;
175             executable->m_codeBlockForConstruct = codeBlock;
176             break;
177         }
178         break;
179     }
180     }
181
182     switch (kind) {
183     case CodeForCall:
184         m_jitCodeForCall = genericCodeBlock ? genericCodeBlock->jitCode() : nullptr;
185         m_jitCodeForCallWithArityCheck = MacroAssemblerCodePtr();
186         m_jitCodeForCallWithArityCheckAndPreserveRegs = MacroAssemblerCodePtr();
187         m_numParametersForCall = genericCodeBlock ? genericCodeBlock->numParameters() : NUM_PARAMETERS_NOT_COMPILED;
188         break;
189     case CodeForConstruct:
190         m_jitCodeForConstruct = genericCodeBlock ? genericCodeBlock->jitCode() : nullptr;
191         m_jitCodeForConstructWithArityCheck = MacroAssemblerCodePtr();
192         m_jitCodeForConstructWithArityCheckAndPreserveRegs = MacroAssemblerCodePtr();
193         m_numParametersForConstruct = genericCodeBlock ? genericCodeBlock->numParameters() : NUM_PARAMETERS_NOT_COMPILED;
194         break;
195     }
196
197     if (genericCodeBlock) {
198         RELEASE_ASSERT(genericCodeBlock->ownerExecutable() == this);
199         RELEASE_ASSERT(JITCode::isExecutableScript(genericCodeBlock->jitType()));
200         
201         if (Options::verboseOSR())
202             dataLog("Installing ", *genericCodeBlock, "\n");
203         
204         if (vm.m_perBytecodeProfiler)
205             vm.m_perBytecodeProfiler->ensureBytecodesFor(genericCodeBlock);
206         
207         if (Debugger* debugger = genericCodeBlock->globalObject()->debugger())
208             debugger->registerCodeBlock(genericCodeBlock);
209     }
210
211     if (oldCodeBlock)
212         oldCodeBlock->unlinkIncomingCalls();
213
214     vm.heap.writeBarrier(this);
215 }
216
217 RefPtr<CodeBlock> ScriptExecutable::newCodeBlockFor(
218     CodeSpecializationKind kind, JSFunction* function, JSScope* scope, JSObject*& exception)
219 {
220     VM* vm = scope->vm();
221
222     ASSERT(vm->heap.isDeferred());
223     ASSERT(startColumn() != UINT_MAX);
224     ASSERT(endColumn() != UINT_MAX);
225
226     if (classInfo() == EvalExecutable::info()) {
227         EvalExecutable* executable = jsCast<EvalExecutable*>(this);
228         RELEASE_ASSERT(kind == CodeForCall);
229         RELEASE_ASSERT(!executable->m_evalCodeBlock);
230         RELEASE_ASSERT(!function);
231         return adoptRef(new EvalCodeBlock(
232             executable, executable->m_unlinkedEvalCodeBlock.get(), scope,
233             executable->source().provider()));
234     }
235     
236     if (classInfo() == ProgramExecutable::info()) {
237         ProgramExecutable* executable = jsCast<ProgramExecutable*>(this);
238         RELEASE_ASSERT(kind == CodeForCall);
239         RELEASE_ASSERT(!executable->m_programCodeBlock);
240         RELEASE_ASSERT(!function);
241         return adoptRef(new ProgramCodeBlock(
242             executable, executable->m_unlinkedProgramCodeBlock.get(), scope,
243             executable->source().provider(), executable->source().startColumn()));
244     }
245
246     if (classInfo() == ModuleProgramExecutable::info()) {
247         ModuleProgramExecutable* executable = jsCast<ModuleProgramExecutable*>(this);
248         RELEASE_ASSERT(kind == CodeForCall);
249         RELEASE_ASSERT(!executable->m_moduleProgramCodeBlock);
250         RELEASE_ASSERT(!function);
251         return adoptRef(new ModuleProgramCodeBlock(
252             executable, executable->m_unlinkedModuleProgramCodeBlock.get(), scope,
253             executable->source().provider(), executable->source().startColumn()));
254     }
255
256     RELEASE_ASSERT(classInfo() == FunctionExecutable::info());
257     RELEASE_ASSERT(function);
258     FunctionExecutable* executable = jsCast<FunctionExecutable*>(this);
259     RELEASE_ASSERT(!executable->codeBlockFor(kind));
260     JSGlobalObject* globalObject = scope->globalObject();
261     ParserError error;
262     DebuggerMode debuggerMode = globalObject->hasDebugger() ? DebuggerOn : DebuggerOff;
263     ProfilerMode profilerMode = globalObject->hasProfiler() ? ProfilerOn : ProfilerOff;
264     UnlinkedFunctionCodeBlock* unlinkedCodeBlock = 
265         executable->m_unlinkedExecutable->unlinkedCodeBlockFor(
266             *vm, executable->m_source, kind, debuggerMode, profilerMode, error, 
267             executable->isArrowFunction());
268     recordParse(
269         executable->m_unlinkedExecutable->features(), 
270         executable->m_unlinkedExecutable->hasCapturedVariables(), firstLine(), 
271         lastLine(), startColumn(), endColumn()); 
272     if (!unlinkedCodeBlock) {
273         exception = vm->throwException(
274             globalObject->globalExec(),
275             error.toErrorObject(globalObject, executable->m_source));
276         return nullptr;
277     }
278
279     SourceProvider* provider = executable->source().provider();
280     unsigned sourceOffset = executable->source().startOffset();
281     unsigned startColumn = executable->source().startColumn();
282
283     return adoptRef(new FunctionCodeBlock(
284         executable, unlinkedCodeBlock, scope, provider, sourceOffset, startColumn));
285 }
286
287 PassRefPtr<CodeBlock> ScriptExecutable::newReplacementCodeBlockFor(
288     CodeSpecializationKind kind)
289 {
290     if (classInfo() == EvalExecutable::info()) {
291         RELEASE_ASSERT(kind == CodeForCall);
292         EvalExecutable* executable = jsCast<EvalExecutable*>(this);
293         EvalCodeBlock* baseline = static_cast<EvalCodeBlock*>(
294             executable->m_evalCodeBlock->baselineVersion());
295         RefPtr<EvalCodeBlock> result = adoptRef(new EvalCodeBlock(
296             CodeBlock::CopyParsedBlock, *baseline));
297         result->setAlternative(baseline);
298         return result;
299     }
300     
301     if (classInfo() == ProgramExecutable::info()) {
302         RELEASE_ASSERT(kind == CodeForCall);
303         ProgramExecutable* executable = jsCast<ProgramExecutable*>(this);
304         ProgramCodeBlock* baseline = static_cast<ProgramCodeBlock*>(
305             executable->m_programCodeBlock->baselineVersion());
306         RefPtr<ProgramCodeBlock> result = adoptRef(new ProgramCodeBlock(
307             CodeBlock::CopyParsedBlock, *baseline));
308         result->setAlternative(baseline);
309         return result;
310     }
311
312     if (classInfo() == ModuleProgramExecutable::info()) {
313         RELEASE_ASSERT(kind == CodeForCall);
314         ModuleProgramExecutable* executable = jsCast<ModuleProgramExecutable*>(this);
315         ModuleProgramCodeBlock* baseline = static_cast<ModuleProgramCodeBlock*>(
316             executable->m_moduleProgramCodeBlock->baselineVersion());
317         RefPtr<ModuleProgramCodeBlock> result = adoptRef(new ModuleProgramCodeBlock(
318             CodeBlock::CopyParsedBlock, *baseline));
319         result->setAlternative(baseline);
320         return result;
321     }
322
323     RELEASE_ASSERT(classInfo() == FunctionExecutable::info());
324     FunctionExecutable* executable = jsCast<FunctionExecutable*>(this);
325     FunctionCodeBlock* baseline = static_cast<FunctionCodeBlock*>(
326         executable->codeBlockFor(kind)->baselineVersion());
327     RefPtr<FunctionCodeBlock> result = adoptRef(new FunctionCodeBlock(
328         CodeBlock::CopyParsedBlock, *baseline));
329     result->setAlternative(baseline);
330     return result;
331 }
332
333 static void setupLLInt(VM& vm, CodeBlock* codeBlock)
334 {
335     LLInt::setEntrypoint(vm, codeBlock);
336 }
337
338 static void setupJIT(VM& vm, CodeBlock* codeBlock)
339 {
340 #if ENABLE(JIT)
341     CompilationResult result = JIT::compile(&vm, codeBlock, JITCompilationMustSucceed);
342     RELEASE_ASSERT(result == CompilationSuccessful);
343 #else
344     UNUSED_PARAM(vm);
345     UNUSED_PARAM(codeBlock);
346     UNREACHABLE_FOR_PLATFORM();
347 #endif
348 }
349
350 JSObject* ScriptExecutable::prepareForExecutionImpl(
351     ExecState* exec, JSFunction* function, JSScope* scope, CodeSpecializationKind kind)
352 {
353     VM& vm = exec->vm();
354     DeferGC deferGC(vm.heap);
355     
356     JSObject* exception = 0;
357     RefPtr<CodeBlock> codeBlock = newCodeBlockFor(kind, function, scope, exception);
358     if (!codeBlock) {
359         RELEASE_ASSERT(exception);
360         return exception;
361     }
362     
363     if (Options::validateBytecode())
364         codeBlock->validate();
365     
366     if (Options::useLLInt())
367         setupLLInt(vm, codeBlock.get());
368     else
369         setupJIT(vm, codeBlock.get());
370     
371     installCode(*codeBlock->vm(), codeBlock.get(), codeBlock->codeType(), codeBlock->specializationKind());
372     return 0;
373 }
374
375 const ClassInfo EvalExecutable::s_info = { "EvalExecutable", &ScriptExecutable::s_info, 0, CREATE_METHOD_TABLE(EvalExecutable) };
376
377 EvalExecutable* EvalExecutable::create(ExecState* exec, const SourceCode& source, bool isInStrictContext, ThisTDZMode thisTDZMode, const VariableEnvironment* variablesUnderTDZ)
378 {
379     JSGlobalObject* globalObject = exec->lexicalGlobalObject();
380     if (!globalObject->evalEnabled()) {
381         exec->vm().throwException(exec, createEvalError(exec, globalObject->evalDisabledErrorMessage()));
382         return 0;
383     }
384
385     EvalExecutable* executable = new (NotNull, allocateCell<EvalExecutable>(*exec->heap())) EvalExecutable(exec, source, isInStrictContext);
386     executable->finishCreation(exec->vm());
387
388     UnlinkedEvalCodeBlock* unlinkedEvalCode = globalObject->createEvalCodeBlock(exec, executable, thisTDZMode, variablesUnderTDZ);
389     if (!unlinkedEvalCode)
390         return 0;
391
392     executable->m_unlinkedEvalCodeBlock.set(exec->vm(), executable, unlinkedEvalCode);
393
394     return executable;
395 }
396
397 EvalExecutable::EvalExecutable(ExecState* exec, const SourceCode& source, bool inStrictContext)
398     : ScriptExecutable(exec->vm().evalExecutableStructure.get(), exec->vm(), source, inStrictContext)
399 {
400 }
401
402 void EvalExecutable::destroy(JSCell* cell)
403 {
404     static_cast<EvalExecutable*>(cell)->EvalExecutable::~EvalExecutable();
405 }
406
407 const ClassInfo ProgramExecutable::s_info = { "ProgramExecutable", &ScriptExecutable::s_info, 0, CREATE_METHOD_TABLE(ProgramExecutable) };
408
409 ProgramExecutable::ProgramExecutable(ExecState* exec, const SourceCode& source)
410     : ScriptExecutable(exec->vm().programExecutableStructure.get(), exec->vm(), source, false)
411 {
412     m_typeProfilingStartOffset = 0;
413     m_typeProfilingEndOffset = source.length() - 1;
414     if (exec->vm().typeProfiler() || exec->vm().controlFlowProfiler())
415         exec->vm().functionHasExecutedCache()->insertUnexecutedRange(sourceID(), m_typeProfilingStartOffset, m_typeProfilingEndOffset);
416 }
417
418 void ProgramExecutable::destroy(JSCell* cell)
419 {
420     static_cast<ProgramExecutable*>(cell)->ProgramExecutable::~ProgramExecutable();
421 }
422
423 const ClassInfo ModuleProgramExecutable::s_info = { "ModuleProgramExecutable", &ScriptExecutable::s_info, 0, CREATE_METHOD_TABLE(ModuleProgramExecutable) };
424
425 ModuleProgramExecutable::ModuleProgramExecutable(ExecState* exec, const SourceCode& source)
426     : ScriptExecutable(exec->vm().moduleProgramExecutableStructure.get(), exec->vm(), source, false)
427 {
428     m_typeProfilingStartOffset = 0;
429     m_typeProfilingEndOffset = source.length() - 1;
430     if (exec->vm().typeProfiler() || exec->vm().controlFlowProfiler())
431         exec->vm().functionHasExecutedCache()->insertUnexecutedRange(sourceID(), m_typeProfilingStartOffset, m_typeProfilingEndOffset);
432 }
433
434 ModuleProgramExecutable* ModuleProgramExecutable::create(ExecState* exec, const SourceCode& source)
435 {
436     JSGlobalObject* globalObject = exec->lexicalGlobalObject();
437     ModuleProgramExecutable* executable = new (NotNull, allocateCell<ModuleProgramExecutable>(*exec->heap())) ModuleProgramExecutable(exec, source);
438     executable->finishCreation(exec->vm());
439
440     UnlinkedModuleProgramCodeBlock* unlinkedModuleProgramCode = globalObject->createModuleProgramCodeBlock(exec, executable);
441     if (!unlinkedModuleProgramCode)
442         return nullptr;
443     executable->m_unlinkedModuleProgramCodeBlock.set(exec->vm(), executable, unlinkedModuleProgramCode);
444
445     executable->m_moduleEnvironmentSymbolTable.set(exec->vm(), executable, jsCast<SymbolTable*>(unlinkedModuleProgramCode->constantRegister(unlinkedModuleProgramCode->moduleEnvironmentSymbolTableConstantRegisterOffset()).get())->cloneScopePart(exec->vm()));
446
447     return executable;
448 }
449
450 void ModuleProgramExecutable::destroy(JSCell* cell)
451 {
452     static_cast<ModuleProgramExecutable*>(cell)->ModuleProgramExecutable::~ModuleProgramExecutable();
453 }
454
455 const ClassInfo FunctionExecutable::s_info = { "FunctionExecutable", &ScriptExecutable::s_info, 0, CREATE_METHOD_TABLE(FunctionExecutable) };
456
457 FunctionExecutable::FunctionExecutable(VM& vm, const SourceCode& source, 
458     UnlinkedFunctionExecutable* unlinkedExecutable, unsigned firstLine, 
459     unsigned lastLine, unsigned startColumn, unsigned endColumn)
460     : ScriptExecutable(vm.functionExecutableStructure.get(), vm, source, unlinkedExecutable->isInStrictContext())
461     , m_unlinkedExecutable(vm, this, unlinkedExecutable)
462 {
463     RELEASE_ASSERT(!source.isNull());
464     ASSERT(source.length());
465     m_firstLine = firstLine;
466     m_lastLine = lastLine;
467     ASSERT(startColumn != UINT_MAX);
468     ASSERT(endColumn != UINT_MAX);
469     m_startColumn = startColumn;
470     m_endColumn = endColumn;
471     m_parametersStartOffset = unlinkedExecutable->parametersStartOffset();
472     m_typeProfilingStartOffset = unlinkedExecutable->typeProfilingStartOffset();
473     m_typeProfilingEndOffset = unlinkedExecutable->typeProfilingEndOffset();
474 }
475
476 void FunctionExecutable::finishCreation(VM& vm)
477 {
478     Base::finishCreation(vm);
479     m_singletonFunction.set(vm, this, InferredValue::create(vm));
480 }
481
482 void FunctionExecutable::destroy(JSCell* cell)
483 {
484     static_cast<FunctionExecutable*>(cell)->FunctionExecutable::~FunctionExecutable();
485 }
486
487 inline const char* samplingDescription(JITCode::JITType jitType)
488 {
489     switch (jitType) {
490     case JITCode::InterpreterThunk:
491         return "Interpreter Compilation (TOTAL)";
492     case JITCode::BaselineJIT:
493         return "Baseline Compilation (TOTAL)";
494     case JITCode::DFGJIT:
495         return "DFG Compilation (TOTAL)";
496     case JITCode::FTLJIT:
497         return "FTL Compilation (TOTAL)";
498     default:
499         RELEASE_ASSERT_NOT_REACHED();
500         return 0;
501     }
502 }
503
504 void EvalExecutable::visitChildren(JSCell* cell, SlotVisitor& visitor)
505 {
506     EvalExecutable* thisObject = jsCast<EvalExecutable*>(cell);
507     ASSERT_GC_OBJECT_INHERITS(thisObject, info());
508     ScriptExecutable::visitChildren(thisObject, visitor);
509     if (thisObject->m_evalCodeBlock)
510         thisObject->m_evalCodeBlock->visitAggregate(visitor);
511     visitor.append(&thisObject->m_unlinkedEvalCodeBlock);
512 }
513
514 void EvalExecutable::clearCode()
515 {
516     m_evalCodeBlock = nullptr;
517     m_unlinkedEvalCodeBlock.clear();
518     Base::clearCode();
519 }
520
521 JSObject* ProgramExecutable::checkSyntax(ExecState* exec)
522 {
523     ParserError error;
524     VM* vm = &exec->vm();
525     JSGlobalObject* lexicalGlobalObject = exec->lexicalGlobalObject();
526     std::unique_ptr<ProgramNode> programNode = parse<ProgramNode>(
527         vm, m_source, Identifier(), JSParserBuiltinMode::NotBuiltin, 
528         JSParserStrictMode::NotStrict, SourceParseMode::ProgramMode, error);
529     if (programNode)
530         return 0;
531     ASSERT(error.isValid());
532     return error.toErrorObject(lexicalGlobalObject, m_source);
533 }
534
535 JSObject* ProgramExecutable::initializeGlobalProperties(VM& vm, CallFrame* callFrame, JSScope* scope)
536 {
537     RELEASE_ASSERT(scope);
538     JSGlobalObject* globalObject = scope->globalObject();
539     RELEASE_ASSERT(globalObject);
540     ASSERT(&globalObject->vm() == &vm);
541
542     JSObject* exception = 0;
543     UnlinkedProgramCodeBlock* unlinkedCodeBlock = globalObject->createProgramCodeBlock(callFrame, this, &exception);
544     if (exception)
545         return exception;
546
547     JSGlobalLexicalEnvironment* globalLexicalEnvironment = globalObject->globalLexicalEnvironment();
548     const VariableEnvironment& variableDeclarations = unlinkedCodeBlock->variableDeclarations();
549     const VariableEnvironment& lexicalDeclarations = unlinkedCodeBlock->lexicalDeclarations();
550     // The ES6 spec says that no vars/global properties/let/const can be duplicated in the global scope.
551     // This carried out section 15.1.8 of the ES6 spec: http://www.ecma-international.org/ecma-262/6.0/index.html#sec-globaldeclarationinstantiation
552     {
553         ExecState* exec = globalObject->globalExec();
554         // Check for intersection of "var" and "let"/"const"/"class"
555         for (auto& entry : lexicalDeclarations) {
556             if (variableDeclarations.contains(entry.key))
557                 return createSyntaxError(exec, makeString("Can't create duplicate variable: '", String(entry.key.get()), "'"));
558         }
559
560         // Check if any new "let"/"const"/"class" will shadow any pre-existing global property names, or "var"/"let"/"const" variables.
561         // It's an error to introduce a shadow.
562         for (auto& entry : lexicalDeclarations) {
563             if (globalObject->hasProperty(exec, entry.key.get()))
564                 return createSyntaxError(exec, makeString("Can't create duplicate variable that shadows a global property: '", String(entry.key.get()), "'"));
565
566             if (globalLexicalEnvironment->hasProperty(exec, entry.key.get()))
567                 return createSyntaxError(exec, makeString("Can't create duplicate variable: '", String(entry.key.get()), "'"));
568         }
569
570         // Check if any new "var"s will shadow any previous "let"/"const"/"class" names.
571         // It's an error to introduce a shadow.
572         if (!globalLexicalEnvironment->isEmpty()) {
573             for (auto& entry : variableDeclarations) {
574                 if (globalLexicalEnvironment->hasProperty(exec, entry.key.get()))
575                     return createSyntaxError(exec, makeString("Can't create duplicate variable: '", String(entry.key.get()), "'"));
576             }
577         }
578     }
579
580
581     m_unlinkedProgramCodeBlock.set(vm, this, unlinkedCodeBlock);
582
583     BatchedTransitionOptimizer optimizer(vm, globalObject);
584
585     for (size_t i = 0, numberOfFunctions = unlinkedCodeBlock->numberOfFunctionDecls(); i < numberOfFunctions; ++i) {
586         UnlinkedFunctionExecutable* unlinkedFunctionExecutable = unlinkedCodeBlock->functionDecl(i);
587         ASSERT(!unlinkedFunctionExecutable->name().isEmpty());
588         globalObject->addFunction(callFrame, unlinkedFunctionExecutable->name());
589         if (vm.typeProfiler() || vm.controlFlowProfiler()) {
590             vm.functionHasExecutedCache()->insertUnexecutedRange(sourceID(), 
591                 unlinkedFunctionExecutable->typeProfilingStartOffset(), 
592                 unlinkedFunctionExecutable->typeProfilingEndOffset());
593         }
594     }
595
596     for (auto& entry : variableDeclarations) {
597         ASSERT(entry.value.isVar());
598         globalObject->addVar(callFrame, Identifier::fromUid(&vm, entry.key.get()));
599     }
600
601     {
602         JSGlobalLexicalEnvironment* globalLexicalEnvironment = jsCast<JSGlobalLexicalEnvironment*>(globalObject->globalScope());
603         SymbolTable* symbolTable = globalLexicalEnvironment->symbolTable();
604         ConcurrentJITLocker locker(symbolTable->m_lock);
605         for (auto& entry : lexicalDeclarations) {
606             ScopeOffset offset = symbolTable->takeNextScopeOffset(locker);
607             SymbolTableEntry newEntry(VarOffset(offset), entry.value.isConst() ? ReadOnly : 0);
608             newEntry.prepareToWatch();
609             symbolTable->add(locker, entry.key.get(), newEntry);
610             
611             ScopeOffset offsetForAssert = globalLexicalEnvironment->addVariables(1, jsTDZValue());
612             RELEASE_ASSERT(offsetForAssert == offset);
613         }
614     }
615     return 0;
616 }
617
618 void ProgramExecutable::visitChildren(JSCell* cell, SlotVisitor& visitor)
619 {
620     ProgramExecutable* thisObject = jsCast<ProgramExecutable*>(cell);
621     ASSERT_GC_OBJECT_INHERITS(thisObject, info());
622     ScriptExecutable::visitChildren(thisObject, visitor);
623     visitor.append(&thisObject->m_unlinkedProgramCodeBlock);
624     if (thisObject->m_programCodeBlock)
625         thisObject->m_programCodeBlock->visitAggregate(visitor);
626 }
627
628 void ProgramExecutable::clearCode()
629 {
630     m_programCodeBlock = nullptr;
631     m_unlinkedProgramCodeBlock.clear();
632     Base::clearCode();
633 }
634
635 void ModuleProgramExecutable::visitChildren(JSCell* cell, SlotVisitor& visitor)
636 {
637     ModuleProgramExecutable* thisObject = jsCast<ModuleProgramExecutable*>(cell);
638     ASSERT_GC_OBJECT_INHERITS(thisObject, info());
639     ScriptExecutable::visitChildren(thisObject, visitor);
640     visitor.append(&thisObject->m_unlinkedModuleProgramCodeBlock);
641     visitor.append(&thisObject->m_moduleEnvironmentSymbolTable);
642     if (thisObject->m_moduleProgramCodeBlock)
643         thisObject->m_moduleProgramCodeBlock->visitAggregate(visitor);
644 }
645
646 void ModuleProgramExecutable::clearCode()
647 {
648     m_moduleProgramCodeBlock = nullptr;
649     m_unlinkedModuleProgramCodeBlock.clear();
650     m_moduleEnvironmentSymbolTable.clear();
651     Base::clearCode();
652 }
653
654 FunctionCodeBlock* FunctionExecutable::baselineCodeBlockFor(CodeSpecializationKind kind)
655 {
656     FunctionCodeBlock* result;
657     if (kind == CodeForCall)
658         result = m_codeBlockForCall.get();
659     else {
660         RELEASE_ASSERT(kind == CodeForConstruct);
661         result = m_codeBlockForConstruct.get();
662     }
663     if (!result)
664         return 0;
665     return static_cast<FunctionCodeBlock*>(result->baselineAlternative());
666 }
667
668 void FunctionExecutable::visitChildren(JSCell* cell, SlotVisitor& visitor)
669 {
670     FunctionExecutable* thisObject = jsCast<FunctionExecutable*>(cell);
671     ASSERT_GC_OBJECT_INHERITS(thisObject, info());
672     ScriptExecutable::visitChildren(thisObject, visitor);
673     if (thisObject->m_codeBlockForCall)
674         thisObject->m_codeBlockForCall->visitAggregate(visitor);
675     if (thisObject->m_codeBlockForConstruct)
676         thisObject->m_codeBlockForConstruct->visitAggregate(visitor);
677     visitor.append(&thisObject->m_unlinkedExecutable);
678     visitor.append(&thisObject->m_singletonFunction);
679 }
680
681 void FunctionExecutable::clearCode()
682 {
683     m_codeBlockForCall = nullptr;
684     m_codeBlockForConstruct = nullptr;
685     Base::clearCode();
686 }
687
688 FunctionExecutable* FunctionExecutable::fromGlobalCode(
689     const Identifier& name, ExecState& exec, const SourceCode& source, 
690     JSObject*& exception, int overrideLineNumber)
691 {
692     UnlinkedFunctionExecutable* unlinkedExecutable = 
693         UnlinkedFunctionExecutable::fromGlobalCode(
694             name, exec, source, exception, overrideLineNumber);
695     if (!unlinkedExecutable)
696         return nullptr;
697
698     return unlinkedExecutable->link(exec.vm(), source, overrideLineNumber);
699 }
700
701 #if ENABLE(WEBASSEMBLY)
702 const ClassInfo WebAssemblyExecutable::s_info = { "WebAssemblyExecutable", &ExecutableBase::s_info, 0, CREATE_METHOD_TABLE(WebAssemblyExecutable) };
703
704 WebAssemblyExecutable::WebAssemblyExecutable(VM& vm, const SourceCode& source, JSWASMModule* module, unsigned functionIndex)
705     : ExecutableBase(vm, vm.webAssemblyExecutableStructure.get(), NUM_PARAMETERS_NOT_COMPILED)
706     , m_source(source)
707     , m_module(vm, this, module)
708     , m_functionIndex(functionIndex)
709 {
710 }
711
712 void WebAssemblyExecutable::destroy(JSCell* cell)
713 {
714     static_cast<WebAssemblyExecutable*>(cell)->WebAssemblyExecutable::~WebAssemblyExecutable();
715 }
716
717 void WebAssemblyExecutable::visitChildren(JSCell* cell, SlotVisitor& visitor)
718 {
719     WebAssemblyExecutable* thisObject = jsCast<WebAssemblyExecutable*>(cell);
720     ASSERT_GC_OBJECT_INHERITS(thisObject, info());
721     ExecutableBase::visitChildren(thisObject, visitor);
722     if (thisObject->m_codeBlockForCall)
723         thisObject->m_codeBlockForCall->visitAggregate(visitor);
724     visitor.append(&thisObject->m_module);
725 }
726
727 void WebAssemblyExecutable::clearCode()
728 {
729     m_codeBlockForCall = nullptr;
730     Base::clearCode();
731 }
732
733 void WebAssemblyExecutable::prepareForExecution(ExecState* exec)
734 {
735     if (hasJITCodeForCall())
736         return;
737
738     VM& vm = exec->vm();
739     DeferGC deferGC(vm.heap);
740
741     RefPtr<WebAssemblyCodeBlock> codeBlock = adoptRef(new WebAssemblyCodeBlock(
742         this, vm, exec->lexicalGlobalObject()));
743
744     WASMFunctionParser::compile(vm, codeBlock.get(), m_module.get(), m_source, m_functionIndex);
745
746     m_jitCodeForCall = codeBlock->jitCode();
747     m_jitCodeForCallWithArityCheck = MacroAssemblerCodePtr();
748     m_jitCodeForCallWithArityCheckAndPreserveRegs = MacroAssemblerCodePtr();
749     m_numParametersForCall = codeBlock->numParameters();
750
751     m_codeBlockForCall = codeBlock;
752
753     Heap::heap(this)->writeBarrier(this);
754 }
755 #endif
756
757 void ExecutableBase::dump(PrintStream& out) const
758 {
759     ExecutableBase* realThis = const_cast<ExecutableBase*>(this);
760     
761     if (classInfo() == NativeExecutable::info()) {
762         NativeExecutable* native = jsCast<NativeExecutable*>(realThis);
763         out.print("NativeExecutable:", RawPointer(bitwise_cast<void*>(native->function())), "/", RawPointer(bitwise_cast<void*>(native->constructor())));
764         return;
765     }
766     
767     if (classInfo() == EvalExecutable::info()) {
768         EvalExecutable* eval = jsCast<EvalExecutable*>(realThis);
769         if (CodeBlock* codeBlock = eval->codeBlock())
770             out.print(*codeBlock);
771         else
772             out.print("EvalExecutable w/o CodeBlock");
773         return;
774     }
775     
776     if (classInfo() == ProgramExecutable::info()) {
777         ProgramExecutable* eval = jsCast<ProgramExecutable*>(realThis);
778         if (CodeBlock* codeBlock = eval->codeBlock())
779             out.print(*codeBlock);
780         else
781             out.print("ProgramExecutable w/o CodeBlock");
782         return;
783     }
784
785     if (classInfo() == ModuleProgramExecutable::info()) {
786         ModuleProgramExecutable* executable = jsCast<ModuleProgramExecutable*>(realThis);
787         if (CodeBlock* codeBlock = executable->codeBlock())
788             out.print(*codeBlock);
789         else
790             out.print("ModuleProgramExecutable w/o CodeBlock");
791         return;
792     }
793     
794     FunctionExecutable* function = jsCast<FunctionExecutable*>(realThis);
795     if (!function->eitherCodeBlock())
796         out.print("FunctionExecutable w/o CodeBlock");
797     else {
798         CommaPrinter comma("/");
799         if (function->codeBlockForCall())
800             out.print(comma, *function->codeBlockForCall());
801         if (function->codeBlockForConstruct())
802             out.print(comma, *function->codeBlockForConstruct());
803     }
804 }
805
806 CodeBlockHash ExecutableBase::hashFor(CodeSpecializationKind kind) const
807 {
808     if (this->classInfo() == NativeExecutable::info())
809         return jsCast<const NativeExecutable*>(this)->hashFor(kind);
810     
811     return jsCast<const ScriptExecutable*>(this)->hashFor(kind);
812 }
813
814 CodeBlockHash NativeExecutable::hashFor(CodeSpecializationKind kind) const
815 {
816     if (kind == CodeForCall)
817         return CodeBlockHash(static_cast<unsigned>(bitwise_cast<size_t>(m_function)));
818     
819     RELEASE_ASSERT(kind == CodeForConstruct);
820     return CodeBlockHash(static_cast<unsigned>(bitwise_cast<size_t>(m_constructor)));
821 }
822
823 CodeBlockHash ScriptExecutable::hashFor(CodeSpecializationKind kind) const
824 {
825     return CodeBlockHash(source(), kind);
826 }
827
828 }