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