Add API to generate and consume cached bytecode
[WebKit-https.git] / Source / JavaScriptCore / bytecode / UnlinkedFunctionExecutable.cpp
1 /*
2  * Copyright (C) 2012-2018 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 "UnlinkedFunctionExecutable.h"
28
29 #include "BuiltinExecutables.h"
30 #include "BytecodeGenerator.h"
31 #include "ClassInfo.h"
32 #include "CodeCache.h"
33 #include "Debugger.h"
34 #include "ExecutableInfo.h"
35 #include "FunctionOverrides.h"
36 #include "IsoCellSetInlines.h"
37 #include "JSCInlines.h"
38 #include "Parser.h"
39 #include "SourceProvider.h"
40 #include "Structure.h"
41 #include "UnlinkedFunctionCodeBlock.h"
42
43 namespace JSC {
44
45 static_assert(sizeof(UnlinkedFunctionExecutable) <= 160, "UnlinkedFunctionExecutable should fit in a 160-byte cell. If you increase the size of this class, consider making a size class that perfectly fits it.");
46
47 const ClassInfo UnlinkedFunctionExecutable::s_info = { "UnlinkedFunctionExecutable", nullptr, nullptr, nullptr, CREATE_METHOD_TABLE(UnlinkedFunctionExecutable) };
48
49 static UnlinkedFunctionCodeBlock* generateUnlinkedFunctionCodeBlock(
50     VM& vm, UnlinkedFunctionExecutable* executable, const SourceCode& source,
51     CodeSpecializationKind kind, DebuggerMode debuggerMode,
52     UnlinkedFunctionKind functionKind, ParserError& error, SourceParseMode parseMode)
53 {
54     JSParserBuiltinMode builtinMode = executable->isBuiltinFunction() ? JSParserBuiltinMode::Builtin : JSParserBuiltinMode::NotBuiltin;
55     JSParserStrictMode strictMode = executable->isInStrictContext() ? JSParserStrictMode::Strict : JSParserStrictMode::NotStrict;
56     JSParserScriptMode scriptMode = executable->scriptMode();
57     ASSERT(isFunctionParseMode(executable->parseMode()));
58     std::unique_ptr<FunctionNode> function = parse<FunctionNode>(
59         &vm, source, executable->name(), builtinMode, strictMode, scriptMode, executable->parseMode(), executable->superBinding(), error, nullptr);
60
61     if (!function) {
62         ASSERT(error.isValid());
63         return nullptr;
64     }
65
66     function->finishParsing(executable->name(), executable->functionMode());
67     executable->recordParse(function->features(), function->hasCapturedVariables());
68
69     bool isClassContext = executable->superBinding() == SuperBinding::Needed;
70
71     UnlinkedFunctionCodeBlock* result = UnlinkedFunctionCodeBlock::create(&vm, FunctionCode, ExecutableInfo(function->usesEval(), function->isStrictMode(), kind == CodeForConstruct, functionKind == UnlinkedBuiltinFunction, executable->constructorKind(), scriptMode, executable->superBinding(), parseMode, executable->derivedContextType(), false, isClassContext, EvalContextType::FunctionEvalContext), debuggerMode);
72
73     VariableEnvironment parentScopeTDZVariables = executable->parentScopeTDZVariables();
74     error = BytecodeGenerator::generate(vm, function.get(), source, result, debuggerMode, &parentScopeTDZVariables);
75
76     if (error.isValid())
77         return nullptr;
78     return result;
79 }
80
81 UnlinkedFunctionExecutable::UnlinkedFunctionExecutable(VM* vm, Structure* structure, const SourceCode& parentSource, FunctionMetadataNode* node, UnlinkedFunctionKind kind, ConstructAbility constructAbility, JSParserScriptMode scriptMode, VariableEnvironment& parentScopeTDZVariables, DerivedContextType derivedContextType, bool isBuiltinDefaultClassConstructor)
82     : Base(*vm, structure)
83     , m_firstLineOffset(node->firstLine() - parentSource.firstLine().oneBasedInt())
84     , m_lineCount(node->lastLine() - node->firstLine())
85     , m_unlinkedFunctionNameStart(node->functionNameStart() - parentSource.startOffset())
86     , m_unlinkedBodyStartColumn(node->startColumn())
87     , m_unlinkedBodyEndColumn(m_lineCount ? node->endColumn() : node->endColumn() - node->startColumn())
88     , m_startOffset(node->source().startOffset() - parentSource.startOffset())
89     , m_sourceLength(node->source().length())
90     , m_parametersStartOffset(node->parametersStart())
91     , m_typeProfilingStartOffset(node->functionKeywordStart())
92     , m_typeProfilingEndOffset(node->startStartOffset() + node->source().length() - 1)
93     , m_parameterCount(node->parameterCount())
94     , m_features(0)
95     , m_sourceParseMode(node->parseMode())
96     , m_isInStrictContext(node->isInStrictContext())
97     , m_hasCapturedVariables(false)
98     , m_isBuiltinFunction(kind == UnlinkedBuiltinFunction)
99     , m_isBuiltinDefaultClassConstructor(isBuiltinDefaultClassConstructor)
100     , m_constructAbility(static_cast<unsigned>(constructAbility))
101     , m_constructorKind(static_cast<unsigned>(node->constructorKind()))
102     , m_functionMode(static_cast<unsigned>(node->functionMode()))
103     , m_scriptMode(static_cast<unsigned>(scriptMode))
104     , m_superBinding(static_cast<unsigned>(node->superBinding()))
105     , m_derivedContextType(static_cast<unsigned>(derivedContextType))
106     , m_name(node->ident())
107     , m_ecmaName(node->ecmaName())
108     , m_inferredName(node->inferredName())
109     , m_classSource(node->classSource())
110     , m_parentScopeTDZVariables(vm->m_compactVariableMap->get(parentScopeTDZVariables))
111 {
112     // Make sure these bitfields are adequately wide.
113     ASSERT(m_constructAbility == static_cast<unsigned>(constructAbility));
114     ASSERT(m_constructorKind == static_cast<unsigned>(node->constructorKind()));
115     ASSERT(m_functionMode == static_cast<unsigned>(node->functionMode()));
116     ASSERT(m_scriptMode == static_cast<unsigned>(scriptMode));
117     ASSERT(m_superBinding == static_cast<unsigned>(node->superBinding()));
118     ASSERT(m_derivedContextType == static_cast<unsigned>(derivedContextType));
119     ASSERT(!(m_isBuiltinDefaultClassConstructor && constructorKind() == ConstructorKind::None));
120 }
121
122 void UnlinkedFunctionExecutable::destroy(JSCell* cell)
123 {
124     static_cast<UnlinkedFunctionExecutable*>(cell)->~UnlinkedFunctionExecutable();
125 }
126
127 void UnlinkedFunctionExecutable::visitChildren(JSCell* cell, SlotVisitor& visitor)
128 {
129     UnlinkedFunctionExecutable* thisObject = jsCast<UnlinkedFunctionExecutable*>(cell);
130     ASSERT_GC_OBJECT_INHERITS(thisObject, info());
131     Base::visitChildren(thisObject, visitor);
132     visitor.append(thisObject->m_unlinkedCodeBlockForCall);
133     visitor.append(thisObject->m_unlinkedCodeBlockForConstruct);
134 }
135
136 FunctionExecutable* UnlinkedFunctionExecutable::link(VM& vm, const SourceCode& passedParentSource, Optional<int> overrideLineNumber, Intrinsic intrinsic)
137 {
138     const SourceCode& parentSource = !m_isBuiltinDefaultClassConstructor ? passedParentSource : BuiltinExecutables::defaultConstructorSourceCode(constructorKind());
139     unsigned firstLine = parentSource.firstLine().oneBasedInt() + m_firstLineOffset;
140     unsigned startOffset = parentSource.startOffset() + m_startOffset;
141     unsigned lineCount = m_lineCount;
142
143     unsigned startColumn = linkedStartColumn(parentSource.startColumn().oneBasedInt());
144     unsigned endColumn = linkedEndColumn(startColumn);
145
146     SourceCode source(parentSource.provider(), startOffset, startOffset + m_sourceLength, firstLine, startColumn);
147     FunctionOverrides::OverrideInfo overrideInfo;
148     bool hasFunctionOverride = false;
149
150     if (UNLIKELY(Options::functionOverrides())) {
151         hasFunctionOverride = FunctionOverrides::initializeOverrideFor(source, overrideInfo);
152         if (UNLIKELY(hasFunctionOverride)) {
153             firstLine = overrideInfo.firstLine;
154             lineCount = overrideInfo.lineCount;
155             startColumn = overrideInfo.startColumn;
156             endColumn = overrideInfo.endColumn;
157             source = overrideInfo.sourceCode;
158         }
159     }
160
161     FunctionExecutable* result = FunctionExecutable::create(vm, source, this, firstLine + lineCount, endColumn, intrinsic);
162     if (overrideLineNumber)
163         result->setOverrideLineNumber(*overrideLineNumber);
164
165     if (UNLIKELY(hasFunctionOverride)) {
166         result->overrideParameterAndTypeProfilingStartEndOffsets(
167             overrideInfo.parametersStartOffset,
168             overrideInfo.typeProfilingStartOffset,
169             overrideInfo.typeProfilingEndOffset);
170     }
171
172     return result;
173 }
174
175 UnlinkedFunctionExecutable* UnlinkedFunctionExecutable::fromGlobalCode(
176     const Identifier& name, ExecState& exec, const SourceCode& source, 
177     JSObject*& exception, int overrideLineNumber, Optional<int> functionConstructorParametersEndPosition)
178 {
179     ParserError error;
180     VM& vm = exec.vm();
181     auto& globalObject = *exec.lexicalGlobalObject();
182     CodeCache* codeCache = vm.codeCache();
183     DebuggerMode debuggerMode = globalObject.hasInteractiveDebugger() ? DebuggerOn : DebuggerOff;
184     UnlinkedFunctionExecutable* executable = codeCache->getUnlinkedGlobalFunctionExecutable(vm, name, source, debuggerMode, functionConstructorParametersEndPosition, error);
185
186     if (globalObject.hasDebugger())
187         globalObject.debugger()->sourceParsed(&exec, source.provider(), error.line(), error.message());
188
189     if (error.isValid()) {
190         exception = error.toErrorObject(&globalObject, source, overrideLineNumber);
191         return nullptr;
192     }
193
194     return executable;
195 }
196
197 UnlinkedFunctionCodeBlock* UnlinkedFunctionExecutable::unlinkedCodeBlockFor(CodeSpecializationKind specializationKind)
198 {
199     switch (specializationKind) {
200     case CodeForCall:
201         return m_unlinkedCodeBlockForCall.get();
202     case CodeForConstruct:
203         return m_unlinkedCodeBlockForConstruct.get();
204     }
205 }
206
207 UnlinkedFunctionCodeBlock* UnlinkedFunctionExecutable::unlinkedCodeBlockFor(
208     VM& vm, const SourceCode& source, CodeSpecializationKind specializationKind, 
209     DebuggerMode debuggerMode, ParserError& error, SourceParseMode parseMode)
210 {
211     switch (specializationKind) {
212     case CodeForCall:
213         if (UnlinkedFunctionCodeBlock* codeBlock = m_unlinkedCodeBlockForCall.get())
214             return codeBlock;
215         break;
216     case CodeForConstruct:
217         if (UnlinkedFunctionCodeBlock* codeBlock = m_unlinkedCodeBlockForConstruct.get())
218             return codeBlock;
219         break;
220     }
221
222     UnlinkedFunctionCodeBlock* result = generateUnlinkedFunctionCodeBlock(
223         vm, this, source, specializationKind, debuggerMode, 
224         isBuiltinFunction() ? UnlinkedBuiltinFunction : UnlinkedNormalFunction, 
225         error, parseMode);
226     
227     if (error.isValid())
228         return nullptr;
229
230     switch (specializationKind) {
231     case CodeForCall:
232         m_unlinkedCodeBlockForCall.set(vm, this, result);
233         break;
234     case CodeForConstruct:
235         m_unlinkedCodeBlockForConstruct.set(vm, this, result);
236         break;
237     }
238     vm.unlinkedFunctionExecutableSpace.clearableCodeSet.add(this);
239     return result;
240 }
241
242 void UnlinkedFunctionExecutable::setInvalidTypeProfilingOffsets()
243 {
244     m_typeProfilingStartOffset = std::numeric_limits<unsigned>::max();
245     m_typeProfilingEndOffset = std::numeric_limits<unsigned>::max();
246 }
247
248 } // namespace JSC