2 * Copyright (C) 2008-2017 Apple Inc. All rights reserved.
3 * Copyright (C) 2008 Cameron Zwarich <cwzwarich@uwaterloo.ca>
4 * Copyright (C) 2012 Igalia, S.L.
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions
10 * 1. Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above copyright
13 * notice, this list of conditions and the following disclaimer in the
14 * documentation and/or other materials provided with the distribution.
15 * 3. Neither the name of Apple Inc. ("Apple") nor the names of
16 * its contributors may be used to endorse or promote products derived
17 * from this software without specific prior written permission.
19 * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
20 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
21 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
22 * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
23 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
24 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
25 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
26 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
28 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32 #include "BytecodeGenerator.h"
34 #include "ArithProfile.h"
35 #include "BuiltinExecutables.h"
36 #include "BuiltinNames.h"
37 #include "BytecodeGeneratorification.h"
38 #include "BytecodeLivenessAnalysis.h"
39 #include "DefinePropertyAttributes.h"
40 #include "Interpreter.h"
41 #include "JSAsyncGeneratorFunction.h"
42 #include "JSCInlines.h"
43 #include "JSFunction.h"
44 #include "JSGeneratorFunction.h"
45 #include "JSLexicalEnvironment.h"
46 #include "JSTemplateRegistryKey.h"
47 #include "LowLevelInterpreter.h"
49 #include "StackAlignment.h"
50 #include "StrongInlines.h"
51 #include "UnlinkedCodeBlock.h"
52 #include "UnlinkedEvalCodeBlock.h"
53 #include "UnlinkedFunctionCodeBlock.h"
54 #include "UnlinkedInstructionStream.h"
55 #include "UnlinkedModuleProgramCodeBlock.h"
56 #include "UnlinkedProgramCodeBlock.h"
57 #include <wtf/BitVector.h>
58 #include <wtf/CommaPrinter.h>
59 #include <wtf/SmallPtrSet.h>
60 #include <wtf/StdLibExtras.h>
61 #include <wtf/text/WTFString.h>
68 static inline void shrinkToFit(T& segmentedVector)
70 while (segmentedVector.size() && !segmentedVector.last().refCount())
71 segmentedVector.removeLast();
74 void Label::setLocation(BytecodeGenerator& generator, unsigned location)
76 m_location = location;
78 unsigned size = m_unresolvedJumps.size();
79 for (unsigned i = 0; i < size; ++i)
80 generator.instructions()[m_unresolvedJumps[i].second].u.operand = m_location - m_unresolvedJumps[i].first;
83 void Variable::dump(PrintStream& out) const
87 ", offset = ", m_offset,
88 ", local = ", RawPointer(m_local),
89 ", attributes = ", m_attributes,
91 ", symbolTableConstantIndex = ", m_symbolTableConstantIndex,
92 ", isLexicallyScoped = ", m_isLexicallyScoped, "}");
95 ParserError BytecodeGenerator::generate()
97 m_codeBlock->setThisRegister(m_thisRegister.virtualRegister());
99 emitLogShadowChickenPrologueIfNecessary();
101 // If we have declared a variable named "arguments" and we are using arguments then we should
102 // perform that assignment now.
103 if (m_needToInitializeArguments)
104 initializeVariable(variable(propertyNames().arguments), m_argumentsRegister);
107 m_restParameter->emit(*this);
110 RefPtr<RegisterID> temp = newTemporary();
111 RefPtr<RegisterID> tolLevelScope;
112 for (auto functionPair : m_functionsToInitialize) {
113 FunctionMetadataNode* metadata = functionPair.first;
114 FunctionVariableType functionType = functionPair.second;
115 emitNewFunction(temp.get(), metadata);
116 if (functionType == NormalFunctionVariable)
117 initializeVariable(variable(metadata->ident()), temp.get());
118 else if (functionType == TopLevelFunctionVariable) {
119 if (!tolLevelScope) {
120 // We know this will resolve to the top level scope or global object because our parser/global initialization code
121 // doesn't allow let/const/class variables to have the same names as functions.
122 // This is a top level function, and it's an error to ever create a top level function
123 // name that would resolve to a lexical variable. E.g:
129 // //// error thrown here
130 // eval("function x(){}");
135 // Therefore, we're guaranteed to have this resolve to a top level variable.
136 RefPtr<RegisterID> tolLevelObjectScope = emitResolveScope(nullptr, Variable(metadata->ident()));
137 tolLevelScope = newBlockScopeVariable();
138 emitMove(tolLevelScope.get(), tolLevelObjectScope.get());
140 emitPutToScope(tolLevelScope.get(), Variable(metadata->ident()), temp.get(), ThrowIfNotFound, InitializationMode::NotInitialization);
142 RELEASE_ASSERT_NOT_REACHED();
146 bool callingClassConstructor = constructorKind() != ConstructorKind::None && !isConstructor();
147 if (!callingClassConstructor)
148 m_scopeNode->emitBytecode(*this);
150 // At this point we would have emitted an unconditional throw followed by some nonsense that's
151 // just an artifact of how this generator is structured. That code never runs, but it confuses
152 // bytecode analyses because it constitutes an unterminated basic block. So, we terminate the
153 // basic block the strongest way possible.
157 for (auto& tuple : m_catchesToEmit) {
158 Ref<Label> realCatchTarget = newEmittedLabel();
159 emitOpcode(op_catch);
160 instructions().append(std::get<1>(tuple));
161 instructions().append(std::get<2>(tuple));
162 instructions().append(0);
164 TryData* tryData = std::get<0>(tuple);
165 emitJump(tryData->target.get());
166 tryData->target = WTFMove(realCatchTarget);
169 m_staticPropertyAnalyzer.kill();
171 for (auto& range : m_tryRanges) {
172 int start = range.start->bind();
173 int end = range.end->bind();
175 // This will happen for empty try blocks and for some cases of finally blocks:
187 // The return will pop scopes to execute the outer finally block. But this includes
188 // popping the try context for the inner try. The try context is live in the fall-through
189 // part of the finally block not because we will emit a handler that overlaps the finally,
190 // but because we haven't yet had a chance to plant the catch target. Then when we finish
191 // emitting code for the outer finally block, we repush the try contex, this time with a
192 // new start index. But that means that the start index for the try range corresponding
193 // to the inner-finally-following-the-return (marked as "*HERE*" above) will be greater
194 // than the end index of the try block. This is harmless since end < start handlers will
195 // never get matched in our logic, but we do the runtime a favor and choose to not emit
196 // such handlers at all.
200 UnlinkedHandlerInfo info(static_cast<uint32_t>(start), static_cast<uint32_t>(end),
201 static_cast<uint32_t>(range.tryData->target->bind()), range.tryData->handlerType);
202 m_codeBlock->addExceptionHandler(info);
206 if (isGeneratorOrAsyncFunctionBodyParseMode(m_codeBlock->parseMode()))
207 performGeneratorification(m_codeBlock.get(), m_instructions, m_generatorFrameSymbolTable.get(), m_generatorFrameSymbolTableIndex);
209 RELEASE_ASSERT(static_cast<unsigned>(m_codeBlock->numCalleeLocals()) < static_cast<unsigned>(FirstConstantRegisterIndex));
210 m_codeBlock->setInstructions(std::make_unique<UnlinkedInstructionStream>(m_instructions));
212 m_codeBlock->shrinkToFit();
214 if (m_expressionTooDeep)
215 return ParserError(ParserError::OutOfMemory);
216 return ParserError(ParserError::ErrorNone);
219 BytecodeGenerator::BytecodeGenerator(VM& vm, ProgramNode* programNode, UnlinkedProgramCodeBlock* codeBlock, DebuggerMode debuggerMode, const VariableEnvironment* parentScopeTDZVariables)
220 : m_shouldEmitDebugHooks(Options::forceDebuggerBytecodeGeneration() || debuggerMode == DebuggerOn)
221 , m_scopeNode(programNode)
222 , m_codeBlock(vm, codeBlock)
223 , m_thisRegister(CallFrame::thisArgumentOffset())
224 , m_codeType(GlobalCode)
226 , m_needsToUpdateArrowFunctionContext(programNode->usesArrowFunction() || programNode->usesEval())
228 ASSERT_UNUSED(parentScopeTDZVariables, !parentScopeTDZVariables->size());
230 for (auto& constantRegister : m_linkTimeConstantRegisters)
231 constantRegister = nullptr;
233 allocateCalleeSaveSpace();
235 m_codeBlock->setNumParameters(1); // Allocate space for "this"
239 allocateAndEmitScope();
243 const FunctionStack& functionStack = programNode->functionStack();
245 for (auto* function : functionStack)
246 m_functionsToInitialize.append(std::make_pair(function, TopLevelFunctionVariable));
248 if (Options::validateBytecode()) {
249 for (auto& entry : programNode->varDeclarations())
250 RELEASE_ASSERT(entry.value.isVar());
252 codeBlock->setVariableDeclarations(programNode->varDeclarations());
253 codeBlock->setLexicalDeclarations(programNode->lexicalVariables());
254 // Even though this program may have lexical variables that go under TDZ, when linking the get_from_scope/put_to_scope
255 // operations we emit we will have ResolveTypes that implictly do TDZ checks. Therefore, we don't need
256 // additional TDZ checks on top of those. This is why we can omit pushing programNode->lexicalVariables()
259 if (needsToUpdateArrowFunctionContext()) {
260 initializeArrowFunctionContextScopeIfNeeded();
261 emitPutThisToArrowFunctionContextScope();
265 BytecodeGenerator::BytecodeGenerator(VM& vm, FunctionNode* functionNode, UnlinkedFunctionCodeBlock* codeBlock, DebuggerMode debuggerMode, const VariableEnvironment* parentScopeTDZVariables)
266 : m_shouldEmitDebugHooks(Options::forceDebuggerBytecodeGeneration() || debuggerMode == DebuggerOn)
267 , m_scopeNode(functionNode)
268 , m_codeBlock(vm, codeBlock)
269 , m_codeType(FunctionCode)
271 , m_isBuiltinFunction(codeBlock->isBuiltinFunction())
272 , m_usesNonStrictEval(codeBlock->usesEval() && !codeBlock->isStrictMode())
273 // FIXME: We should be able to have tail call elimination with the profiler
274 // enabled. This is currently not possible because the profiler expects
275 // op_will_call / op_did_call pairs before and after a call, which are not
276 // compatible with tail calls (we have no way of emitting op_did_call).
277 // https://bugs.webkit.org/show_bug.cgi?id=148819
278 , m_inTailPosition(Options::useTailCalls() && !isConstructor() && constructorKind() == ConstructorKind::None && isStrictMode())
279 , m_needsToUpdateArrowFunctionContext(functionNode->usesArrowFunction() || functionNode->usesEval())
280 , m_derivedContextType(codeBlock->derivedContextType())
282 for (auto& constantRegister : m_linkTimeConstantRegisters)
283 constantRegister = nullptr;
285 if (m_isBuiltinFunction)
286 m_shouldEmitDebugHooks = false;
288 allocateCalleeSaveSpace();
290 SymbolTable* functionSymbolTable = SymbolTable::create(*m_vm);
291 functionSymbolTable->setUsesNonStrictEval(m_usesNonStrictEval);
292 int symbolTableConstantIndex = 0;
294 FunctionParameters& parameters = *functionNode->parameters();
295 // http://www.ecma-international.org/ecma-262/6.0/index.html#sec-functiondeclarationinstantiation
296 // This implements IsSimpleParameterList in the Ecma 2015 spec.
297 // If IsSimpleParameterList is false, we will create a strict-mode like arguments object.
298 // IsSimpleParameterList is false if the argument list contains any default parameter values,
299 // a rest parameter, or any destructuring patterns.
300 // If we do have default parameters, destructuring parameters, or a rest parameter, our parameters will be allocated in a different scope.
301 bool isSimpleParameterList = parameters.isSimpleParameterList();
303 SourceParseMode parseMode = codeBlock->parseMode();
305 bool containsArrowOrEvalButNotInArrowBlock = ((functionNode->usesArrowFunction() && functionNode->doAnyInnerArrowFunctionsUseAnyFeature()) || functionNode->usesEval()) && !m_codeBlock->isArrowFunction();
306 bool shouldCaptureSomeOfTheThings = m_shouldEmitDebugHooks || functionNode->needsActivation() || containsArrowOrEvalButNotInArrowBlock;
308 bool shouldCaptureAllOfTheThings = m_shouldEmitDebugHooks || codeBlock->usesEval();
309 bool needsArguments = ((functionNode->usesArguments() && !codeBlock->isArrowFunction()) || codeBlock->usesEval() || (functionNode->usesArrowFunction() && !codeBlock->isArrowFunction() && isArgumentsUsedInInnerArrowFunction()));
311 if (isGeneratorOrAsyncFunctionBodyParseMode(parseMode)) {
312 // Generator and AsyncFunction never provides "arguments". "arguments" reference will be resolved in an upper generator function scope.
313 needsArguments = false;
315 // Generator and AsyncFunction uses the var scope to save and resume its variables. So the lexical scope is always instantiated.
316 shouldCaptureSomeOfTheThings = true;
319 if (isGeneratorOrAsyncFunctionWrapperParseMode(parseMode) && needsArguments) {
320 // Generator does not provide "arguments". Instead, wrapping GeneratorFunction provides "arguments".
321 // This is because arguments of a generator should be evaluated before starting it.
322 // To workaround it, we evaluate these arguments as arguments of a wrapping generator function, and reference it from a generator.
324 // function *gen(a, b = hello())
327 // @generatorNext: function (@generator, @generatorState, @generatorValue, @generatorResumeMode, @generatorFrame)
329 // arguments; // This `arguments` should reference to the gen's arguments.
334 shouldCaptureSomeOfTheThings = true;
337 if (shouldCaptureAllOfTheThings)
338 functionNode->varDeclarations().markAllVariablesAsCaptured();
340 auto captures = [&] (UniquedStringImpl* uid) -> bool {
341 if (!shouldCaptureSomeOfTheThings)
343 if (needsArguments && uid == propertyNames().arguments.impl()) {
344 // Actually, we only need to capture the arguments object when we "need full activation"
345 // because of name scopes. But historically we did it this way, so for now we just preserve
347 // FIXME: https://bugs.webkit.org/show_bug.cgi?id=143072
350 return functionNode->captures(uid);
352 auto varKind = [&] (UniquedStringImpl* uid) -> VarKind {
353 return captures(uid) ? VarKind::Scope : VarKind::Stack;
356 m_calleeRegister.setIndex(CallFrameSlot::callee);
358 initializeParameters(parameters);
359 ASSERT(!(isSimpleParameterList && m_restParameter));
363 if (isGeneratorOrAsyncFunctionBodyParseMode(parseMode))
364 m_generatorRegister = &m_parameters[1];
366 allocateAndEmitScope();
370 if (functionNameIsInScope(functionNode->ident(), functionNode->functionMode())) {
371 ASSERT(parseMode != SourceParseMode::GeneratorBodyMode);
372 ASSERT(!isAsyncFunctionBodyParseMode(parseMode));
373 bool isDynamicScope = functionNameScopeIsDynamic(codeBlock->usesEval(), codeBlock->isStrictMode());
374 bool isFunctionNameCaptured = captures(functionNode->ident().impl());
375 bool markAsCaptured = isDynamicScope || isFunctionNameCaptured;
376 emitPushFunctionNameScope(functionNode->ident(), &m_calleeRegister, markAsCaptured);
379 if (shouldCaptureSomeOfTheThings)
380 m_lexicalEnvironmentRegister = addVar();
382 if (shouldCaptureSomeOfTheThings || vm.typeProfiler())
383 symbolTableConstantIndex = addConstantValue(functionSymbolTable)->index();
385 // We can allocate the "var" environment if we don't have default parameter expressions. If we have
386 // default parameter expressions, we have to hold off on allocating the "var" environment because
387 // the parent scope of the "var" environment is the parameter environment.
388 if (isSimpleParameterList)
389 initializeVarLexicalEnvironment(symbolTableConstantIndex, functionSymbolTable, shouldCaptureSomeOfTheThings);
391 // Figure out some interesting facts about our arguments.
392 bool capturesAnyArgumentByName = false;
393 if (functionNode->hasCapturedVariables()) {
394 FunctionParameters& parameters = *functionNode->parameters();
395 for (size_t i = 0; i < parameters.size(); ++i) {
396 auto pattern = parameters.at(i).first;
397 if (!pattern->isBindingNode())
399 const Identifier& ident = static_cast<const BindingNode*>(pattern)->boundProperty();
400 capturesAnyArgumentByName |= captures(ident.impl());
404 if (capturesAnyArgumentByName)
405 ASSERT(m_lexicalEnvironmentRegister);
407 // Need to know what our functions are called. Parameters have some goofy behaviors when it
408 // comes to functions of the same name.
409 for (FunctionMetadataNode* function : functionNode->functionStack())
410 m_functions.add(function->ident().impl());
412 if (needsArguments) {
413 // Create the arguments object now. We may put the arguments object into the activation if
414 // it is captured. Either way, we create two arguments object variables: one is our
415 // private variable that is immutable, and another that is the user-visible variable. The
416 // immutable one is only used here, or during formal parameter resolutions if we opt for
419 m_argumentsRegister = addVar();
420 m_argumentsRegister->ref();
423 if (needsArguments && !codeBlock->isStrictMode() && isSimpleParameterList) {
424 // If we captured any formal parameter by name, then we use ScopedArguments. Otherwise we
425 // use DirectArguments. With ScopedArguments, we lift all of our arguments into the
428 if (capturesAnyArgumentByName) {
429 functionSymbolTable->setArgumentsLength(vm, parameters.size());
431 // For each parameter, we have two possibilities:
432 // Either it's a binding node with no function overlap, in which case it gets a name
433 // in the symbol table - or it just gets space reserved in the symbol table. Either
434 // way we lift the value into the scope.
435 for (unsigned i = 0; i < parameters.size(); ++i) {
436 ScopeOffset offset = functionSymbolTable->takeNextScopeOffset(NoLockingNecessary);
437 functionSymbolTable->setArgumentOffset(vm, i, offset);
438 if (UniquedStringImpl* name = visibleNameForParameter(parameters.at(i).first)) {
439 VarOffset varOffset(offset);
440 SymbolTableEntry entry(varOffset);
441 // Stores to these variables via the ScopedArguments object will not do
442 // notifyWrite(), since that would be cumbersome. Also, watching formal
443 // parameters when "arguments" is in play is unlikely to be super profitable.
444 // So, we just disable it.
445 entry.disableWatching(*m_vm);
446 functionSymbolTable->set(NoLockingNecessary, name, entry);
448 emitOpcode(op_put_to_scope);
449 instructions().append(m_lexicalEnvironmentRegister->index());
450 instructions().append(UINT_MAX);
451 instructions().append(virtualRegisterForArgument(1 + i).offset());
452 instructions().append(GetPutInfo(ThrowIfNotFound, LocalClosureVar, InitializationMode::NotInitialization).operand());
453 instructions().append(symbolTableConstantIndex);
454 instructions().append(offset.offset());
457 // This creates a scoped arguments object and copies the overflow arguments into the
458 // scope. It's the equivalent of calling ScopedArguments::createByCopying().
459 emitOpcode(op_create_scoped_arguments);
460 instructions().append(m_argumentsRegister->index());
461 instructions().append(m_lexicalEnvironmentRegister->index());
463 // We're going to put all parameters into the DirectArguments object. First ensure
464 // that the symbol table knows that this is happening.
465 for (unsigned i = 0; i < parameters.size(); ++i) {
466 if (UniquedStringImpl* name = visibleNameForParameter(parameters.at(i).first))
467 functionSymbolTable->set(NoLockingNecessary, name, SymbolTableEntry(VarOffset(DirectArgumentsOffset(i))));
470 emitOpcode(op_create_direct_arguments);
471 instructions().append(m_argumentsRegister->index());
473 } else if (isSimpleParameterList) {
474 // Create the formal parameters the normal way. Any of them could be captured, or not. If
475 // captured, lift them into the scope. We cannot do this if we have default parameter expressions
476 // because when default parameter expressions exist, they belong in their own lexical environment
477 // separate from the "var" lexical environment.
478 for (unsigned i = 0; i < parameters.size(); ++i) {
479 UniquedStringImpl* name = visibleNameForParameter(parameters.at(i).first);
483 if (!captures(name)) {
484 // This is the easy case - just tell the symbol table about the argument. It will
485 // be accessed directly.
486 functionSymbolTable->set(NoLockingNecessary, name, SymbolTableEntry(VarOffset(virtualRegisterForArgument(1 + i))));
490 ScopeOffset offset = functionSymbolTable->takeNextScopeOffset(NoLockingNecessary);
491 const Identifier& ident =
492 static_cast<const BindingNode*>(parameters.at(i).first)->boundProperty();
493 functionSymbolTable->set(NoLockingNecessary, name, SymbolTableEntry(VarOffset(offset)));
495 emitOpcode(op_put_to_scope);
496 instructions().append(m_lexicalEnvironmentRegister->index());
497 instructions().append(addConstant(ident));
498 instructions().append(virtualRegisterForArgument(1 + i).offset());
499 instructions().append(GetPutInfo(ThrowIfNotFound, LocalClosureVar, InitializationMode::NotInitialization).operand());
500 instructions().append(symbolTableConstantIndex);
501 instructions().append(offset.offset());
505 if (needsArguments && (codeBlock->isStrictMode() || !isSimpleParameterList)) {
506 // Allocate a cloned arguments object.
507 emitOpcode(op_create_cloned_arguments);
508 instructions().append(m_argumentsRegister->index());
511 // There are some variables that need to be preinitialized to something other than Undefined:
513 // - "arguments": unless it's used as a function or parameter, this should refer to the
516 // - functions: these always override everything else.
518 // The most logical way to do all of this is to initialize none of the variables until now,
519 // and then initialize them in BytecodeGenerator::generate() in such an order that the rules
520 // for how these things override each other end up holding. We would initialize "arguments" first,
521 // then all arguments, then the functions.
523 // But some arguments are already initialized by default, since if they aren't captured and we
524 // don't have "arguments" then we just point the symbol table at the stack slot of those
525 // arguments. We end up initializing the rest of the arguments that have an uncomplicated
526 // binding (i.e. don't involve destructuring) above when figuring out how to lay them out,
527 // because that's just the simplest thing. This means that when we initialize them, we have to
528 // watch out for the things that override arguments (namely, functions).
530 // This is our final act of weirdness. "arguments" is overridden by everything except the
531 // callee. We add it to the symbol table if it's not already there and it's not an argument.
532 bool shouldCreateArgumentsVariableInParameterScope = false;
533 if (needsArguments) {
534 // If "arguments" is overridden by a function or destructuring parameter name, then it's
535 // OK for us to call createVariable() because it won't change anything. It's also OK for
536 // us to them tell BytecodeGenerator::generate() to write to it because it will do so
537 // before it initializes functions and destructuring parameters. But if "arguments" is
538 // overridden by a "simple" function parameter, then we have to bail: createVariable()
539 // would assert and BytecodeGenerator::generate() would write the "arguments" after the
540 // argument value had already been properly initialized.
542 bool haveParameterNamedArguments = false;
543 for (unsigned i = 0; i < parameters.size(); ++i) {
544 UniquedStringImpl* name = visibleNameForParameter(parameters.at(i).first);
545 if (name == propertyNames().arguments.impl()) {
546 haveParameterNamedArguments = true;
551 bool shouldCreateArgumensVariable = !haveParameterNamedArguments
552 && !SourceParseModeSet(SourceParseMode::ArrowFunctionMode, SourceParseMode::AsyncArrowFunctionMode).contains(m_codeBlock->parseMode());
553 shouldCreateArgumentsVariableInParameterScope = shouldCreateArgumensVariable && !isSimpleParameterList;
554 // Do not create arguments variable in case of Arrow function. Value will be loaded from parent scope
555 if (shouldCreateArgumensVariable && !shouldCreateArgumentsVariableInParameterScope) {
557 propertyNames().arguments, varKind(propertyNames().arguments.impl()), functionSymbolTable);
559 m_needToInitializeArguments = true;
563 for (FunctionMetadataNode* function : functionNode->functionStack()) {
564 const Identifier& ident = function->ident();
565 createVariable(ident, varKind(ident.impl()), functionSymbolTable);
566 m_functionsToInitialize.append(std::make_pair(function, NormalFunctionVariable));
568 for (auto& entry : functionNode->varDeclarations()) {
569 ASSERT(!entry.value.isLet() && !entry.value.isConst());
570 if (!entry.value.isVar()) // This is either a parameter or callee.
572 if (shouldCreateArgumentsVariableInParameterScope && entry.key.get() == propertyNames().arguments.impl())
574 createVariable(Identifier::fromUid(m_vm, entry.key.get()), varKind(entry.key.get()), functionSymbolTable, IgnoreExisting);
578 m_newTargetRegister = addVar();
580 case SourceParseMode::GeneratorWrapperFunctionMode:
581 case SourceParseMode::GeneratorWrapperMethodMode:
582 case SourceParseMode::AsyncGeneratorWrapperMethodMode:
583 case SourceParseMode::AsyncGeneratorWrapperFunctionMode: {
584 m_generatorRegister = addVar();
586 // FIXME: Emit to_this only when Generator uses it.
587 // https://bugs.webkit.org/show_bug.cgi?id=151586
588 m_codeBlock->addPropertyAccessInstruction(instructions().size());
589 emitOpcode(op_to_this);
590 instructions().append(kill(&m_thisRegister));
591 instructions().append(0);
592 instructions().append(0);
594 emitMove(m_generatorRegister, &m_calleeRegister);
595 emitCreateThis(m_generatorRegister);
599 case SourceParseMode::AsyncArrowFunctionMode:
600 case SourceParseMode::AsyncMethodMode:
601 case SourceParseMode::AsyncFunctionMode: {
602 ASSERT(!isConstructor());
603 ASSERT(constructorKind() == ConstructorKind::None);
604 m_generatorRegister = addVar();
605 m_promiseCapabilityRegister = addVar();
607 if (parseMode != SourceParseMode::AsyncArrowFunctionMode) {
608 // FIXME: Emit to_this only when AsyncFunctionBody uses it.
609 // https://bugs.webkit.org/show_bug.cgi?id=151586
610 m_codeBlock->addPropertyAccessInstruction(instructions().size());
611 emitOpcode(op_to_this);
612 instructions().append(kill(&m_thisRegister));
613 instructions().append(0);
614 instructions().append(0);
617 emitNewObject(m_generatorRegister);
619 // let promiseCapability be @newPromiseCapability(@Promise)
620 auto varNewPromiseCapability = variable(propertyNames().builtinNames().newPromiseCapabilityPrivateName());
621 RefPtr<RegisterID> scope = newTemporary();
622 moveToDestinationIfNeeded(scope.get(), emitResolveScope(scope.get(), varNewPromiseCapability));
623 RefPtr<RegisterID> newPromiseCapability = emitGetFromScope(newTemporary(), scope.get(), varNewPromiseCapability, ThrowIfNotFound);
625 CallArguments args(*this, nullptr, 1);
626 emitLoad(args.thisRegister(), jsUndefined());
628 auto varPromiseConstructor = variable(propertyNames().builtinNames().PromisePrivateName());
629 moveToDestinationIfNeeded(scope.get(), emitResolveScope(scope.get(), varPromiseConstructor));
630 emitGetFromScope(args.argumentRegister(0), scope.get(), varPromiseConstructor, ThrowIfNotFound);
632 // JSTextPosition(int _line, int _offset, int _lineStartOffset)
633 JSTextPosition divot(m_scopeNode->firstLine(), m_scopeNode->startOffset(), m_scopeNode->lineStartOffset());
634 emitCall(promiseCapabilityRegister(), newPromiseCapability.get(), NoExpectedFunction, args, divot, divot, divot, DebuggableCall::No);
638 case SourceParseMode::AsyncGeneratorBodyMode:
639 case SourceParseMode::AsyncFunctionBodyMode:
640 case SourceParseMode::AsyncArrowFunctionBodyMode:
641 case SourceParseMode::GeneratorBodyMode: {
642 // |this| is already filled correctly before here.
643 emitLoad(m_newTargetRegister, jsUndefined());
648 if (SourceParseMode::ArrowFunctionMode != parseMode) {
649 if (isConstructor()) {
650 emitMove(m_newTargetRegister, &m_thisRegister);
651 if (constructorKind() == ConstructorKind::Extends) {
652 emitMoveEmptyValue(&m_thisRegister);
654 emitCreateThis(&m_thisRegister);
655 } else if (constructorKind() != ConstructorKind::None)
656 emitThrowTypeError("Cannot call a class constructor without |new|");
658 bool shouldEmitToThis = false;
659 if (functionNode->usesThis() || codeBlock->usesEval() || m_scopeNode->doAnyInnerArrowFunctionsUseThis() || m_scopeNode->doAnyInnerArrowFunctionsUseEval())
660 shouldEmitToThis = true;
661 else if ((functionNode->usesSuperProperty() || m_scopeNode->doAnyInnerArrowFunctionsUseSuperProperty()) && !codeBlock->isStrictMode()) {
662 // We must emit to_this when we're not in strict mode because we
663 // will convert |this| to an object, and that object may be passed
664 // to a strict function as |this|. This is observable because that
665 // strict function's to_this will just return the object.
667 // We don't need to emit this for strict-mode code because
668 // strict-mode code may call another strict function, which will
669 // to_this if it directly uses this; this is OK, because we defer
670 // to_this until |this| is used directly. Strict-mode code might
671 // also call a sloppy mode function, and that will to_this, which
672 // will defer the conversion, again, until necessary.
673 shouldEmitToThis = true;
676 if (shouldEmitToThis) {
677 m_codeBlock->addPropertyAccessInstruction(instructions().size());
678 emitOpcode(op_to_this);
679 instructions().append(kill(&m_thisRegister));
680 instructions().append(0);
681 instructions().append(0);
689 // We need load |super| & |this| for arrow function before initializeDefaultParameterValuesAndSetupFunctionScopeStack
690 // if we have default parameter expression. Because |super| & |this| values can be used there
691 if ((SourceParseModeSet(SourceParseMode::ArrowFunctionMode, SourceParseMode::AsyncArrowFunctionMode).contains(parseMode) && !isSimpleParameterList) || parseMode == SourceParseMode::AsyncArrowFunctionBodyMode) {
692 if (functionNode->usesThis() || functionNode->usesSuperProperty())
693 emitLoadThisFromArrowFunctionLexicalEnvironment();
695 if (m_scopeNode->usesNewTarget() || m_scopeNode->usesSuperCall())
696 emitLoadNewTargetFromArrowFunctionLexicalEnvironment();
699 if (needsToUpdateArrowFunctionContext() && !codeBlock->isArrowFunction()) {
700 bool canReuseLexicalEnvironment = isSimpleParameterList;
701 initializeArrowFunctionContextScopeIfNeeded(functionSymbolTable, canReuseLexicalEnvironment);
702 emitPutThisToArrowFunctionContextScope();
703 emitPutNewTargetToArrowFunctionContextScope();
704 emitPutDerivedConstructorToArrowFunctionContextScope();
707 // All "addVar()"s needs to happen before "initializeDefaultParameterValuesAndSetupFunctionScopeStack()" is called
708 // because a function's default parameter ExpressionNodes will use temporary registers.
709 pushTDZVariables(*parentScopeTDZVariables, TDZCheckOptimization::DoNotOptimize, TDZRequirement::UnderTDZ);
711 Ref<Label> catchLabel = newLabel();
712 TryData* tryFormalParametersData = nullptr;
713 bool needTryCatch = isAsyncFunctionWrapperParseMode(parseMode) && !isSimpleParameterList;
715 Ref<Label> tryFormalParametersStart = newEmittedLabel();
716 tryFormalParametersData = pushTry(tryFormalParametersStart.get(), catchLabel.get(), HandlerType::SynthesizedCatch);
719 initializeDefaultParameterValuesAndSetupFunctionScopeStack(parameters, isSimpleParameterList, functionNode, functionSymbolTable, symbolTableConstantIndex, captures, shouldCreateArgumentsVariableInParameterScope);
722 Ref<Label> didNotThrow = newLabel();
723 emitJump(didNotThrow.get());
724 emitLabel(catchLabel.get());
725 popTry(tryFormalParametersData, catchLabel.get());
727 RefPtr<RegisterID> thrownValue = newTemporary();
728 RegisterID* unused = newTemporary();
729 emitCatch(unused, thrownValue.get(), tryFormalParametersData);
731 // return promiseCapability.@reject(thrownValue)
732 RefPtr<RegisterID> reject = emitGetById(newTemporary(), promiseCapabilityRegister(), m_vm->propertyNames->builtinNames().rejectPrivateName());
734 CallArguments args(*this, nullptr, 1);
735 emitLoad(args.thisRegister(), jsUndefined());
736 emitMove(args.argumentRegister(0), thrownValue.get());
738 JSTextPosition divot(functionNode->firstLine(), functionNode->startOffset(), functionNode->lineStartOffset());
740 RefPtr<RegisterID> result = emitCall(newTemporary(), reject.get(), NoExpectedFunction, args, divot, divot, divot, DebuggableCall::No);
741 emitReturn(emitGetById(newTemporary(), promiseCapabilityRegister(), m_vm->propertyNames->builtinNames().promisePrivateName()));
743 emitLabel(didNotThrow.get());
746 // If we don't have default parameter expression, then loading |this| inside an arrow function must be done
747 // after initializeDefaultParameterValuesAndSetupFunctionScopeStack() because that function sets up the
748 // SymbolTable stack and emitLoadThisFromArrowFunctionLexicalEnvironment() consults the SymbolTable stack
749 if (SourceParseModeSet(SourceParseMode::ArrowFunctionMode, SourceParseMode::AsyncArrowFunctionMode).contains(parseMode) && isSimpleParameterList) {
750 if (functionNode->usesThis() || functionNode->usesSuperProperty())
751 emitLoadThisFromArrowFunctionLexicalEnvironment();
753 if (m_scopeNode->usesNewTarget() || m_scopeNode->usesSuperCall())
754 emitLoadNewTargetFromArrowFunctionLexicalEnvironment();
757 // Set up the lexical environment scope as the generator frame. We store the saved and resumed generator registers into this scope with the symbol keys.
758 // Since they are symbol keyed, these variables cannot be reached from the usual code.
759 if (isGeneratorOrAsyncFunctionBodyParseMode(parseMode)) {
760 ASSERT(m_lexicalEnvironmentRegister);
761 m_generatorFrameSymbolTable.set(*m_vm, functionSymbolTable);
762 m_generatorFrameSymbolTableIndex = symbolTableConstantIndex;
763 emitMove(generatorFrameRegister(), m_lexicalEnvironmentRegister);
764 emitPutById(generatorRegister(), propertyNames().builtinNames().generatorFramePrivateName(), generatorFrameRegister());
767 bool shouldInitializeBlockScopedFunctions = false; // We generate top-level function declarations in ::generate().
768 pushLexicalScope(m_scopeNode, TDZCheckOptimization::Optimize, NestedScopeType::IsNotNested, nullptr, shouldInitializeBlockScopedFunctions);
771 BytecodeGenerator::BytecodeGenerator(VM& vm, EvalNode* evalNode, UnlinkedEvalCodeBlock* codeBlock, DebuggerMode debuggerMode, const VariableEnvironment* parentScopeTDZVariables)
772 : m_shouldEmitDebugHooks(Options::forceDebuggerBytecodeGeneration() || debuggerMode == DebuggerOn)
773 , m_scopeNode(evalNode)
774 , m_codeBlock(vm, codeBlock)
775 , m_thisRegister(CallFrame::thisArgumentOffset())
776 , m_codeType(EvalCode)
778 , m_usesNonStrictEval(codeBlock->usesEval() && !codeBlock->isStrictMode())
779 , m_needsToUpdateArrowFunctionContext(evalNode->usesArrowFunction() || evalNode->usesEval())
780 , m_derivedContextType(codeBlock->derivedContextType())
782 for (auto& constantRegister : m_linkTimeConstantRegisters)
783 constantRegister = nullptr;
785 allocateCalleeSaveSpace();
787 m_codeBlock->setNumParameters(1);
789 pushTDZVariables(*parentScopeTDZVariables, TDZCheckOptimization::DoNotOptimize, TDZRequirement::UnderTDZ);
793 allocateAndEmitScope();
797 for (FunctionMetadataNode* function : evalNode->functionStack()) {
798 m_codeBlock->addFunctionDecl(makeFunction(function));
799 m_functionsToInitialize.append(std::make_pair(function, TopLevelFunctionVariable));
802 const VariableEnvironment& varDeclarations = evalNode->varDeclarations();
803 Vector<Identifier, 0, UnsafeVectorOverflow> variables;
804 Vector<Identifier, 0, UnsafeVectorOverflow> hoistedFunctions;
805 for (auto& entry : varDeclarations) {
806 ASSERT(entry.value.isVar());
807 ASSERT(entry.key->isAtomic() || entry.key->isSymbol());
808 if (entry.value.isSloppyModeHoistingCandidate())
809 hoistedFunctions.append(Identifier::fromUid(m_vm, entry.key.get()));
811 variables.append(Identifier::fromUid(m_vm, entry.key.get()));
813 codeBlock->adoptVariables(variables);
814 codeBlock->adoptFunctionHoistingCandidates(WTFMove(hoistedFunctions));
816 if (evalNode->usesSuperCall() || evalNode->usesNewTarget())
817 m_newTargetRegister = addVar();
819 if (codeBlock->isArrowFunctionContext() && (evalNode->usesThis() || evalNode->usesSuperProperty()))
820 emitLoadThisFromArrowFunctionLexicalEnvironment();
822 if (evalNode->usesSuperCall() || evalNode->usesNewTarget())
823 emitLoadNewTargetFromArrowFunctionLexicalEnvironment();
825 if (needsToUpdateArrowFunctionContext() && !codeBlock->isArrowFunctionContext() && !isDerivedConstructorContext()) {
826 initializeArrowFunctionContextScopeIfNeeded();
827 emitPutThisToArrowFunctionContextScope();
830 bool shouldInitializeBlockScopedFunctions = false; // We generate top-level function declarations in ::generate().
831 pushLexicalScope(m_scopeNode, TDZCheckOptimization::Optimize, NestedScopeType::IsNotNested, nullptr, shouldInitializeBlockScopedFunctions);
834 BytecodeGenerator::BytecodeGenerator(VM& vm, ModuleProgramNode* moduleProgramNode, UnlinkedModuleProgramCodeBlock* codeBlock, DebuggerMode debuggerMode, const VariableEnvironment* parentScopeTDZVariables)
835 : m_shouldEmitDebugHooks(Options::forceDebuggerBytecodeGeneration() || debuggerMode == DebuggerOn)
836 , m_scopeNode(moduleProgramNode)
837 , m_codeBlock(vm, codeBlock)
838 , m_thisRegister(CallFrame::thisArgumentOffset())
839 , m_codeType(ModuleCode)
841 , m_usesNonStrictEval(false)
842 , m_needsToUpdateArrowFunctionContext(moduleProgramNode->usesArrowFunction() || moduleProgramNode->usesEval())
844 ASSERT_UNUSED(parentScopeTDZVariables, !parentScopeTDZVariables->size());
846 for (auto& constantRegister : m_linkTimeConstantRegisters)
847 constantRegister = nullptr;
849 if (m_isBuiltinFunction)
850 m_shouldEmitDebugHooks = false;
852 allocateCalleeSaveSpace();
854 SymbolTable* moduleEnvironmentSymbolTable = SymbolTable::create(*m_vm);
855 moduleEnvironmentSymbolTable->setUsesNonStrictEval(m_usesNonStrictEval);
856 moduleEnvironmentSymbolTable->setScopeType(SymbolTable::ScopeType::LexicalScope);
858 bool shouldCaptureAllOfTheThings = m_shouldEmitDebugHooks || codeBlock->usesEval();
859 if (shouldCaptureAllOfTheThings)
860 moduleProgramNode->varDeclarations().markAllVariablesAsCaptured();
862 auto captures = [&] (UniquedStringImpl* uid) -> bool {
863 return moduleProgramNode->captures(uid);
865 auto lookUpVarKind = [&] (UniquedStringImpl* uid, const VariableEnvironmentEntry& entry) -> VarKind {
866 // Allocate the exported variables in the module environment.
867 if (entry.isExported())
868 return VarKind::Scope;
870 // Allocate the namespace variables in the module environment to instantiate
871 // it from the outside of the module code.
872 if (entry.isImportedNamespace())
873 return VarKind::Scope;
875 if (entry.isCaptured())
876 return VarKind::Scope;
877 return captures(uid) ? VarKind::Scope : VarKind::Stack;
882 allocateAndEmitScope();
886 m_calleeRegister.setIndex(CallFrameSlot::callee);
888 m_codeBlock->setNumParameters(1); // Allocate space for "this"
890 // Now declare all variables.
892 createVariable(m_vm->propertyNames->builtinNames().metaPrivateName(), VarKind::Scope, moduleEnvironmentSymbolTable, VerifyExisting);
894 for (auto& entry : moduleProgramNode->varDeclarations()) {
895 ASSERT(!entry.value.isLet() && !entry.value.isConst());
896 if (!entry.value.isVar()) // This is either a parameter or callee.
898 // Imported bindings are not allocated in the module environment as usual variables' way.
899 // These references remain the "Dynamic" in the unlinked code block. Later, when linking
900 // the code block, we resolve the reference to the "ModuleVar".
901 if (entry.value.isImported() && !entry.value.isImportedNamespace())
903 createVariable(Identifier::fromUid(m_vm, entry.key.get()), lookUpVarKind(entry.key.get(), entry.value), moduleEnvironmentSymbolTable, IgnoreExisting);
906 VariableEnvironment& lexicalVariables = moduleProgramNode->lexicalVariables();
907 instantiateLexicalVariables(lexicalVariables, moduleEnvironmentSymbolTable, ScopeRegisterType::Block, lookUpVarKind);
909 // We keep the symbol table in the constant pool.
910 RegisterID* constantSymbolTable = nullptr;
911 if (vm.typeProfiler())
912 constantSymbolTable = addConstantValue(moduleEnvironmentSymbolTable);
914 constantSymbolTable = addConstantValue(moduleEnvironmentSymbolTable->cloneScopePart(*m_vm));
916 pushTDZVariables(lexicalVariables, TDZCheckOptimization::Optimize, TDZRequirement::UnderTDZ);
917 bool isWithScope = false;
918 m_lexicalScopeStack.append({ moduleEnvironmentSymbolTable, m_topMostScope, isWithScope, constantSymbolTable->index() });
919 emitPrefillStackTDZVariables(lexicalVariables, moduleEnvironmentSymbolTable);
921 // makeFunction assumes that there's correct TDZ stack entries.
922 // So it should be called after putting our lexical environment to the TDZ stack correctly.
924 for (FunctionMetadataNode* function : moduleProgramNode->functionStack()) {
925 const auto& iterator = moduleProgramNode->varDeclarations().find(function->ident().impl());
926 RELEASE_ASSERT(iterator != moduleProgramNode->varDeclarations().end());
927 RELEASE_ASSERT(!iterator->value.isImported());
929 VarKind varKind = lookUpVarKind(iterator->key.get(), iterator->value);
930 if (varKind == VarKind::Scope) {
931 // http://www.ecma-international.org/ecma-262/6.0/#sec-moduledeclarationinstantiation
932 // Section 15.2.1.16.4, step 16-a-iv-1.
933 // All heap allocated function declarations should be instantiated when the module environment
934 // is created. They include the exported function declarations and not-exported-but-heap-allocated
935 // function declarations. This is required because exported function should be instantiated before
936 // executing the any module in the dependency graph. This enables the modules to link the imported
937 // bindings before executing the any module code.
939 // And since function declarations are instantiated before executing the module body code, the spec
940 // allows the functions inside the module to be executed before its module body is executed under
941 // the circular dependencies. The following is the example.
943 // Module A (executed first):
944 // import { b } from "B";
945 // // Here, the module "B" is not executed yet, but the function declaration is already instantiated.
946 // // So we can call the function exported from "B".
949 // export function a() {
952 // Module B (executed second):
953 // import { a } from "A";
955 // export function b() {
959 // // c is not exported, but since it is referenced from the b, we should instantiate it before
960 // // executing the "B" module code.
965 // Module EntryPoint (executed last):
969 m_codeBlock->addFunctionDecl(makeFunction(function));
971 // Stack allocated functions can be allocated when executing the module's body.
972 m_functionsToInitialize.append(std::make_pair(function, NormalFunctionVariable));
976 // Remember the constant register offset to the top-most symbol table. This symbol table will be
977 // cloned in the code block linking. After that, to create the module environment, we retrieve
978 // the cloned symbol table from the linked code block by using this offset.
979 codeBlock->setModuleEnvironmentSymbolTableConstantRegisterOffset(constantSymbolTable->index());
982 BytecodeGenerator::~BytecodeGenerator()
986 void BytecodeGenerator::initializeDefaultParameterValuesAndSetupFunctionScopeStack(
987 FunctionParameters& parameters, bool isSimpleParameterList, FunctionNode* functionNode, SymbolTable* functionSymbolTable,
988 int symbolTableConstantIndex, const std::function<bool (UniquedStringImpl*)>& captures, bool shouldCreateArgumentsVariableInParameterScope)
990 Vector<std::pair<Identifier, RefPtr<RegisterID>>> valuesToMoveIntoVars;
991 ASSERT(!(isSimpleParameterList && shouldCreateArgumentsVariableInParameterScope));
992 if (!isSimpleParameterList) {
993 // Refer to the ES6 spec section 9.2.12: http://www.ecma-international.org/ecma-262/6.0/index.html#sec-functiondeclarationinstantiation
994 // This implements step 21.
995 VariableEnvironment environment;
996 Vector<Identifier> allParameterNames;
997 for (unsigned i = 0; i < parameters.size(); i++)
998 parameters.at(i).first->collectBoundIdentifiers(allParameterNames);
999 if (shouldCreateArgumentsVariableInParameterScope)
1000 allParameterNames.append(propertyNames().arguments);
1001 IdentifierSet parameterSet;
1002 for (auto& ident : allParameterNames) {
1003 parameterSet.add(ident.impl());
1004 auto addResult = environment.add(ident);
1005 addResult.iterator->value.setIsLet(); // When we have default parameter expressions, parameters act like "let" variables.
1006 if (captures(ident.impl()))
1007 addResult.iterator->value.setIsCaptured();
1009 // This implements step 25 of section 9.2.12.
1010 pushLexicalScopeInternal(environment, TDZCheckOptimization::Optimize, NestedScopeType::IsNotNested, nullptr, TDZRequirement::UnderTDZ, ScopeType::LetConstScope, ScopeRegisterType::Block);
1012 if (shouldCreateArgumentsVariableInParameterScope) {
1013 Variable argumentsVariable = variable(propertyNames().arguments);
1014 initializeVariable(argumentsVariable, m_argumentsRegister);
1015 liftTDZCheckIfPossible(argumentsVariable);
1018 RefPtr<RegisterID> temp = newTemporary();
1019 for (unsigned i = 0; i < parameters.size(); i++) {
1020 std::pair<DestructuringPatternNode*, ExpressionNode*> parameter = parameters.at(i);
1021 if (parameter.first->isRestParameter())
1023 if ((i + 1) < m_parameters.size())
1024 emitMove(temp.get(), &m_parameters[i + 1]);
1026 emitGetArgument(temp.get(), i);
1027 if (parameter.second) {
1028 RefPtr<RegisterID> condition = emitIsUndefined(newTemporary(), temp.get());
1029 Ref<Label> skipDefaultParameterBecauseNotUndefined = newLabel();
1030 emitJumpIfFalse(condition.get(), skipDefaultParameterBecauseNotUndefined.get());
1031 emitNode(temp.get(), parameter.second);
1032 emitLabel(skipDefaultParameterBecauseNotUndefined.get());
1035 parameter.first->bindValue(*this, temp.get());
1038 // Final act of weirdness for default parameters. If a "var" also
1039 // has the same name as a parameter, it should start out as the
1040 // value of that parameter. Note, though, that they will be distinct
1042 // This is step 28 of section 9.2.12.
1043 for (auto& entry : functionNode->varDeclarations()) {
1044 if (!entry.value.isVar()) // This is either a parameter or callee.
1047 if (parameterSet.contains(entry.key)) {
1048 Identifier ident = Identifier::fromUid(m_vm, entry.key.get());
1049 Variable var = variable(ident);
1050 RegisterID* scope = emitResolveScope(nullptr, var);
1051 RefPtr<RegisterID> value = emitGetFromScope(newTemporary(), scope, var, DoNotThrowIfNotFound);
1052 valuesToMoveIntoVars.append(std::make_pair(ident, value));
1056 // Functions with default parameter expressions must have a separate environment
1057 // record for parameters and "var"s. The "var" environment record must have the
1058 // parameter environment record as its parent.
1059 // See step 28 of section 9.2.12.
1060 bool hasCapturedVariables = !!m_lexicalEnvironmentRegister;
1061 initializeVarLexicalEnvironment(symbolTableConstantIndex, functionSymbolTable, hasCapturedVariables);
1064 // This completes step 28 of section 9.2.12.
1065 for (unsigned i = 0; i < valuesToMoveIntoVars.size(); i++) {
1066 ASSERT(!isSimpleParameterList);
1067 Variable var = variable(valuesToMoveIntoVars[i].first);
1068 RegisterID* scope = emitResolveScope(nullptr, var);
1069 emitPutToScope(scope, var, valuesToMoveIntoVars[i].second.get(), DoNotThrowIfNotFound, InitializationMode::NotInitialization);
1073 bool BytecodeGenerator::needsDerivedConstructorInArrowFunctionLexicalEnvironment()
1075 ASSERT(m_codeBlock->isClassContext() || !(isConstructor() && constructorKind() == ConstructorKind::Extends));
1076 return m_codeBlock->isClassContext() && isSuperUsedInInnerArrowFunction();
1079 void BytecodeGenerator::initializeArrowFunctionContextScopeIfNeeded(SymbolTable* functionSymbolTable, bool canReuseLexicalEnvironment)
1081 ASSERT(!m_arrowFunctionContextLexicalEnvironmentRegister);
1083 if (canReuseLexicalEnvironment && m_lexicalEnvironmentRegister) {
1084 RELEASE_ASSERT(!m_codeBlock->isArrowFunction());
1085 RELEASE_ASSERT(functionSymbolTable);
1087 m_arrowFunctionContextLexicalEnvironmentRegister = m_lexicalEnvironmentRegister;
1091 if (isThisUsedInInnerArrowFunction()) {
1092 offset = functionSymbolTable->takeNextScopeOffset(NoLockingNecessary);
1093 functionSymbolTable->set(NoLockingNecessary, propertyNames().thisIdentifier.impl(), SymbolTableEntry(VarOffset(offset)));
1096 if (m_codeType == FunctionCode && isNewTargetUsedInInnerArrowFunction()) {
1097 offset = functionSymbolTable->takeNextScopeOffset();
1098 functionSymbolTable->set(NoLockingNecessary, propertyNames().builtinNames().newTargetLocalPrivateName().impl(), SymbolTableEntry(VarOffset(offset)));
1101 if (needsDerivedConstructorInArrowFunctionLexicalEnvironment()) {
1102 offset = functionSymbolTable->takeNextScopeOffset(NoLockingNecessary);
1103 functionSymbolTable->set(NoLockingNecessary, propertyNames().builtinNames().derivedConstructorPrivateName().impl(), SymbolTableEntry(VarOffset(offset)));
1109 VariableEnvironment environment;
1111 if (isThisUsedInInnerArrowFunction()) {
1112 auto addResult = environment.add(propertyNames().thisIdentifier);
1113 addResult.iterator->value.setIsCaptured();
1114 addResult.iterator->value.setIsLet();
1117 if (m_codeType == FunctionCode && isNewTargetUsedInInnerArrowFunction()) {
1118 auto addTarget = environment.add(propertyNames().builtinNames().newTargetLocalPrivateName());
1119 addTarget.iterator->value.setIsCaptured();
1120 addTarget.iterator->value.setIsLet();
1123 if (needsDerivedConstructorInArrowFunctionLexicalEnvironment()) {
1124 auto derivedConstructor = environment.add(propertyNames().builtinNames().derivedConstructorPrivateName());
1125 derivedConstructor.iterator->value.setIsCaptured();
1126 derivedConstructor.iterator->value.setIsLet();
1129 if (environment.size() > 0) {
1130 size_t size = m_lexicalScopeStack.size();
1131 pushLexicalScopeInternal(environment, TDZCheckOptimization::Optimize, NestedScopeType::IsNotNested, nullptr, TDZRequirement::UnderTDZ, ScopeType::LetConstScope, ScopeRegisterType::Block);
1133 ASSERT_UNUSED(size, m_lexicalScopeStack.size() == size + 1);
1135 m_arrowFunctionContextLexicalEnvironmentRegister = m_lexicalScopeStack.last().m_scope;
1139 RegisterID* BytecodeGenerator::initializeNextParameter()
1141 VirtualRegister reg = virtualRegisterForArgument(m_codeBlock->numParameters());
1142 m_parameters.grow(m_parameters.size() + 1);
1143 auto& parameter = registerFor(reg);
1144 parameter.setIndex(reg.offset());
1145 m_codeBlock->addParameter();
1149 void BytecodeGenerator::initializeParameters(FunctionParameters& parameters)
1151 // Make sure the code block knows about all of our parameters, and make sure that parameters
1152 // needing destructuring are noted.
1153 m_thisRegister.setIndex(initializeNextParameter()->index()); // this
1155 bool nonSimpleArguments = false;
1156 for (unsigned i = 0; i < parameters.size(); ++i) {
1157 auto parameter = parameters.at(i);
1158 auto pattern = parameter.first;
1159 if (pattern->isRestParameter()) {
1160 RELEASE_ASSERT(!m_restParameter);
1161 m_restParameter = static_cast<RestParameterNode*>(pattern);
1162 nonSimpleArguments = true;
1165 if (parameter.second) {
1166 nonSimpleArguments = true;
1169 if (!nonSimpleArguments)
1170 initializeNextParameter();
1174 void BytecodeGenerator::initializeVarLexicalEnvironment(int symbolTableConstantIndex, SymbolTable* functionSymbolTable, bool hasCapturedVariables)
1176 if (hasCapturedVariables) {
1177 RELEASE_ASSERT(m_lexicalEnvironmentRegister);
1178 emitOpcode(op_create_lexical_environment);
1179 instructions().append(m_lexicalEnvironmentRegister->index());
1180 instructions().append(scopeRegister()->index());
1181 instructions().append(symbolTableConstantIndex);
1182 instructions().append(addConstantValue(jsUndefined())->index());
1185 instructions().append(scopeRegister()->index());
1186 instructions().append(m_lexicalEnvironmentRegister->index());
1188 pushLocalControlFlowScope();
1190 bool isWithScope = false;
1191 m_lexicalScopeStack.append({ functionSymbolTable, m_lexicalEnvironmentRegister, isWithScope, symbolTableConstantIndex });
1192 m_varScopeLexicalScopeStackIndex = m_lexicalScopeStack.size() - 1;
1195 UniquedStringImpl* BytecodeGenerator::visibleNameForParameter(DestructuringPatternNode* pattern)
1197 if (pattern->isBindingNode()) {
1198 const Identifier& ident = static_cast<const BindingNode*>(pattern)->boundProperty();
1199 if (!m_functions.contains(ident.impl()))
1200 return ident.impl();
1205 RegisterID* BytecodeGenerator::newRegister()
1207 m_calleeLocals.append(virtualRegisterForLocal(m_calleeLocals.size()));
1208 int numCalleeLocals = max<int>(m_codeBlock->m_numCalleeLocals, m_calleeLocals.size());
1209 numCalleeLocals = WTF::roundUpToMultipleOf(stackAlignmentRegisters(), numCalleeLocals);
1210 m_codeBlock->m_numCalleeLocals = numCalleeLocals;
1211 return &m_calleeLocals.last();
1214 void BytecodeGenerator::reclaimFreeRegisters()
1216 shrinkToFit(m_calleeLocals);
1219 RegisterID* BytecodeGenerator::newBlockScopeVariable()
1221 reclaimFreeRegisters();
1223 return newRegister();
1226 RegisterID* BytecodeGenerator::newTemporary()
1228 reclaimFreeRegisters();
1230 RegisterID* result = newRegister();
1231 result->setTemporary();
1235 Ref<LabelScope> BytecodeGenerator::newLabelScope(LabelScope::Type type, const Identifier* name)
1237 shrinkToFit(m_labelScopes);
1239 // Allocate new label scope.
1240 m_labelScopes.append(type, name, labelScopeDepth(), newLabel(), type == LabelScope::Loop ? RefPtr<Label>(newLabel()) : RefPtr<Label>()); // Only loops have continue targets.
1241 return m_labelScopes.last();
1244 Ref<Label> BytecodeGenerator::newLabel()
1246 shrinkToFit(m_labels);
1248 // Allocate new label ID.
1250 return m_labels.last();
1253 Ref<Label> BytecodeGenerator::newEmittedLabel()
1255 Ref<Label> label = newLabel();
1256 emitLabel(label.get());
1260 void BytecodeGenerator::emitLabel(Label& l0)
1262 unsigned newLabelIndex = instructions().size();
1263 l0.setLocation(*this, newLabelIndex);
1265 if (m_codeBlock->numberOfJumpTargets()) {
1266 unsigned lastLabelIndex = m_codeBlock->lastJumpTarget();
1267 ASSERT(lastLabelIndex <= newLabelIndex);
1268 if (newLabelIndex == lastLabelIndex) {
1269 // Peephole optimizations have already been disabled by emitting the last label
1274 m_codeBlock->addJumpTarget(newLabelIndex);
1276 // This disables peephole optimizations when an instruction is a jump target
1277 m_lastOpcodeID = op_end;
1280 void BytecodeGenerator::emitOpcode(OpcodeID opcodeID)
1283 size_t opcodePosition = instructions().size();
1284 ASSERT(opcodePosition - m_lastOpcodePosition == opcodeLength(m_lastOpcodeID) || m_lastOpcodeID == op_end);
1285 m_lastOpcodePosition = opcodePosition;
1287 instructions().append(opcodeID);
1288 m_lastOpcodeID = opcodeID;
1291 UnlinkedArrayProfile BytecodeGenerator::newArrayProfile()
1293 return m_codeBlock->addArrayProfile();
1296 UnlinkedArrayAllocationProfile BytecodeGenerator::newArrayAllocationProfile()
1298 return m_codeBlock->addArrayAllocationProfile();
1301 UnlinkedObjectAllocationProfile BytecodeGenerator::newObjectAllocationProfile()
1303 return m_codeBlock->addObjectAllocationProfile();
1306 UnlinkedValueProfile BytecodeGenerator::emitProfiledOpcode(OpcodeID opcodeID)
1308 UnlinkedValueProfile result = m_codeBlock->addValueProfile();
1309 emitOpcode(opcodeID);
1313 void BytecodeGenerator::emitEnter()
1315 emitOpcode(op_enter);
1318 void BytecodeGenerator::emitLoopHint()
1320 emitOpcode(op_loop_hint);
1324 void BytecodeGenerator::emitCheckTraps()
1326 emitOpcode(op_check_traps);
1329 void BytecodeGenerator::retrieveLastBinaryOp(int& dstIndex, int& src1Index, int& src2Index)
1331 ASSERT(instructions().size() >= 4);
1332 size_t size = instructions().size();
1333 dstIndex = instructions().at(size - 3).u.operand;
1334 src1Index = instructions().at(size - 2).u.operand;
1335 src2Index = instructions().at(size - 1).u.operand;
1338 void BytecodeGenerator::retrieveLastUnaryOp(int& dstIndex, int& srcIndex)
1340 ASSERT(instructions().size() >= 3);
1341 size_t size = instructions().size();
1342 dstIndex = instructions().at(size - 2).u.operand;
1343 srcIndex = instructions().at(size - 1).u.operand;
1346 void ALWAYS_INLINE BytecodeGenerator::rewindBinaryOp()
1348 ASSERT(instructions().size() >= 4);
1349 instructions().shrink(instructions().size() - 4);
1350 m_lastOpcodeID = op_end;
1353 void ALWAYS_INLINE BytecodeGenerator::rewindUnaryOp()
1355 ASSERT(instructions().size() >= 3);
1356 instructions().shrink(instructions().size() - 3);
1357 m_lastOpcodeID = op_end;
1360 void BytecodeGenerator::emitJump(Label& target)
1362 size_t begin = instructions().size();
1364 instructions().append(target.bind(begin, instructions().size()));
1367 void BytecodeGenerator::emitJumpIfTrue(RegisterID* cond, Label& target)
1369 auto fuseCompareAndJump = [&] (OpcodeID jumpID) {
1374 retrieveLastBinaryOp(dstIndex, src1Index, src2Index);
1376 if (cond->index() == dstIndex && cond->isTemporary() && !cond->refCount()) {
1379 size_t begin = instructions().size();
1381 instructions().append(src1Index);
1382 instructions().append(src2Index);
1383 instructions().append(target.bind(begin, instructions().size()));
1389 if (m_lastOpcodeID == op_less) {
1390 if (fuseCompareAndJump(op_jless))
1392 } else if (m_lastOpcodeID == op_lesseq) {
1393 if (fuseCompareAndJump(op_jlesseq))
1395 } else if (m_lastOpcodeID == op_greater) {
1396 if (fuseCompareAndJump(op_jgreater))
1398 } else if (m_lastOpcodeID == op_greatereq) {
1399 if (fuseCompareAndJump(op_jgreatereq))
1401 } else if (m_lastOpcodeID == op_below) {
1402 if (fuseCompareAndJump(op_jbelow))
1404 } else if (m_lastOpcodeID == op_beloweq) {
1405 if (fuseCompareAndJump(op_jbeloweq))
1407 } else if (m_lastOpcodeID == op_eq_null && target.isForward()) {
1411 retrieveLastUnaryOp(dstIndex, srcIndex);
1413 if (cond->index() == dstIndex && cond->isTemporary() && !cond->refCount()) {
1416 size_t begin = instructions().size();
1417 emitOpcode(op_jeq_null);
1418 instructions().append(srcIndex);
1419 instructions().append(target.bind(begin, instructions().size()));
1422 } else if (m_lastOpcodeID == op_neq_null && target.isForward()) {
1426 retrieveLastUnaryOp(dstIndex, srcIndex);
1428 if (cond->index() == dstIndex && cond->isTemporary() && !cond->refCount()) {
1431 size_t begin = instructions().size();
1432 emitOpcode(op_jneq_null);
1433 instructions().append(srcIndex);
1434 instructions().append(target.bind(begin, instructions().size()));
1439 size_t begin = instructions().size();
1441 emitOpcode(op_jtrue);
1442 instructions().append(cond->index());
1443 instructions().append(target.bind(begin, instructions().size()));
1446 void BytecodeGenerator::emitJumpIfFalse(RegisterID* cond, Label& target)
1448 auto fuseCompareAndJump = [&] (OpcodeID jumpID, bool replaceOperands) {
1453 retrieveLastBinaryOp(dstIndex, src1Index, src2Index);
1455 if (cond->index() == dstIndex && cond->isTemporary() && !cond->refCount()) {
1458 size_t begin = instructions().size();
1460 // Since op_below and op_beloweq only accepts Int32, replacing operands is not observable to users.
1461 if (replaceOperands)
1462 std::swap(src1Index, src2Index);
1463 instructions().append(src1Index);
1464 instructions().append(src2Index);
1465 instructions().append(target.bind(begin, instructions().size()));
1471 if (m_lastOpcodeID == op_less && target.isForward()) {
1472 if (fuseCompareAndJump(op_jnless, false))
1474 } else if (m_lastOpcodeID == op_lesseq && target.isForward()) {
1475 if (fuseCompareAndJump(op_jnlesseq, false))
1477 } else if (m_lastOpcodeID == op_greater && target.isForward()) {
1478 if (fuseCompareAndJump(op_jngreater, false))
1480 } else if (m_lastOpcodeID == op_greatereq && target.isForward()) {
1481 if (fuseCompareAndJump(op_jngreatereq, false))
1483 } else if (m_lastOpcodeID == op_below && target.isForward()) {
1484 if (fuseCompareAndJump(op_jbeloweq, true))
1486 } else if (m_lastOpcodeID == op_beloweq && target.isForward()) {
1487 if (fuseCompareAndJump(op_jbelow, true))
1489 } else if (m_lastOpcodeID == op_not) {
1493 retrieveLastUnaryOp(dstIndex, srcIndex);
1495 if (cond->index() == dstIndex && cond->isTemporary() && !cond->refCount()) {
1498 size_t begin = instructions().size();
1499 emitOpcode(op_jtrue);
1500 instructions().append(srcIndex);
1501 instructions().append(target.bind(begin, instructions().size()));
1504 } else if (m_lastOpcodeID == op_eq_null && target.isForward()) {
1508 retrieveLastUnaryOp(dstIndex, srcIndex);
1510 if (cond->index() == dstIndex && cond->isTemporary() && !cond->refCount()) {
1513 size_t begin = instructions().size();
1514 emitOpcode(op_jneq_null);
1515 instructions().append(srcIndex);
1516 instructions().append(target.bind(begin, instructions().size()));
1519 } else if (m_lastOpcodeID == op_neq_null && target.isForward()) {
1523 retrieveLastUnaryOp(dstIndex, srcIndex);
1525 if (cond->index() == dstIndex && cond->isTemporary() && !cond->refCount()) {
1528 size_t begin = instructions().size();
1529 emitOpcode(op_jeq_null);
1530 instructions().append(srcIndex);
1531 instructions().append(target.bind(begin, instructions().size()));
1536 size_t begin = instructions().size();
1537 emitOpcode(op_jfalse);
1538 instructions().append(cond->index());
1539 instructions().append(target.bind(begin, instructions().size()));
1542 void BytecodeGenerator::emitJumpIfNotFunctionCall(RegisterID* cond, Label& target)
1544 size_t begin = instructions().size();
1546 emitOpcode(op_jneq_ptr);
1547 instructions().append(cond->index());
1548 instructions().append(Special::CallFunction);
1549 instructions().append(target.bind(begin, instructions().size()));
1550 instructions().append(0);
1553 void BytecodeGenerator::emitJumpIfNotFunctionApply(RegisterID* cond, Label& target)
1555 size_t begin = instructions().size();
1557 emitOpcode(op_jneq_ptr);
1558 instructions().append(cond->index());
1559 instructions().append(Special::ApplyFunction);
1560 instructions().append(target.bind(begin, instructions().size()));
1561 instructions().append(0);
1564 bool BytecodeGenerator::hasConstant(const Identifier& ident) const
1566 UniquedStringImpl* rep = ident.impl();
1567 return m_identifierMap.contains(rep);
1570 unsigned BytecodeGenerator::addConstant(const Identifier& ident)
1572 UniquedStringImpl* rep = ident.impl();
1573 IdentifierMap::AddResult result = m_identifierMap.add(rep, m_codeBlock->numberOfIdentifiers());
1574 if (result.isNewEntry)
1575 m_codeBlock->addIdentifier(ident);
1577 return result.iterator->value;
1580 // We can't hash JSValue(), so we use a dedicated data member to cache it.
1581 RegisterID* BytecodeGenerator::addConstantEmptyValue()
1583 if (!m_emptyValueRegister) {
1584 int index = addConstantIndex();
1585 m_codeBlock->addConstant(JSValue());
1586 m_emptyValueRegister = &m_constantPoolRegisters[index];
1589 return m_emptyValueRegister;
1592 RegisterID* BytecodeGenerator::addConstantValue(JSValue v, SourceCodeRepresentation sourceCodeRepresentation)
1595 return addConstantEmptyValue();
1597 int index = m_nextConstantOffset;
1599 if (sourceCodeRepresentation == SourceCodeRepresentation::Double && v.isInt32())
1600 v = jsDoubleNumber(v.asNumber());
1601 EncodedJSValueWithRepresentation valueMapKey { JSValue::encode(v), sourceCodeRepresentation };
1602 JSValueMap::AddResult result = m_jsValueMap.add(valueMapKey, m_nextConstantOffset);
1603 if (result.isNewEntry) {
1605 m_codeBlock->addConstant(v, sourceCodeRepresentation);
1607 index = result.iterator->value;
1608 return &m_constantPoolRegisters[index];
1611 RegisterID* BytecodeGenerator::emitMoveLinkTimeConstant(RegisterID* dst, LinkTimeConstant type)
1613 unsigned constantIndex = static_cast<unsigned>(type);
1614 if (!m_linkTimeConstantRegisters[constantIndex]) {
1615 int index = addConstantIndex();
1616 m_codeBlock->addConstant(type);
1617 m_linkTimeConstantRegisters[constantIndex] = &m_constantPoolRegisters[index];
1621 return m_linkTimeConstantRegisters[constantIndex];
1624 instructions().append(dst->index());
1625 instructions().append(m_linkTimeConstantRegisters[constantIndex]->index());
1630 unsigned BytecodeGenerator::addRegExp(RegExp* r)
1632 return m_codeBlock->addRegExp(r);
1635 RegisterID* BytecodeGenerator::emitMoveEmptyValue(RegisterID* dst)
1637 RefPtr<RegisterID> emptyValue = addConstantEmptyValue();
1640 instructions().append(dst->index());
1641 instructions().append(emptyValue->index());
1645 RegisterID* BytecodeGenerator::emitMove(RegisterID* dst, RegisterID* src)
1647 ASSERT(src != m_emptyValueRegister);
1649 m_staticPropertyAnalyzer.mov(dst->index(), src->index());
1651 instructions().append(dst->index());
1652 instructions().append(src->index());
1657 RegisterID* BytecodeGenerator::emitUnaryOp(OpcodeID opcodeID, RegisterID* dst, RegisterID* src)
1659 ASSERT_WITH_MESSAGE(op_to_number != opcodeID, "op_to_number has a Value Profile.");
1660 ASSERT_WITH_MESSAGE(op_negate != opcodeID, "op_negate has an Arith Profile.");
1661 emitOpcode(opcodeID);
1662 instructions().append(dst->index());
1663 instructions().append(src->index());
1668 RegisterID* BytecodeGenerator::emitUnaryOp(OpcodeID opcodeID, RegisterID* dst, RegisterID* src, OperandTypes types)
1670 ASSERT_WITH_MESSAGE(op_to_number != opcodeID, "op_to_number has a Value Profile.");
1671 emitOpcode(opcodeID);
1672 instructions().append(dst->index());
1673 instructions().append(src->index());
1675 if (opcodeID == op_negate)
1676 instructions().append(ArithProfile(types.first()).bits());
1680 RegisterID* BytecodeGenerator::emitUnaryOpProfiled(OpcodeID opcodeID, RegisterID* dst, RegisterID* src)
1682 UnlinkedValueProfile profile = emitProfiledOpcode(opcodeID);
1683 instructions().append(dst->index());
1684 instructions().append(src->index());
1685 instructions().append(profile);
1689 RegisterID* BytecodeGenerator::emitInc(RegisterID* srcDst)
1692 instructions().append(srcDst->index());
1696 RegisterID* BytecodeGenerator::emitDec(RegisterID* srcDst)
1699 instructions().append(srcDst->index());
1703 RegisterID* BytecodeGenerator::emitBinaryOp(OpcodeID opcodeID, RegisterID* dst, RegisterID* src1, RegisterID* src2, OperandTypes types)
1705 emitOpcode(opcodeID);
1706 instructions().append(dst->index());
1707 instructions().append(src1->index());
1708 instructions().append(src2->index());
1710 if (opcodeID == op_bitor || opcodeID == op_bitand || opcodeID == op_bitxor ||
1711 opcodeID == op_add || opcodeID == op_mul || opcodeID == op_sub || opcodeID == op_div)
1712 instructions().append(ArithProfile(types.first(), types.second()).bits());
1717 RegisterID* BytecodeGenerator::emitEqualityOp(OpcodeID opcodeID, RegisterID* dst, RegisterID* src1, RegisterID* src2)
1719 if (m_lastOpcodeID == op_typeof) {
1723 retrieveLastUnaryOp(dstIndex, srcIndex);
1725 if (src1->index() == dstIndex
1726 && src1->isTemporary()
1727 && m_codeBlock->isConstantRegisterIndex(src2->index())
1728 && m_codeBlock->constantRegister(src2->index()).get().isString()) {
1729 const String& value = asString(m_codeBlock->constantRegister(src2->index()).get())->tryGetValue();
1730 if (value == "undefined") {
1732 emitOpcode(op_is_undefined);
1733 instructions().append(dst->index());
1734 instructions().append(srcIndex);
1737 if (value == "boolean") {
1739 emitOpcode(op_is_boolean);
1740 instructions().append(dst->index());
1741 instructions().append(srcIndex);
1744 if (value == "number") {
1746 emitOpcode(op_is_number);
1747 instructions().append(dst->index());
1748 instructions().append(srcIndex);
1751 if (value == "string") {
1753 emitOpcode(op_is_cell_with_type);
1754 instructions().append(dst->index());
1755 instructions().append(srcIndex);
1756 instructions().append(StringType);
1759 if (value == "symbol") {
1761 emitOpcode(op_is_cell_with_type);
1762 instructions().append(dst->index());
1763 instructions().append(srcIndex);
1764 instructions().append(SymbolType);
1767 if (value == "object") {
1769 emitOpcode(op_is_object_or_null);
1770 instructions().append(dst->index());
1771 instructions().append(srcIndex);
1774 if (value == "function") {
1776 emitOpcode(op_is_function);
1777 instructions().append(dst->index());
1778 instructions().append(srcIndex);
1784 emitOpcode(opcodeID);
1785 instructions().append(dst->index());
1786 instructions().append(src1->index());
1787 instructions().append(src2->index());
1791 void BytecodeGenerator::emitTypeProfilerExpressionInfo(const JSTextPosition& startDivot, const JSTextPosition& endDivot)
1793 ASSERT(vm()->typeProfiler());
1795 unsigned start = startDivot.offset; // Ranges are inclusive of their endpoints, AND 0 indexed.
1796 unsigned end = endDivot.offset - 1; // End Ranges already go one past the inclusive range, so subtract 1.
1797 unsigned instructionOffset = instructions().size() - 1;
1798 m_codeBlock->addTypeProfilerExpressionInfo(instructionOffset, start, end);
1801 void BytecodeGenerator::emitProfileType(RegisterID* registerToProfile, ProfileTypeBytecodeFlag flag)
1803 if (!vm()->typeProfiler())
1806 if (!registerToProfile)
1809 emitOpcode(op_profile_type);
1810 instructions().append(registerToProfile->index());
1811 instructions().append(0);
1812 instructions().append(flag);
1813 instructions().append(0);
1814 instructions().append(resolveType());
1816 // Don't emit expression info for this version of profile type. This generally means
1817 // we're profiling information for something that isn't in the actual text of a JavaScript
1818 // program. For example, implicit return undefined from a function call.
1821 void BytecodeGenerator::emitProfileType(RegisterID* registerToProfile, const JSTextPosition& startDivot, const JSTextPosition& endDivot)
1823 emitProfileType(registerToProfile, ProfileTypeBytecodeDoesNotHaveGlobalID, startDivot, endDivot);
1826 void BytecodeGenerator::emitProfileType(RegisterID* registerToProfile, ProfileTypeBytecodeFlag flag, const JSTextPosition& startDivot, const JSTextPosition& endDivot)
1828 if (!vm()->typeProfiler())
1831 if (!registerToProfile)
1834 // The format of this instruction is: op_profile_type regToProfile, TypeLocation*, flag, identifier?, resolveType?
1835 emitOpcode(op_profile_type);
1836 instructions().append(registerToProfile->index());
1837 instructions().append(0);
1838 instructions().append(flag);
1839 instructions().append(0);
1840 instructions().append(resolveType());
1842 emitTypeProfilerExpressionInfo(startDivot, endDivot);
1845 void BytecodeGenerator::emitProfileType(RegisterID* registerToProfile, const Variable& var, const JSTextPosition& startDivot, const JSTextPosition& endDivot)
1847 if (!vm()->typeProfiler())
1850 if (!registerToProfile)
1853 ProfileTypeBytecodeFlag flag;
1854 int symbolTableOrScopeDepth;
1855 if (var.local() || var.offset().isScope()) {
1856 flag = ProfileTypeBytecodeLocallyResolved;
1857 ASSERT(var.symbolTableConstantIndex());
1858 symbolTableOrScopeDepth = var.symbolTableConstantIndex();
1860 flag = ProfileTypeBytecodeClosureVar;
1861 symbolTableOrScopeDepth = localScopeDepth();
1864 // The format of this instruction is: op_profile_type regToProfile, TypeLocation*, flag, identifier?, resolveType?
1865 emitOpcode(op_profile_type);
1866 instructions().append(registerToProfile->index());
1867 instructions().append(symbolTableOrScopeDepth);
1868 instructions().append(flag);
1869 instructions().append(addConstant(var.ident()));
1870 instructions().append(resolveType());
1872 emitTypeProfilerExpressionInfo(startDivot, endDivot);
1875 void BytecodeGenerator::emitProfileControlFlow(int textOffset)
1877 if (vm()->controlFlowProfiler()) {
1878 RELEASE_ASSERT(textOffset >= 0);
1879 size_t bytecodeOffset = instructions().size();
1880 m_codeBlock->addOpProfileControlFlowBytecodeOffset(bytecodeOffset);
1882 emitOpcode(op_profile_control_flow);
1883 instructions().append(textOffset);
1887 unsigned BytecodeGenerator::addConstantIndex()
1889 unsigned index = m_nextConstantOffset;
1890 m_constantPoolRegisters.append(FirstConstantRegisterIndex + m_nextConstantOffset);
1891 ++m_nextConstantOffset;
1895 RegisterID* BytecodeGenerator::emitLoad(RegisterID* dst, bool b)
1897 return emitLoad(dst, jsBoolean(b));
1900 RegisterID* BytecodeGenerator::emitLoad(RegisterID* dst, const Identifier& identifier)
1902 ASSERT(!identifier.isSymbol());
1903 JSString*& stringInMap = m_stringMap.add(identifier.impl(), nullptr).iterator->value;
1905 stringInMap = jsOwnedString(vm(), identifier.string());
1907 return emitLoad(dst, JSValue(stringInMap));
1910 RegisterID* BytecodeGenerator::emitLoad(RegisterID* dst, JSValue v, SourceCodeRepresentation sourceCodeRepresentation)
1912 RegisterID* constantID = addConstantValue(v, sourceCodeRepresentation);
1914 return emitMove(dst, constantID);
1918 RegisterID* BytecodeGenerator::emitLoad(RegisterID* dst, IdentifierSet& set)
1920 for (const auto& entry : m_codeBlock->constantIdentifierSets()) {
1921 if (entry.first != set)
1924 return &m_constantPoolRegisters[entry.second];
1927 unsigned index = addConstantIndex();
1928 m_codeBlock->addSetConstant(set);
1929 RegisterID* m_setRegister = &m_constantPoolRegisters[index];
1932 return emitMove(dst, m_setRegister);
1934 return m_setRegister;
1937 RegisterID* BytecodeGenerator::emitLoadGlobalObject(RegisterID* dst)
1939 if (!m_globalObjectRegister) {
1940 int index = addConstantIndex();
1941 m_codeBlock->addConstant(JSValue());
1942 m_globalObjectRegister = &m_constantPoolRegisters[index];
1943 m_codeBlock->setGlobalObjectRegister(VirtualRegister(index));
1946 emitMove(dst, m_globalObjectRegister);
1947 return m_globalObjectRegister;
1950 template<typename LookUpVarKindFunctor>
1951 bool BytecodeGenerator::instantiateLexicalVariables(const VariableEnvironment& lexicalVariables, SymbolTable* symbolTable, ScopeRegisterType scopeRegisterType, LookUpVarKindFunctor lookUpVarKind)
1953 bool hasCapturedVariables = false;
1955 for (auto& entry : lexicalVariables) {
1956 ASSERT(entry.value.isLet() || entry.value.isConst() || entry.value.isFunction());
1957 ASSERT(!entry.value.isVar());
1958 SymbolTableEntry symbolTableEntry = symbolTable->get(NoLockingNecessary, entry.key.get());
1959 ASSERT(symbolTableEntry.isNull());
1961 // Imported bindings which are not the namespace bindings are not allocated
1962 // in the module environment as usual variables' way.
1963 // And since these types of the variables only seen in the module environment,
1964 // other lexical environment need not to take care this.
1965 if (entry.value.isImported() && !entry.value.isImportedNamespace())
1968 VarKind varKind = lookUpVarKind(entry.key.get(), entry.value);
1969 VarOffset varOffset;
1970 if (varKind == VarKind::Scope) {
1971 varOffset = VarOffset(symbolTable->takeNextScopeOffset(NoLockingNecessary));
1972 hasCapturedVariables = true;
1974 ASSERT(varKind == VarKind::Stack);
1976 if (scopeRegisterType == ScopeRegisterType::Block) {
1977 local = newBlockScopeVariable();
1981 varOffset = VarOffset(local->virtualRegister());
1984 SymbolTableEntry newEntry(varOffset, static_cast<unsigned>(entry.value.isConst() ? PropertyAttribute::ReadOnly : PropertyAttribute::None));
1985 symbolTable->add(NoLockingNecessary, entry.key.get(), newEntry);
1988 return hasCapturedVariables;
1991 void BytecodeGenerator::emitPrefillStackTDZVariables(const VariableEnvironment& lexicalVariables, SymbolTable* symbolTable)
1993 // Prefill stack variables with the TDZ empty value.
1994 // Scope variables will be initialized to the TDZ empty value when JSLexicalEnvironment is allocated.
1995 for (auto& entry : lexicalVariables) {
1996 // Imported bindings which are not the namespace bindings are not allocated
1997 // in the module environment as usual variables' way.
1998 // And since these types of the variables only seen in the module environment,
1999 // other lexical environment need not to take care this.
2000 if (entry.value.isImported() && !entry.value.isImportedNamespace())
2003 if (entry.value.isFunction())
2006 SymbolTableEntry symbolTableEntry = symbolTable->get(NoLockingNecessary, entry.key.get());
2007 ASSERT(!symbolTableEntry.isNull());
2008 VarOffset offset = symbolTableEntry.varOffset();
2009 if (offset.isScope())
2012 ASSERT(offset.isStack());
2013 emitMoveEmptyValue(®isterFor(offset.stackOffset()));
2017 void BytecodeGenerator::pushLexicalScope(VariableEnvironmentNode* node, TDZCheckOptimization tdzCheckOptimization, NestedScopeType nestedScopeType, RegisterID** constantSymbolTableResult, bool shouldInitializeBlockScopedFunctions)
2019 VariableEnvironment& environment = node->lexicalVariables();
2020 RegisterID* constantSymbolTableResultTemp = nullptr;
2021 pushLexicalScopeInternal(environment, tdzCheckOptimization, nestedScopeType, &constantSymbolTableResultTemp, TDZRequirement::UnderTDZ, ScopeType::LetConstScope, ScopeRegisterType::Block);
2023 if (shouldInitializeBlockScopedFunctions)
2024 initializeBlockScopedFunctions(environment, node->functionStack(), constantSymbolTableResultTemp);
2026 if (constantSymbolTableResult && constantSymbolTableResultTemp)
2027 *constantSymbolTableResult = constantSymbolTableResultTemp;
2030 void BytecodeGenerator::pushLexicalScopeInternal(VariableEnvironment& environment, TDZCheckOptimization tdzCheckOptimization, NestedScopeType nestedScopeType,
2031 RegisterID** constantSymbolTableResult, TDZRequirement tdzRequirement, ScopeType scopeType, ScopeRegisterType scopeRegisterType)
2033 if (!environment.size())
2036 if (m_shouldEmitDebugHooks)
2037 environment.markAllVariablesAsCaptured();
2039 SymbolTable* symbolTable = SymbolTable::create(*m_vm);
2040 switch (scopeType) {
2041 case ScopeType::CatchScope:
2042 symbolTable->setScopeType(SymbolTable::ScopeType::CatchScope);
2044 case ScopeType::LetConstScope:
2045 symbolTable->setScopeType(SymbolTable::ScopeType::LexicalScope);
2047 case ScopeType::FunctionNameScope:
2048 symbolTable->setScopeType(SymbolTable::ScopeType::FunctionNameScope);
2052 if (nestedScopeType == NestedScopeType::IsNested)
2053 symbolTable->markIsNestedLexicalScope();
2055 auto lookUpVarKind = [] (UniquedStringImpl*, const VariableEnvironmentEntry& entry) -> VarKind {
2056 return entry.isCaptured() ? VarKind::Scope : VarKind::Stack;
2059 bool hasCapturedVariables = instantiateLexicalVariables(environment, symbolTable, scopeRegisterType, lookUpVarKind);
2061 RegisterID* newScope = nullptr;
2062 RegisterID* constantSymbolTable = nullptr;
2063 int symbolTableConstantIndex = 0;
2064 if (vm()->typeProfiler()) {
2065 constantSymbolTable = addConstantValue(symbolTable);
2066 symbolTableConstantIndex = constantSymbolTable->index();
2068 if (hasCapturedVariables) {
2069 if (scopeRegisterType == ScopeRegisterType::Block) {
2070 newScope = newBlockScopeVariable();
2073 newScope = addVar();
2074 if (!constantSymbolTable) {
2075 ASSERT(!vm()->typeProfiler());
2076 constantSymbolTable = addConstantValue(symbolTable->cloneScopePart(*m_vm));
2077 symbolTableConstantIndex = constantSymbolTable->index();
2079 if (constantSymbolTableResult)
2080 *constantSymbolTableResult = constantSymbolTable;
2082 emitOpcode(op_create_lexical_environment);
2083 instructions().append(newScope->index());
2084 instructions().append(scopeRegister()->index());
2085 instructions().append(constantSymbolTable->index());
2086 instructions().append(addConstantValue(tdzRequirement == TDZRequirement::UnderTDZ ? jsTDZValue() : jsUndefined())->index());
2088 emitMove(scopeRegister(), newScope);
2090 pushLocalControlFlowScope();
2093 bool isWithScope = false;
2094 m_lexicalScopeStack.append({ symbolTable, newScope, isWithScope, symbolTableConstantIndex });
2095 pushTDZVariables(environment, tdzCheckOptimization, tdzRequirement);
2097 if (tdzRequirement == TDZRequirement::UnderTDZ)
2098 emitPrefillStackTDZVariables(environment, symbolTable);
2101 void BytecodeGenerator::initializeBlockScopedFunctions(VariableEnvironment& environment, FunctionStack& functionStack, RegisterID* constantSymbolTable)
2104 * We must transform block scoped function declarations in strict mode like so:
2108 * function foo() { ... }
2111 * function baz() { ... }
2119 * let foo = function foo() { ... }
2120 * let baz = function baz() { ... }
2126 * But without the TDZ checks.
2129 if (!environment.size()) {
2130 RELEASE_ASSERT(!functionStack.size());
2134 if (!functionStack.size())
2137 SymbolTable* symbolTable = m_lexicalScopeStack.last().m_symbolTable;
2138 RegisterID* scope = m_lexicalScopeStack.last().m_scope;
2139 RefPtr<RegisterID> temp = newTemporary();
2140 int symbolTableIndex = constantSymbolTable ? constantSymbolTable->index() : 0;
2141 for (FunctionMetadataNode* function : functionStack) {
2142 const Identifier& name = function->ident();
2143 auto iter = environment.find(name.impl());
2144 RELEASE_ASSERT(iter != environment.end());
2145 RELEASE_ASSERT(iter->value.isFunction());
2146 // We purposefully don't hold the symbol table lock around this loop because emitNewFunctionExpressionCommon may GC.
2147 SymbolTableEntry entry = symbolTable->get(NoLockingNecessary, name.impl());
2148 RELEASE_ASSERT(!entry.isNull());
2149 emitNewFunctionExpressionCommon(temp.get(), function);
2150 bool isLexicallyScoped = true;
2151 emitPutToScope(scope, variableForLocalEntry(name, entry, symbolTableIndex, isLexicallyScoped), temp.get(), DoNotThrowIfNotFound, InitializationMode::Initialization);
2155 void BytecodeGenerator::hoistSloppyModeFunctionIfNecessary(const Identifier& functionName)
2157 if (m_scopeNode->hasSloppyModeHoistedFunction(functionName.impl())) {
2158 if (codeType() != EvalCode) {
2159 Variable currentFunctionVariable = variable(functionName);
2160 RefPtr<RegisterID> currentValue;
2161 if (RegisterID* local = currentFunctionVariable.local())
2162 currentValue = local;
2164 RefPtr<RegisterID> scope = emitResolveScope(nullptr, currentFunctionVariable);
2165 currentValue = emitGetFromScope(newTemporary(), scope.get(), currentFunctionVariable, DoNotThrowIfNotFound);
2168 ASSERT(m_varScopeLexicalScopeStackIndex);
2169 ASSERT(*m_varScopeLexicalScopeStackIndex < m_lexicalScopeStack.size());
2170 LexicalScopeStackEntry varScope = m_lexicalScopeStack[*m_varScopeLexicalScopeStackIndex];
2171 SymbolTable* varSymbolTable = varScope.m_symbolTable;
2172 ASSERT(varSymbolTable->scopeType() == SymbolTable::ScopeType::VarScope);
2173 SymbolTableEntry entry = varSymbolTable->get(NoLockingNecessary, functionName.impl());
2174 if (functionName == propertyNames().arguments && entry.isNull()) {
2175 // "arguments" might be put in the parameter scope when we have a non-simple
2176 // parameter list since "arguments" is visible to expressions inside the
2177 // parameter evaluation list.
2179 // function foo(x = arguments) { { function arguments() { } } }
2180 RELEASE_ASSERT(*m_varScopeLexicalScopeStackIndex > 0);
2181 varScope = m_lexicalScopeStack[*m_varScopeLexicalScopeStackIndex - 1];
2182 SymbolTable* parameterSymbolTable = varScope.m_symbolTable;
2183 entry = parameterSymbolTable->get(NoLockingNecessary, functionName.impl());
2185 RELEASE_ASSERT(!entry.isNull());
2186 bool isLexicallyScoped = false;
2187 emitPutToScope(varScope.m_scope, variableForLocalEntry(functionName, entry, varScope.m_symbolTableConstantIndex, isLexicallyScoped), currentValue.get(), DoNotThrowIfNotFound, InitializationMode::NotInitialization);
2189 Variable currentFunctionVariable = variable(functionName);
2190 RefPtr<RegisterID> currentValue;
2191 if (RegisterID* local = currentFunctionVariable.local())
2192 currentValue = local;
2194 RefPtr<RegisterID> scope = emitResolveScope(nullptr, currentFunctionVariable);
2195 currentValue = emitGetFromScope(newTemporary(), scope.get(), currentFunctionVariable, DoNotThrowIfNotFound);
2198 RefPtr<RegisterID> scopeId = emitResolveScopeForHoistingFuncDeclInEval(nullptr, functionName);
2199 RefPtr<RegisterID> checkResult = emitIsUndefined(newTemporary(), scopeId.get());
2201 Ref<Label> isNotVarScopeLabel = newLabel();
2202 emitJumpIfTrue(checkResult.get(), isNotVarScopeLabel.get());
2204 // Put to outer scope
2205 emitPutToScope(scopeId.get(), functionName, currentValue.get(), DoNotThrowIfNotFound, InitializationMode::NotInitialization);
2206 emitLabel(isNotVarScopeLabel.get());
2212 RegisterID* BytecodeGenerator::emitResolveScopeForHoistingFuncDeclInEval(RegisterID* dst, const Identifier& property)
2214 ASSERT(m_codeType == EvalCode);
2216 dst = finalDestination(dst);
2217 emitOpcode(op_resolve_scope_for_hoisting_func_decl_in_eval);
2218 instructions().append(kill(dst));
2219 instructions().append(m_topMostScope->index());
2220 instructions().append(addConstant(property));
2224 void BytecodeGenerator::popLexicalScope(VariableEnvironmentNode* node)
2226 VariableEnvironment& environment = node->lexicalVariables();
2227 popLexicalScopeInternal(environment);
2230 void BytecodeGenerator::popLexicalScopeInternal(VariableEnvironment& environment)
2232 // NOTE: This function only makes sense for scopes that aren't ScopeRegisterType::Var (only function name scope right now is ScopeRegisterType::Var).
2233 // This doesn't make sense for ScopeRegisterType::Var because we deref RegisterIDs here.
2234 if (!environment.size())
2237 if (m_shouldEmitDebugHooks)
2238 environment.markAllVariablesAsCaptured();
2240 auto stackEntry = m_lexicalScopeStack.takeLast();
2241 SymbolTable* symbolTable = stackEntry.m_symbolTable;
2242 bool hasCapturedVariables = false;
2243 for (auto& entry : environment) {
2244 if (entry.value.isCaptured()) {
2245 hasCapturedVariables = true;
2248 SymbolTableEntry symbolTableEntry = symbolTable->get(NoLockingNecessary, entry.key.get());
2249 ASSERT(!symbolTableEntry.isNull());
2250 VarOffset offset = symbolTableEntry.varOffset();
2251 ASSERT(offset.isStack());
2252 RegisterID* local = ®isterFor(offset.stackOffset());
2256 if (hasCapturedVariables) {
2257 RELEASE_ASSERT(stackEntry.m_scope);
2258 emitPopScope(scopeRegister(), stackEntry.m_scope);
2259 popLocalControlFlowScope();
2260 stackEntry.m_scope->deref();
2263 m_TDZStack.removeLast();
2266 void BytecodeGenerator::prepareLexicalScopeForNextForLoopIteration(VariableEnvironmentNode* node, RegisterID* loopSymbolTable)
2268 VariableEnvironment& environment = node->lexicalVariables();
2269 if (!environment.size())
2271 if (m_shouldEmitDebugHooks)
2272 environment.markAllVariablesAsCaptured();
2273 if (!environment.hasCapturedVariables())
2276 RELEASE_ASSERT(loopSymbolTable);
2278 // This function needs to do setup for a for loop's activation if any of
2279 // the for loop's lexically declared variables are captured (that is, variables
2280 // declared in the loop header, not the loop body). This function needs to
2281 // make a copy of the current activation and copy the values from the previous
2282 // activation into the new activation because each iteration of a for loop
2283 // gets a new activation.
2285 auto stackEntry = m_lexicalScopeStack.last();
2286 SymbolTable* symbolTable = stackEntry.m_symbolTable;
2287 RegisterID* loopScope = stackEntry.m_scope;
2288 ASSERT(symbolTable->scopeSize());
2290 Vector<std::pair<RegisterID*, Identifier>> activationValuesToCopyOver;
2293 activationValuesToCopyOver.reserveInitialCapacity(symbolTable->scopeSize());
2295 for (auto end = symbolTable->end(NoLockingNecessary), ptr = symbolTable->begin(NoLockingNecessary); ptr != end; ++ptr) {
2296 if (!ptr->value.varOffset().isScope())
2299 RefPtr<UniquedStringImpl> ident = ptr->key;
2300 Identifier identifier = Identifier::fromUid(m_vm, ident.get());
2302 RegisterID* transitionValue = newBlockScopeVariable();
2303 transitionValue->ref();
2304 emitGetFromScope(transitionValue, loopScope, variableForLocalEntry(identifier, ptr->value, loopSymbolTable->index(), true), DoNotThrowIfNotFound);
2305 activationValuesToCopyOver.uncheckedAppend(std::make_pair(transitionValue, identifier));
2309 // We need this dynamic behavior of the executing code to ensure
2310 // each loop iteration has a new activation object. (It's pretty ugly).
2311 // Also, this new activation needs to be assigned to the same register
2312 // as the previous scope because the loop body is compiled under
2313 // the assumption that the scope's register index is constant even
2314 // though the value in that register will change on each loop iteration.
2315 RefPtr<RegisterID> parentScope = emitGetParentScope(newTemporary(), loopScope);
2316 emitMove(scopeRegister(), parentScope.get());
2318 emitOpcode(op_create_lexical_environment);
2319 instructions().append(loopScope->index());
2320 instructions().append(scopeRegister()->index());
2321 instructions().append(loopSymbolTable->index());
2322 instructions().append(addConstantValue(jsTDZValue())->index());
2324 emitMove(scopeRegister(), loopScope);
2327 for (auto pair : activationValuesToCopyOver) {
2328 const Identifier& identifier = pair.second;
2329 SymbolTableEntry entry = symbolTable->get(NoLockingNecessary, identifier.impl());
2330 RELEASE_ASSERT(!entry.isNull());
2331 RegisterID* transitionValue = pair.first;
2332 emitPutToScope(loopScope, variableForLocalEntry(identifier, entry, loopSymbolTable->index(), true), transitionValue, DoNotThrowIfNotFound, InitializationMode::NotInitialization);
2333 transitionValue->deref();
2338 Variable BytecodeGenerator::variable(const Identifier& property, ThisResolutionType thisResolutionType)
2340 if (property == propertyNames().thisIdentifier && thisResolutionType == ThisResolutionType::Local)
2341 return Variable(property, VarOffset(thisRegister()->virtualRegister()), thisRegister(), static_cast<unsigned>(PropertyAttribute::ReadOnly), Variable::SpecialVariable, 0, false);
2343 // We can optimize lookups if the lexical variable is found before a "with" or "catch"
2344 // scope because we're guaranteed static resolution. If we have to pass through
2345 // a "with" or "catch" scope we loose this guarantee.
2346 // We can't optimize cases like this:
2350 // doSomethingWith(x);
2353 // Because we can't gaurantee static resolution on x.
2354 // But, in this case, we are guaranteed static resolution:
2359 // doSomethingWith(x);
2362 for (unsigned i = m_lexicalScopeStack.size(); i--; ) {
2363 auto& stackEntry = m_lexicalScopeStack[i];
2364 if (stackEntry.m_isWithScope)
2365 return Variable(property);
2366 SymbolTable* symbolTable = stackEntry.m_symbolTable;
2367 SymbolTableEntry symbolTableEntry = symbolTable->get(NoLockingNecessary, property.impl());
2368 if (symbolTableEntry.isNull())
2370 bool resultIsCallee = false;
2371 if (symbolTable->scopeType() == SymbolTable::ScopeType::FunctionNameScope) {
2372 if (m_usesNonStrictEval) {
2373 // We don't know if an eval has introduced a "var" named the same thing as the function name scope variable name.
2374 // We resort to dynamic lookup to answer this question.
2375 Variable result = Variable(property);
2378 resultIsCallee = true;
2380 Variable result = variableForLocalEntry(property, symbolTableEntry, stackEntry.m_symbolTableConstantIndex, symbolTable->scopeType() == SymbolTable::ScopeType::LexicalScope);
2382 result.setIsReadOnly();
2386 return Variable(property);
2389 Variable BytecodeGenerator::variableForLocalEntry(
2390 const Identifier& property, const SymbolTableEntry& entry, int symbolTableConstantIndex, bool isLexicallyScoped)
2392 VarOffset offset = entry.varOffset();
2395 if (offset.isStack())
2396 local = ®isterFor(offset.stackOffset());
2400 return Variable(property, offset, local, entry.getAttributes(), Variable::NormalVariable, symbolTableConstantIndex, isLexicallyScoped);
2403 void BytecodeGenerator::createVariable(
2404 const Identifier& property, VarKind varKind, SymbolTable* symbolTable, ExistingVariableMode existingVariableMode)
2406 ASSERT(property != propertyNames().thisIdentifier);
2407 SymbolTableEntry entry = symbolTable->get(NoLockingNecessary, property.impl());
2409 if (!entry.isNull()) {
2410 if (existingVariableMode == IgnoreExisting)
2413 // Do some checks to ensure that the variable we're being asked to create is sufficiently
2414 // compatible with the one we have already created.
2416 VarOffset offset = entry.varOffset();
2418 // We can't change our minds about whether it's captured.
2419 if (offset.kind() != varKind) {
2421 "Trying to add variable called ", property, " as ", varKind,
2422 " but it was already added as ", offset, ".\n");
2423 RELEASE_ASSERT_NOT_REACHED();
2429 VarOffset varOffset;
2430 if (varKind == VarKind::Scope)
2431 varOffset = VarOffset(symbolTable->takeNextScopeOffset(NoLockingNecessary));
2433 ASSERT(varKind == VarKind::Stack);
2434 varOffset = VarOffset(virtualRegisterForLocal(m_calleeLocals.size()));
2436 SymbolTableEntry newEntry(varOffset, 0);
2437 symbolTable->add(NoLockingNecessary, property.impl(), newEntry);
2439 if (varKind == VarKind::Stack) {
2440 RegisterID* local = addVar();
2441 RELEASE_ASSERT(local->index() == varOffset.stackOffset().offset());
2445 RegisterID* BytecodeGenerator::emitOverridesHasInstance(RegisterID* dst, RegisterID* constructor, RegisterID* hasInstanceValue)
2447 emitOpcode(op_overrides_has_instance);
2448 instructions().append(dst->index());
2449 instructions().append(constructor->index());
2450 instructions().append(hasInstanceValue->index());
2454 // Indicates the least upper bound of resolve type based on local scope. The bytecode linker
2455 // will start with this ResolveType and compute the least upper bound including intercepting scopes.
2456 ResolveType BytecodeGenerator::resolveType()
2458 for (unsigned i = m_lexicalScopeStack.size(); i--; ) {
2459 if (m_lexicalScopeStack[i].m_isWithScope)
2461 if (m_usesNonStrictEval && m_lexicalScopeStack[i].m_symbolTable->scopeType() == SymbolTable::ScopeType::FunctionNameScope) {
2462 // We never want to assign to a FunctionNameScope. Returning Dynamic here achieves this goal.
2463 // If we aren't in non-strict eval mode, then NodesCodeGen needs to take care not to emit
2464 // a put_to_scope with the destination being the function name scope variable.
2469 if (m_usesNonStrictEval)
2470 return GlobalPropertyWithVarInjectionChecks;
2471 return GlobalProperty;
2474 RegisterID* BytecodeGenerator::emitResolveScope(RegisterID* dst, const Variable& variable)
2476 switch (variable.offset().kind()) {
2477 case VarKind::Stack:
2480 case VarKind::DirectArgument:
2481 return argumentsRegister();
2483 case VarKind::Scope: {
2484 // This always refers to the activation that *we* allocated, and not the current scope that code
2485 // lives in. Note that this will change once we have proper support for block scoping. Once that
2486 // changes, it will be correct for this code to return scopeRegister(). The only reason why we
2487 // don't do that already is that m_lexicalEnvironment is required by ConstDeclNode. ConstDeclNode
2488 // requires weird things because it is a shameful pile of nonsense, but block scoping would make
2489 // that code sensible and obviate the need for us to do bad things.
2490 for (unsigned i = m_lexicalScopeStack.size(); i--; ) {
2491 auto& stackEntry = m_lexicalScopeStack[i];
2492 // We should not resolve a variable to VarKind::Scope if a "with" scope lies in between the current
2493 // scope and the resolved scope.
2494 RELEASE_ASSERT(!stackEntry.m_isWithScope);
2496 if (stackEntry.m_symbolTable->get(NoLockingNecessary, variable.ident().impl()).isNull())
2499 RegisterID* scope = stackEntry.m_scope;
2500 RELEASE_ASSERT(scope);
2504 RELEASE_ASSERT_NOT_REACHED();
2508 case VarKind::Invalid:
2509 // Indicates non-local resolution.
2511 m_codeBlock->addPropertyAccessInstruction(instructions().size());
2513 // resolve_scope dst, id, ResolveType, depth
2514 dst = tempDestination(dst);
2515 emitOpcode(op_resolve_scope);
2516 instructions().append(kill(dst));
2517 instructions().append(scopeRegister()->index());
2518 instructions().append(addConstant(variable.ident()));
2519 instructions().append(resolveType());
2520 instructions().append(localScopeDepth());
2521 instructions().append(0);
2525 RELEASE_ASSERT_NOT_REACHED();
2529 RegisterID* BytecodeGenerator::emitGetFromScope(RegisterID* dst, RegisterID* scope, const Variable& variable, ResolveMode resolveMode)
2531 switch (variable.offset().kind()) {
2532 case VarKind::Stack:
2533 return emitMove(dst, variable.local());
2535 case VarKind::DirectArgument: {
2536 UnlinkedValueProfile profile = emitProfiledOpcode(op_get_from_arguments);
2537 instructions().append(kill(dst));
2538 instructions().append(scope->index());
2539 instructions().append(variable.offset().capturedArgumentsOffset().offset());
2540 instructions().append(profile);
2544 case VarKind::Scope:
2545 case VarKind::Invalid: {
2546 m_codeBlock->addPropertyAccessInstruction(instructions().size());
2548 // get_from_scope dst, scope, id, GetPutInfo, Structure, Operand
2549 UnlinkedValueProfile profile = emitProfiledOpcode(op_get_from_scope);
2550 instructions().append(kill(dst));
2551 instructions().append(scope->index());
2552 instructions().append(addConstant(variable.ident()));
2553 instructions().append(GetPutInfo(resolveMode, variable.offset().isScope() ? LocalClosureVar : resolveType(), InitializationMode::NotInitialization).operand());
2554 instructions().append(localScopeDepth());
2555 instructions().append(variable.offset().isScope() ? variable.offset().scopeOffset().offset() : 0);
2556 instructions().append(profile);
2560 RELEASE_ASSERT_NOT_REACHED();
2563 RegisterID* BytecodeGenerator::emitPutToScope(RegisterID* scope, const Variable& variable, RegisterID* value, ResolveMode resolveMode, InitializationMode initializationMode)
2565 switch (variable.offset().kind()) {
2566 case VarKind::Stack:
2567 emitMove(variable.local(), value);
2570 case VarKind::DirectArgument:
2571 emitOpcode(op_put_to_arguments);
2572 instructions().append(scope->index());
2573 instructions().append(variable.offset().capturedArgumentsOffset().offset());
2574 instructions().append(value->index());
2577 case VarKind::Scope:
2578 case VarKind::Invalid: {
2579 m_codeBlock->addPropertyAccessInstruction(instructions().size());
2581 // put_to_scope scope, id, value, GetPutInfo, Structure, Operand
2582 emitOpcode(op_put_to_scope);
2583 instructions().append(scope->index());
2584 instructions().append(addConstant(variable.ident()));
2585 instructions().append(value->index());
2587 if (variable.offset().isScope()) {
2588 offset = variable.offset().scopeOffset();
2589 instructions().append(GetPutInfo(resolveMode, LocalClosureVar, initializationMode).operand());
2590 instructions().append(variable.symbolTableConstantIndex());
2592 ASSERT(resolveType() != LocalClosureVar);
2593 instructions().append(GetPutInfo(resolveMode, resolveType(), initializationMode).operand());
2594 instructions().append(localScopeDepth());
2596 instructions().append(!!offset ? offset.offset() : 0);
2600 RELEASE_ASSERT_NOT_REACHED();
2603 RegisterID* BytecodeGenerator::initializeVariable(const Variable& variable, RegisterID* value)
2605 RELEASE_ASSERT(variable.offset().kind() != VarKind::Invalid);
2606 RegisterID* scope = emitResolveScope(nullptr, variable);
2607 return emitPutToScope(scope, variable, value, ThrowIfNotFound, InitializationMode::NotInitialization);
2610 RegisterID* BytecodeGenerator::emitInstanceOf(RegisterID* dst, RegisterID* value, RegisterID* basePrototype)
2612 emitOpcode(op_instanceof);
2613 instructions().append(dst->index());
2614 instructions().append(value->index());
2615 instructions().append(basePrototype->index());
2619 RegisterID* BytecodeGenerator::emitInstanceOfCustom(RegisterID* dst, RegisterID* value, RegisterID* constructor, RegisterID* hasInstanceValue)
2621 emitOpcode(op_instanceof_custom);
2622 instructions().append(dst->index());
2623 instructions().append(value->index());
2624 instructions().append(constructor->index());
2625 instructions().append(hasInstanceValue->index());
2629 RegisterID* BytecodeGenerator::emitIn(RegisterID* dst, RegisterID* property, RegisterID* base)
2631 UnlinkedArrayProfile arrayProfile = newArrayProfile();
2633 instructions().append(dst->index());
2634 instructions().append(base->index());
2635 instructions().append(property->index());
2636 instructions().append(arrayProfile);
2640 RegisterID* BytecodeGenerator::emitTryGetById(RegisterID* dst, RegisterID* base, const Identifier& property)
2642 ASSERT_WITH_MESSAGE(!parseIndex(property), "Indexed properties are not supported with tryGetById.");
2644 UnlinkedValueProfile profile = emitProfiledOpcode(op_try_get_by_id);
2645 instructions().append(kill(dst));
2646 instructions().append(base->index());
2647 instructions().append(addConstant(property));
2648 instructions().append(profile);
2652 RegisterID* BytecodeGenerator::emitGetById(RegisterID* dst, RegisterID* base, const Identifier& property)
2654 ASSERT_WITH_MESSAGE(!parseIndex(property), "Indexed properties should be handled with get_by_val.");
2656 m_codeBlock->addPropertyAccessInstruction(instructions().size());
2658 UnlinkedValueProfile profile = emitProfiledOpcode(op_get_by_id);
2659 instructions().append(kill(dst));
2660 instructions().append(base->index());
2661 instructions().append(addConstant(property));
2662 instructions().append(0);
2663 instructions().append(0);
2664 instructions().append(0);
2665 instructions().append(Options::prototypeHitCountForLLIntCaching());
2666 instructions().append(profile);
2670 RegisterID* BytecodeGenerator::emitGetById(RegisterID* dst, RegisterID* base, RegisterID* thisVal, const Identifier& property)
2672 ASSERT_WITH_MESSAGE(!parseIndex(property), "Indexed properties should be handled with get_by_val.");
2674 UnlinkedValueProfile profile = emitProfiledOpcode(op_get_by_id_with_this);
2675 instructions().append(kill(dst));
2676 instructions().append(base->index());
2677 instructions().append(thisVal->index());
2678 instructions().append(addConstant(property));
2679 instructions().append(profile);
2683 RegisterID* BytecodeGenerator::emitPutById(RegisterID* base, const Identifier& property, RegisterID* value)
2685 ASSERT_WITH_MESSAGE(!parseIndex(property), "Indexed properties should be handled with put_by_val.");
2687 unsigned propertyIndex = addConstant(property);
2689 m_staticPropertyAnalyzer.putById(base->index(), propertyIndex);
2691 m_codeBlock->addPropertyAccessInstruction(instructions().size());
2693 emitOpcode(op_put_by_id);
2694 instructions().append(base->index());
2695 instructions().append(propertyIndex);
2696 instructions().append(value->index());
2697 instructions().append(0); // old structure
2698 instructions().append(0); // offset
2699 instructions().append(0); // new structure
2700 instructions().append(0); // structure chain
2701 instructions().append(static_cast<int>(PutByIdNone)); // is not direct
2706 RegisterID* BytecodeGenerator::emitPutById(RegisterID* base, RegisterID* thisValue, const Identifier& property, RegisterID* value)
2708 ASSERT_WITH_MESSAGE(!parseIndex(property), "Indexed properties should be handled with put_by_val.");
2710 unsigned propertyIndex = addConstant(property);
2712 emitOpcode(op_put_by_id_with_this);
2713 instructions().append(base->index());
2714 instructions().append(thisValue->index());
2715 instructions().append(propertyIndex);
2716 instructions().append(value->index());
2721 RegisterID* BytecodeGenerator::emitDirectPutById(RegisterID* base, const Identifier& property, RegisterID* value, PropertyNode::PutType putType)
2723 ASSERT_WITH_MESSAGE(!parseIndex(property), "Indexed properties should be handled with put_by_val(direct).");
2725 unsigned propertyIndex = addConstant(property);
2727 m_staticPropertyAnalyzer.putById(base->index(), propertyIndex);
2729 m_codeBlock->addPropertyAccessInstruction(instructions().size());
2731 emitOpcode(op_put_by_id);
2732 instructions().append(base->index());
2733 instructions().append(propertyIndex);
2734 instructions().append(value->index());
2735 instructions().append(0); // old structure
2736 instructions().append(0); // offset
2737 instructions().append(0); // new structure
2738 instructions().append(0); // structure chain (unused if direct)
2739 instructions().append(static_cast<int>((putType == PropertyNode::KnownDirect || property != m_vm->propertyNames->underscoreProto) ? PutByIdIsDirect : PutByIdNone));
2743 void BytecodeGenerator::emitPutGetterById(RegisterID* base, const Identifier& property, unsigned attributes, RegisterID* getter)
2745 unsigned propertyIndex = addConstant(property);
2746 m_staticPropertyAnalyzer.putById(base->index(), propertyIndex);
2748 emitOpcode(op_put_getter_by_id);
2749 instructions().append(base->index());
2750 instructions().append(propertyIndex);
2751 instructions().append(attributes);
2752 instructions().append(getter->index());
2755 void BytecodeGenerator::emitPutSetterById(RegisterID* base, const Identifier& property, unsigned attributes, RegisterID* setter)
2757 unsigned propertyIndex = addConstant(property);
2758 m_staticPropertyAnalyzer.putById(base->index(), propertyIndex);
2760 emitOpcode(op_put_setter_by_id);
2761 instructions().append(base->index());
2762 instructions().append(propertyIndex);
2763 instructions().append(attributes);
2764 instructions().append(setter->index());
2767 void BytecodeGenerator::emitPutGetterSetter(RegisterID* base, const Identifier& property, unsigned attributes, RegisterID* getter, RegisterID* setter)
2769 unsigned propertyIndex = addConstant(property);
2771 m_staticPropertyAnalyzer.putById(base->index(), propertyIndex);
2773 emitOpcode(op_put_getter_setter_by_id);
2774 instructions().append(base->index());
2775 instructions().append(propertyIndex);
2776 instructions().append(attributes);
2777 instructions().append(getter->index());
2778 instructions().append(setter->index());
2781 void BytecodeGenerator::emitPutGetterByVal(RegisterID* base, RegisterID* property, unsigned attributes, RegisterID* getter)
2783 emitOpcode(op_put_getter_by_val);
2784 instructions().append(base->index());
2785 instructions().append(property->index());
2786 instructions().append(attributes);
2787 instructions().append(getter->index());
2790 void BytecodeGenerator::emitPutSetterByVal(RegisterID* base, RegisterID* property, unsigned attributes, RegisterID* setter)
2792 emitOpcode(op_put_setter_by_val);
2793 instructions().append(base->index());
2794 instructions().append(property->index());
2795 instructions().append(attributes);
2796 instructions().append(setter->index());
2799 void BytecodeGenerator::emitPutGeneratorFields(RegisterID* nextFunction)
2801 // FIXME: Currently, we just create an object and store generator related fields as its properties for ease.
2802 // But to make it efficient, we will introduce JSGenerator class, add opcode new_generator and use its C++ fields instead of these private properties.
2803 // https://bugs.webkit.org/show_bug.cgi?id=151545
2805 emitDirectPutById(m_generatorRegister, propertyNames().builtinNames().generatorNextPrivateName(), nextFunction, PropertyNode::KnownDirect);
2807 // We do not store 'this' in arrow function within constructor,
2808 // because it might be not initialized, if super is called later.
2809 if (!(isDerivedConstructorContext() && m_codeBlock->parseMode() == SourceParseMode::AsyncArrowFunctionMode))
2810 emitDirectPutById(m_generatorRegister, propertyNames().builtinNames().generatorThisPrivateName(), &m_thisRegister, PropertyNode::KnownDirect);
2812 emitDirectPutById(m_generatorRegister, propertyNames().builtinNames().generatorStatePrivateName(), emitLoad(nullptr, jsNumber(0)), PropertyNode::KnownDirect);
2814 emitDirectPutById(m_generatorRegister, propertyNames().builtinNames().generatorFramePrivateName(), emitLoad(nullptr, jsNull()), PropertyNode::KnownDirect);
2817 void BytecodeGenerator::emitPutAsyncGeneratorFields(RegisterID* nextFunction)
2819 ASSERT(isAsyncGeneratorFunctionParseMode(parseMode()));
2821 emitDirectPutById(m_generatorRegister, propertyNames().builtinNames().generatorNextPrivateName(), nextFunction, PropertyNode::KnownDirect);
2823 emitDirectPutById(m_generatorRegister, propertyNames().builtinNames().generatorThisPrivateName(), &m_thisRegister, PropertyNode::KnownDirect);
2825 emitDirectPutById(m_generatorRegister, propertyNames().builtinNames().generatorStatePrivateName(), emitLoad(nullptr, jsNumber(static_cast<int32_t>(JSAsyncGeneratorFunction::AsyncGeneratorState::SuspendedStart))), PropertyNode::KnownDirect);
2827 emitDirectPutById(m_generatorRegister, propertyNames().builtinNames().generatorFramePrivateName(), emitLoad(nullptr, jsNull()), PropertyNode::KnownDirect);
2829 emitDirectPutById(m_generatorRegister, propertyNames().builtinNames().asyncGeneratorSuspendReasonPrivateName(), emitLoad(nullptr, jsNumber(static_cast<int32_t>(JSAsyncGeneratorFunction::AsyncGeneratorSuspendReason::None))), PropertyNode::KnownDirect);
2831 emitDirectPutById(m_generatorRegister, propertyNames().builtinNames().asyncGeneratorQueueFirstPrivateName(), emitLoad(nullptr, jsNull()), PropertyNode::KnownDirect);
2832 emitDirectPutById(m_generatorRegister, propertyNames().builtinNames().asyncGeneratorQueueLastPrivateName(), emitLoad(nullptr, jsNull()), PropertyNode::KnownDirect);
2835 RegisterID* BytecodeGenerator::emitDeleteById(RegisterID* dst, RegisterID* base, const Identifier& property)
2837 emitOpcode(op_del_by_id);
2838 instructions().append(dst->index());
2839 instructions().append(base->index());
2840 instructions().append(addConstant(property));
2844 RegisterID* BytecodeGenerator::emitGetByVal(RegisterID* dst, RegisterID* base, RegisterID* property)
2846 for (size_t i = m_forInContextStack.size(); i--; ) {
2847 ForInContext& context = m_forInContextStack[i].get();
2848 if (context.local() != property)
2851 unsigned instIndex = instructions().size();
2853 if (context.type() == ForInContext::IndexedForInContextType) {
2854 static_cast<IndexedForInContext&>(context).addGetInst(instIndex, property->index());
2855 property = static_cast<IndexedForInContext&>(context).index();
2859 ASSERT(context.type() == ForInContext::StructureForInContextType);
2860 StructureForInContext& structureContext = static_cast<StructureForInContext&>(context);
2861 UnlinkedValueProfile profile = emitProfiledOpcode(op_get_direct_pname);
2862 instructions().append(kill(dst));
2863 instructions().append(base->index());
2864 instructions().append(property->index());
2865 instructions().append(structureContext.index()->index());
2866 instructions().append(structureContext.enumerator()->index());
2867 instructions().append(profile);
2869 structureContext.addGetInst(instIndex, property->index(), profile);
2873 UnlinkedArrayProfile arrayProfile = newArrayProfile();
2874 UnlinkedValueProfile profile = emitProfiledOpcode(op_get_by_val);
2875 instructions().append(kill(dst));
2876 instructions().append(base->index());
2877 instructions().append(property->index());
2878 instructions().append(arrayProfile);
2879 instructions().append(profile);
2883 RegisterID* BytecodeGenerator::emitGetByVal(RegisterID* dst, RegisterID* base, RegisterID* thisValue, RegisterID* property)
2885 UnlinkedValueProfile profile = emitProfiledOpcode(op_get_by_val_with_this);
2886 instructions().append(kill(dst));
2887 instructions().append(base->index());
2888 instructions().append(thisValue->index());
2889 instructions().append(property->index());
2890 instructions().append(profile);
2894 RegisterID* BytecodeGenerator::emitPutByVal(RegisterID* base, RegisterID* property, RegisterID* value)
2896 UnlinkedArrayProfile arrayProfile = newArrayProfile();
2897 emitOpcode(op_put_by_val);
2898 instructions().append(base->index());
2899 instructions().append(property->index());
2900 instructions().append(value->index());
2901 instructions().append(arrayProfile);
2906 RegisterID* BytecodeGenerator::emitPutByVal(RegisterID* base, RegisterID* thisValue, RegisterID* property, RegisterID* value)
2908 emitOpcode(op_put_by_val_with_this);
2909 instructions().append(base->index());
2910 instructions().append(thisValue->index());
2911 instructions().append(property->index());
2912 instructions().append(value->index());
2917 RegisterID* BytecodeGenerator::emitDirectPutByVal(RegisterID* base, RegisterID* property, RegisterID* value)
2919 UnlinkedArrayProfile arrayProfile = newArrayProfile();
2920 emitOpcode(op_put_by_val_direct);
2921 instructions().append(base->index());
2922 instructions().append(property->index());
2923 instructions().append(value->index());
2924 instructions().append(arrayProfile);
2928 RegisterID* BytecodeGenerator::emitDeleteByVal(RegisterID* dst, RegisterID* base, RegisterID* property)
2930 emitOpcode(op_del_by_val);
2931 instructions().append(dst->index());
2932 instructions().append(base->index());
2933 instructions().append(property->index());
2937 RegisterID* BytecodeGenerator::emitPutByIndex(RegisterID* base, unsigned index, RegisterID* value)
2939 emitOpcode(op_put_by_index);
2940 instructions().append(base->index());
2941 instructions().append(index);
2942 instructions().append(value->index());
2946 RegisterID* BytecodeGenerator::emitAssert(RegisterID* condition, int line)
2948 emitOpcode(op_assert);
2949 instructions().append(condition->index());
2950 instructions().append(line);
2954 RegisterID* BytecodeGenerator::emitIdWithProfile(RegisterID* src, SpeculatedType profile)
2956 emitOpcode(op_identity_with_profile);
2957 instructions().append(src->index());
2958 instructions().append(static_cast<uint32_t>(profile >> 32));
2959 instructions().append(static_cast<uint32_t>(profile));
2963 void BytecodeGenerator::emitUnreachable()
2965 emitOpcode(op_unreachable);
2968 RegisterID* BytecodeGenerator::emitGetArgument(RegisterID* dst, int32_t index)
2970 UnlinkedValueProfile profile = emitProfiledOpcode(op_get_argument);
2971 instructions().append(dst->index());
2972 instructions().append(index + 1); // Including |this|.
2973 instructions().append(profile);
2977 RegisterID* BytecodeGenerator::emitCreateThis(RegisterID* dst)
2979 size_t begin = instructions().size();
2980 m_staticPropertyAnalyzer.createThis(dst->index(), begin + 3);
2982 m_codeBlock->addPropertyAccessInstruction(instructions().size());
2983 emitOpcode(op_create_this);
2984 instructions().append(dst->index());
2985 instructions().append(dst->index());
2986 instructions().append(0);
2987 instructions().append(0);
2991 void BytecodeGenerator::emitTDZCheck(RegisterID* target)
2993 emitOpcode(op_check_tdz);
2994 instructions().append(target->index());
2997 bool BytecodeGenerator::needsTDZCheck(const Variable& variable)
2999 for (unsigned i = m_TDZStack.size(); i--;) {
3000 auto iter = m_TDZStack[i].find(variable.ident().impl());
3001 if (iter == m_TDZStack[i].end())
3003 return iter->value != TDZNecessityLevel::NotNeeded;
3009 void BytecodeGenerator::emitTDZCheckIfNecessary(const Variable& variable, RegisterID* target, RegisterID* scope)
3011 if (needsTDZCheck(variable)) {
3013 emitTDZCheck(target);
3015 RELEASE_ASSERT(!variable.isLocal() && scope);
3016 RefPtr<RegisterID> result = emitGetFromScope(newTemporary(), scope, variable, DoNotThrowIfNotFound);
3017 emitTDZCheck(result.get());
3022 void BytecodeGenerator::liftTDZCheckIfPossible(const Variable& variable)
3024 RefPtr<UniquedStringImpl> identifier(variable.ident().impl());
3025 for (unsigned i = m_TDZStack.size(); i--;) {
3026 auto iter = m_TDZStack[i].find(identifier);
3027 if (iter != m_TDZStack[i].end()) {
3028 if (iter->value == TDZNecessityLevel::Optimize)
3029 iter->value = TDZNecessityLevel::NotNeeded;
3035 void BytecodeGenerator::pushTDZVariables(const VariableEnvironment& environment, TDZCheckOptimization optimization, TDZRequirement requirement)
3037 if (!environment.size())
3040 TDZNecessityLevel level;
3041 if (requirement == TDZRequirement::UnderTDZ) {
3042 if (optimization == TDZCheckOptimization::Optimize)
3043 level = TDZNecessityLevel::Optimize;
3045 level = TDZNecessityLevel::DoNotOptimize;
3047 level = TDZNecessityLevel::NotNeeded;
3050 for (const auto& entry : environment)
3051 map.add(entry.key, entry.value.isFunction() ? TDZNecessityLevel::NotNeeded : level);
3053 m_TDZStack.append(WTFMove(map));
3056 void BytecodeGenerator::getVariablesUnderTDZ(VariableEnvironment& result)
3058 // We keep track of variablesThatDontNeedTDZ in this algorithm to prevent
3059 // reporting that "x" is under TDZ if this function is called at "...".
3069 SmallPtrSet<UniquedStringImpl*, 16> variablesThatDontNeedTDZ;
3070 for (unsigned i = m_TDZStack.size(); i--; ) {
3071 auto& map = m_TDZStack[i];
3072 for (auto& entry : map) {
3073 if (entry.value != TDZNecessityLevel::NotNeeded) {
3074 if (!variablesThatDontNeedTDZ.contains(entry.key.get()))
3075 result.add(entry.key.get());
3077 variablesThatDontNeedTDZ.add(entry.key.get());
3082 RegisterID* BytecodeGenerator::emitNewObject(RegisterID* dst)
3084 size_t begin = instructions().size();
3085 m_staticPropertyAnalyzer.newObject(dst->index(), begin + 2);
3087 emitOpcode(op_new_object);
3088 instructions().append(dst->index());
3089 instructions().append(0);
3090 instructions().append(newObjectAllocationProfile());
3094 unsigned BytecodeGenerator::addConstantBuffer(unsigned length)
3096 return m_codeBlock->addConstantBuffer(length);
3099 JSString* BytecodeGenerator::addStringConstant(const Identifier& identifier)
3101 JSString*& stringInMap = m_stringMap.add(identifier.impl(), nullptr).iterator->value;
3103 stringInMap = jsString(vm(), identifier.string());
3104 addConstantValue(stringInMap);
3109 RegisterID* BytecodeGenerator::addTemplateRegistryKeyConstant(Ref<TemplateRegistryKey>&& templateRegistryKey)
3111 return m_templateRegistryKeyMap.ensure(templateRegistryKey.copyRef(), [&] {
3112 auto* result = JSTemplateRegistryKey::create(*vm(), WTFMove(templateRegistryKey));
3113 unsigned index = addConstantIndex();
3114 m_codeBlock->addConstant(result);
3115 return &m_constantPoolRegisters[index];
3119 RegisterID* BytecodeGenerator::emitNewArray(RegisterID* dst, ElementNode* elements, unsigned length)
3121 #if !ASSERT_DISABLED
3122 unsigned checkLength = 0;
3124 bool hadVariableExpression = false;
3126 for (ElementNode* n = elements; n; n = n->next()) {
3127 if (!n->value()->isConstant()) {
3128 hadVariableExpression = true;
3133 #if !ASSERT_DISABLED
3137 if (!hadVariableExpression) {
3138 ASSERT(length == checkLength);
3139 unsigned constantBufferIndex = addConstantBuffer(length);
3140 JSValue* constantBuffer = m_codeBlock->constantBuffer(constantBufferIndex).data();
3142 for (ElementNode* n = elements; index < length; n = n->next()) {
3143 ASSERT(n->value()->isConstant());
3144 constantBuffer[index++] = static_cast<ConstantNode*>(n->value())->jsValue(*this);
3146 emitOpcode(op_new_array_buffer);
3147 instructions().append(dst->index());
3148 instructions().append(constantBufferIndex);
3149 instructions().append(length);
3150 instructions().append(newArrayAllocationProfile());
3155 Vector<RefPtr<RegisterID>, 16, UnsafeVectorOverflow> argv;
3156 for (ElementNode* n = elements; n; n = n->next()) {