Rolling out r214038 and r213697: Crashes when using computed properties with rest...
[WebKit-https.git] / Source / JavaScriptCore / bytecompiler / BytecodeGenerator.h
1 /*
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.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  *
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.
18  *
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.
29  */
30
31 #pragma once
32
33 #include "CodeBlock.h"
34 #include "Instruction.h"
35 #include "Interpreter.h"
36 #include "JSGeneratorFunction.h"
37 #include "Label.h"
38 #include "LabelScope.h"
39 #include "Nodes.h"
40 #include "ParserError.h"
41 #include "RegisterID.h"
42 #include "StaticPropertyAnalyzer.h"
43 #include "SymbolTable.h"
44 #include "TemplateRegistryKey.h"
45 #include "UnlinkedCodeBlock.h"
46 #include <functional>
47 #include <wtf/CheckedArithmetic.h>
48 #include <wtf/HashTraits.h>
49 #include <wtf/SegmentedVector.h>
50 #include <wtf/SetForScope.h>
51 #include <wtf/Vector.h>
52
53 namespace JSC {
54
55     class Identifier;
56     class JSTemplateRegistryKey;
57
58     enum ExpectedFunction {
59         NoExpectedFunction,
60         ExpectObjectConstructor,
61         ExpectArrayConstructor
62     };
63
64     enum class DebuggableCall { Yes, No };
65     enum class ThisResolutionType { Local, Scoped };
66     
67     class CallArguments {
68     public:
69         CallArguments(BytecodeGenerator&, ArgumentsNode*, unsigned additionalArguments = 0);
70
71         RegisterID* thisRegister() { return m_argv[0].get(); }
72         RegisterID* argumentRegister(unsigned i) { return m_argv[i + 1].get(); }
73         unsigned stackOffset() { return -m_argv[0]->index() + CallFrame::headerSizeInRegisters; }
74         unsigned argumentCountIncludingThis() { return m_argv.size() - m_padding; }
75         ArgumentsNode* argumentsNode() { return m_argumentsNode; }
76
77     private:
78         ArgumentsNode* m_argumentsNode;
79         Vector<RefPtr<RegisterID>, 8, UnsafeVectorOverflow> m_argv;
80         unsigned m_padding;
81     };
82
83     // https://tc39.github.io/ecma262/#sec-completion-record-specification-type
84     //
85     // For the Break and Continue cases, instead of using the Break and Continue enum values
86     // below, we use the unique jumpID of the break and continue statement as the encoding
87     // for the CompletionType value. emitFinallyCompletion() uses this jumpID value later
88     // to determine the appropriate jump target to jump to after executing the relevant finally
89     // blocks. The jumpID is computed as:
90     //     jumpID = bytecodeOffset (of the break/continue node) + CompletionType::NumberOfTypes.
91     // Hence, there won't be any collision between jumpIDs and CompletionType enums.
92     enum class CompletionType : int {
93         Normal,
94         Break,
95         Continue,
96         Return,
97         Throw,
98         
99         NumberOfTypes
100     };
101
102     inline CompletionType bytecodeOffsetToJumpID(unsigned offset)
103     {
104         int jumpIDAsInt = offset + static_cast<int>(CompletionType::NumberOfTypes);
105         ASSERT(jumpIDAsInt >= static_cast<int>(CompletionType::NumberOfTypes));
106         return static_cast<CompletionType>(jumpIDAsInt);
107     }
108
109     struct FinallyJump {
110         FinallyJump(CompletionType jumpID, int targetLexicalScopeIndex, Label& targetLabel)
111             : jumpID(jumpID)
112             , targetLexicalScopeIndex(targetLexicalScopeIndex)
113             , targetLabel(targetLabel)
114         { }
115
116         CompletionType jumpID;
117         int targetLexicalScopeIndex;
118         Ref<Label> targetLabel;
119     };
120
121     struct FinallyContext {
122         FinallyContext() { }
123         FinallyContext(FinallyContext* outerContext, Label& finallyLabel)
124             : m_outerContext(outerContext)
125             , m_finallyLabel(&finallyLabel)
126         {
127             ASSERT(m_jumps.isEmpty());
128         }
129
130         FinallyContext* outerContext() const { return m_outerContext; }
131         Label* finallyLabel() const { return m_finallyLabel; }
132
133         uint32_t numberOfBreaksOrContinues() const { return m_numberOfBreaksOrContinues.unsafeGet(); }
134         void incNumberOfBreaksOrContinues() { m_numberOfBreaksOrContinues++; }
135
136         bool handlesReturns() const { return m_handlesReturns; }
137         void setHandlesReturns() { m_handlesReturns = true; }
138
139         void registerJump(CompletionType jumpID, int lexicalScopeIndex, Label& targetLabel)
140         {
141             m_jumps.append(FinallyJump(jumpID, lexicalScopeIndex, targetLabel));
142         }
143
144         size_t numberOfJumps() const { return m_jumps.size(); }
145         FinallyJump& jumps(size_t i) { return m_jumps[i]; }
146
147     private:
148         FinallyContext* m_outerContext { nullptr };
149         Label* m_finallyLabel { nullptr };
150         Checked<uint32_t, WTF::CrashOnOverflow> m_numberOfBreaksOrContinues;
151         bool m_handlesReturns { false };
152         Vector<FinallyJump> m_jumps;
153     };
154
155     struct ControlFlowScope {
156         typedef uint8_t Type;
157         enum {
158             Label,
159             Finally
160         };
161         ControlFlowScope(Type type, int lexicalScopeIndex, FinallyContext&& finallyContext = FinallyContext())
162             : type(type)
163             , lexicalScopeIndex(lexicalScopeIndex)
164             , finallyContext(std::forward<FinallyContext>(finallyContext))
165         { }
166
167         bool isLabelScope() const { return type == Label; }
168         bool isFinallyScope() const { return type == Finally; }
169
170         Type type;
171         int lexicalScopeIndex;
172         FinallyContext finallyContext;
173     };
174
175     class ForInContext : public RefCounted<ForInContext> {
176         WTF_MAKE_FAST_ALLOCATED;
177         WTF_MAKE_NONCOPYABLE(ForInContext);
178     public:
179         ForInContext(RegisterID* localRegister)
180             : m_localRegister(localRegister)
181             , m_isValid(true)
182         {
183         }
184
185         virtual ~ForInContext()
186         {
187         }
188
189         bool isValid() const { return m_isValid; }
190         void invalidate() { m_isValid = false; }
191
192         enum ForInContextType {
193             StructureForInContextType,
194             IndexedForInContextType
195         };
196         virtual ForInContextType type() const = 0;
197
198         RegisterID* local() const { return m_localRegister.get(); }
199
200     private:
201         RefPtr<RegisterID> m_localRegister;
202         bool m_isValid;
203     };
204
205     class StructureForInContext : public ForInContext {
206     public:
207         StructureForInContext(RegisterID* localRegister, RegisterID* indexRegister, RegisterID* propertyRegister, RegisterID* enumeratorRegister)
208             : ForInContext(localRegister)
209             , m_indexRegister(indexRegister)
210             , m_propertyRegister(propertyRegister)
211             , m_enumeratorRegister(enumeratorRegister)
212         {
213         }
214
215         ForInContextType type() const override
216         {
217             return StructureForInContextType;
218         }
219
220         RegisterID* index() const { return m_indexRegister.get(); }
221         RegisterID* property() const { return m_propertyRegister.get(); }
222         RegisterID* enumerator() const { return m_enumeratorRegister.get(); }
223
224     private:
225         RefPtr<RegisterID> m_indexRegister;
226         RefPtr<RegisterID> m_propertyRegister;
227         RefPtr<RegisterID> m_enumeratorRegister;
228     };
229
230     class IndexedForInContext : public ForInContext {
231     public:
232         IndexedForInContext(RegisterID* localRegister, RegisterID* indexRegister)
233             : ForInContext(localRegister)
234             , m_indexRegister(indexRegister)
235         {
236         }
237
238         ForInContextType type() const override
239         {
240             return IndexedForInContextType;
241         }
242
243         RegisterID* index() const { return m_indexRegister.get(); }
244
245     private:
246         RefPtr<RegisterID> m_indexRegister;
247     };
248
249     struct TryData {
250         Ref<Label> target;
251         HandlerType handlerType;
252     };
253
254     struct TryContext {
255         Ref<Label> start;
256         TryData* tryData;
257     };
258
259     class Variable {
260     public:
261         enum VariableKind { NormalVariable, SpecialVariable };
262
263         Variable()
264             : m_offset()
265             , m_local(nullptr)
266             , m_attributes(0)
267             , m_kind(NormalVariable)
268             , m_symbolTableConstantIndex(0) // This is meaningless here for this kind of Variable.
269             , m_isLexicallyScoped(false)
270         {
271         }
272         
273         Variable(const Identifier& ident)
274             : m_ident(ident)
275             , m_local(nullptr)
276             , m_attributes(0)
277             , m_kind(NormalVariable) // This is somewhat meaningless here for this kind of Variable.
278             , m_symbolTableConstantIndex(0) // This is meaningless here for this kind of Variable.
279             , m_isLexicallyScoped(false)
280         {
281         }
282
283         Variable(const Identifier& ident, VarOffset offset, RegisterID* local, unsigned attributes, VariableKind kind, int symbolTableConstantIndex, bool isLexicallyScoped)
284             : m_ident(ident)
285             , m_offset(offset)
286             , m_local(local)
287             , m_attributes(attributes)
288             , m_kind(kind)
289             , m_symbolTableConstantIndex(symbolTableConstantIndex)
290             , m_isLexicallyScoped(isLexicallyScoped)
291         {
292         }
293
294         // If it's unset, then it is a non-locally-scoped variable. If it is set, then it could be
295         // a stack variable, a scoped variable in a local scope, or a variable captured in the
296         // direct arguments object.
297         bool isResolved() const { return !!m_offset; }
298         int symbolTableConstantIndex() const { ASSERT(isResolved() && !isSpecial()); return m_symbolTableConstantIndex; }
299         
300         const Identifier& ident() const { return m_ident; }
301         
302         VarOffset offset() const { return m_offset; }
303         bool isLocal() const { return m_offset.isStack(); }
304         RegisterID* local() const { return m_local; }
305
306         bool isReadOnly() const { return m_attributes & ReadOnly; }
307         bool isSpecial() const { return m_kind != NormalVariable; }
308         bool isConst() const { return isReadOnly() && m_isLexicallyScoped; }
309         void setIsReadOnly() { m_attributes |= ReadOnly; }
310
311         void dump(PrintStream&) const;
312
313     private:
314         Identifier m_ident;
315         VarOffset m_offset;
316         RegisterID* m_local;
317         unsigned m_attributes;
318         VariableKind m_kind;
319         int m_symbolTableConstantIndex;
320         bool m_isLexicallyScoped;
321     };
322
323     struct TryRange {
324         Ref<Label> start;
325         Ref<Label> end;
326         TryData* tryData;
327     };
328
329     enum ProfileTypeBytecodeFlag {
330         ProfileTypeBytecodeClosureVar,
331         ProfileTypeBytecodeLocallyResolved,
332         ProfileTypeBytecodeDoesNotHaveGlobalID,
333         ProfileTypeBytecodeFunctionArgument,
334         ProfileTypeBytecodeFunctionReturnStatement
335     };
336
337     class BytecodeGenerator {
338         WTF_MAKE_FAST_ALLOCATED;
339         WTF_MAKE_NONCOPYABLE(BytecodeGenerator);
340     public:
341         typedef DeclarationStacks::FunctionStack FunctionStack;
342
343         BytecodeGenerator(VM&, ProgramNode*, UnlinkedProgramCodeBlock*, DebuggerMode, const VariableEnvironment*);
344         BytecodeGenerator(VM&, FunctionNode*, UnlinkedFunctionCodeBlock*, DebuggerMode, const VariableEnvironment*);
345         BytecodeGenerator(VM&, EvalNode*, UnlinkedEvalCodeBlock*, DebuggerMode, const VariableEnvironment*);
346         BytecodeGenerator(VM&, ModuleProgramNode*, UnlinkedModuleProgramCodeBlock*, DebuggerMode, const VariableEnvironment*);
347
348         ~BytecodeGenerator();
349         
350         VM* vm() const { return m_vm; }
351         ParserArena& parserArena() const { return m_scopeNode->parserArena(); }
352         const CommonIdentifiers& propertyNames() const { return *m_vm->propertyNames; }
353
354         bool isConstructor() const { return m_codeBlock->isConstructor(); }
355         DerivedContextType derivedContextType() const { return m_derivedContextType; }
356         bool usesArrowFunction() const { return m_scopeNode->usesArrowFunction(); }
357         bool needsToUpdateArrowFunctionContext() const { return m_needsToUpdateArrowFunctionContext; }
358         bool usesEval() const { return m_scopeNode->usesEval(); }
359         bool usesThis() const { return m_scopeNode->usesThis(); }
360         ConstructorKind constructorKind() const { return m_codeBlock->constructorKind(); }
361         SuperBinding superBinding() const { return m_codeBlock->superBinding(); }
362         JSParserScriptMode scriptMode() const { return m_codeBlock->scriptMode(); }
363
364         template<typename... Args>
365         static ParserError generate(VM& vm, Args&& ...args)
366         {
367             DeferGC deferGC(vm.heap);
368             auto bytecodeGenerator = std::make_unique<BytecodeGenerator>(vm, std::forward<Args>(args)...);
369             return bytecodeGenerator->generate(); 
370         }
371
372         bool isArgumentNumber(const Identifier&, int);
373
374         Variable variable(const Identifier&, ThisResolutionType = ThisResolutionType::Local);
375         
376         enum ExistingVariableMode { VerifyExisting, IgnoreExisting };
377         void createVariable(const Identifier&, VarKind, SymbolTable*, ExistingVariableMode = VerifyExisting); // Creates the variable, or asserts that the already-created variable is sufficiently compatible.
378         
379         // Returns the register storing "this"
380         RegisterID* thisRegister() { return &m_thisRegister; }
381         RegisterID* argumentsRegister() { return m_argumentsRegister; }
382         RegisterID* newTarget()
383         {
384             return m_newTargetRegister;
385         }
386
387         RegisterID* scopeRegister() { return m_scopeRegister; }
388
389         RegisterID* generatorRegister() { return m_generatorRegister; }
390
391         RegisterID* promiseCapabilityRegister() { return m_promiseCapabilityRegister; }
392
393         // Returns the next available temporary register. Registers returned by
394         // newTemporary require a modified form of reference counting: any
395         // register with a refcount of 0 is considered "available", meaning that
396         // the next instruction may overwrite it.
397         RegisterID* newTemporary();
398
399         // The same as newTemporary(), but this function returns "suggestion" if
400         // "suggestion" is a temporary. This function is helpful in situations
401         // where you've put "suggestion" in a RefPtr, but you'd like to allow
402         // the next instruction to overwrite it anyway.
403         RegisterID* newTemporaryOr(RegisterID* suggestion) { return suggestion->isTemporary() ? suggestion : newTemporary(); }
404
405         // Functions for handling of dst register
406
407         RegisterID* ignoredResult() { return &m_ignoredResultRegister; }
408
409         // This will be allocated in the temporary region of registers, but it will
410         // not be marked as a temporary. This will ensure that finalDestination() does
411         // not overwrite a block scope variable that it mistakes as a temporary. These
412         // registers can be (and are) reclaimed when the lexical scope they belong to
413         // is no longer on the symbol table stack.
414         RegisterID* newBlockScopeVariable();
415
416         // Returns a place to write intermediate values of an operation
417         // which reuses dst if it is safe to do so.
418         RegisterID* tempDestination(RegisterID* dst)
419         {
420             return (dst && dst != ignoredResult() && dst->isTemporary()) ? dst : newTemporary();
421         }
422
423         // Returns the place to write the final output of an operation.
424         RegisterID* finalDestination(RegisterID* originalDst, RegisterID* tempDst = 0)
425         {
426             if (originalDst && originalDst != ignoredResult())
427                 return originalDst;
428             ASSERT(tempDst != ignoredResult());
429             if (tempDst && tempDst->isTemporary())
430                 return tempDst;
431             return newTemporary();
432         }
433
434         RegisterID* destinationForAssignResult(RegisterID* dst)
435         {
436             if (dst && dst != ignoredResult())
437                 return dst->isTemporary() ? dst : newTemporary();
438             return 0;
439         }
440
441         // Moves src to dst if dst is not null and is different from src, otherwise just returns src.
442         RegisterID* moveToDestinationIfNeeded(RegisterID* dst, RegisterID* src)
443         {
444             return dst == ignoredResult() ? 0 : (dst && dst != src) ? emitMove(dst, src) : src;
445         }
446
447         Ref<LabelScope> newLabelScope(LabelScope::Type, const Identifier* = 0);
448         Ref<Label> newLabel();
449         Ref<Label> newEmittedLabel();
450
451         void emitNode(RegisterID* dst, StatementNode* n)
452         {
453             SetForScope<bool> tailPositionPoisoner(m_inTailPosition, false);
454             return emitNodeInTailPosition(dst, n);
455         }
456
457         void emitNodeInTailPosition(RegisterID* dst, StatementNode* n)
458         {
459             // Node::emitCode assumes that dst, if provided, is either a local or a referenced temporary.
460             ASSERT(!dst || dst == ignoredResult() || !dst->isTemporary() || dst->refCount());
461             if (UNLIKELY(!m_vm->isSafeToRecurse())) {
462                 emitThrowExpressionTooDeepException();
463                 return;
464             }
465             if (UNLIKELY(n->needsDebugHook()))
466                 emitDebugHook(n);
467             n->emitBytecode(*this, dst);
468         }
469
470         void emitNode(StatementNode* n)
471         {
472             emitNode(nullptr, n);
473         }
474
475         void emitNodeInTailPosition(StatementNode* n)
476         {
477             emitNodeInTailPosition(nullptr, n);
478         }
479
480         RegisterID* emitNode(RegisterID* dst, ExpressionNode* n)
481         {
482             SetForScope<bool> tailPositionPoisoner(m_inTailPosition, false);
483             return emitNodeInTailPosition(dst, n);
484         }
485
486         RegisterID* emitNodeInTailPosition(RegisterID* dst, ExpressionNode* n)
487         {
488             // Node::emitCode assumes that dst, if provided, is either a local or a referenced temporary.
489             ASSERT(!dst || dst == ignoredResult() || !dst->isTemporary() || dst->refCount());
490             if (UNLIKELY(!m_vm->isSafeToRecurse()))
491                 return emitThrowExpressionTooDeepException();
492             if (UNLIKELY(n->needsDebugHook()))
493                 emitDebugHook(n);
494             return n->emitBytecode(*this, dst);
495         }
496
497         RegisterID* emitNode(ExpressionNode* n)
498         {
499             return emitNode(nullptr, n);
500         }
501
502         RegisterID* emitNodeInTailPosition(ExpressionNode* n)
503         {
504             return emitNodeInTailPosition(nullptr, n);
505         }
506
507         void emitNodeInConditionContext(ExpressionNode* n, Label& trueTarget, Label& falseTarget, FallThroughMode fallThroughMode)
508         {
509             if (UNLIKELY(!m_vm->isSafeToRecurse())) {
510                 emitThrowExpressionTooDeepException();
511                 return;
512             }
513             n->emitBytecodeInConditionContext(*this, trueTarget, falseTarget, fallThroughMode);
514         }
515
516         void emitExpressionInfo(const JSTextPosition& divot, const JSTextPosition& divotStart, const JSTextPosition& divotEnd)
517         {            
518             ASSERT(divot.offset >= divotStart.offset);
519             ASSERT(divotEnd.offset >= divot.offset);
520
521             int sourceOffset = m_scopeNode->source().startOffset();
522             unsigned firstLine = m_scopeNode->source().firstLine().oneBasedInt();
523
524             int divotOffset = divot.offset - sourceOffset;
525             int startOffset = divot.offset - divotStart.offset;
526             int endOffset = divotEnd.offset - divot.offset;
527
528             unsigned line = divot.line;
529             ASSERT(line >= firstLine);
530             line -= firstLine;
531
532             int lineStart = divot.lineStartOffset;
533             if (lineStart > sourceOffset)
534                 lineStart -= sourceOffset;
535             else
536                 lineStart = 0;
537
538             if (divotOffset < lineStart)
539                 return;
540
541             unsigned column = divotOffset - lineStart;
542
543             unsigned instructionOffset = instructions().size();
544             if (!m_isBuiltinFunction)
545                 m_codeBlock->addExpressionInfo(instructionOffset, divotOffset, startOffset, endOffset, line, column);
546         }
547
548
549         ALWAYS_INLINE bool leftHandSideNeedsCopy(bool rightHasAssignments, bool rightIsPure)
550         {
551             return (m_codeType != FunctionCode || rightHasAssignments) && !rightIsPure;
552         }
553
554         ALWAYS_INLINE RefPtr<RegisterID> emitNodeForLeftHandSide(ExpressionNode* n, bool rightHasAssignments, bool rightIsPure)
555         {
556             if (leftHandSideNeedsCopy(rightHasAssignments, rightIsPure)) {
557                 RefPtr<RegisterID> dst = newTemporary();
558                 emitNode(dst.get(), n);
559                 return dst;
560             }
561
562             return emitNode(n);
563         }
564
565         void hoistSloppyModeFunctionIfNecessary(const Identifier& functionName);
566
567     private:
568         void emitTypeProfilerExpressionInfo(const JSTextPosition& startDivot, const JSTextPosition& endDivot);
569     public:
570
571         // This doesn't emit expression info. If using this, make sure you shouldn't be emitting text offset.
572         void emitProfileType(RegisterID* registerToProfile, ProfileTypeBytecodeFlag); 
573         // These variables are associated with variables in a program. They could be Locals, LocalClosureVar, or ClosureVar.
574         void emitProfileType(RegisterID* registerToProfile, const Variable&, const JSTextPosition& startDivot, const JSTextPosition& endDivot);
575
576         void emitProfileType(RegisterID* registerToProfile, ProfileTypeBytecodeFlag, const JSTextPosition& startDivot, const JSTextPosition& endDivot);
577         // These are not associated with variables and don't have a global id.
578         void emitProfileType(RegisterID* registerToProfile, const JSTextPosition& startDivot, const JSTextPosition& endDivot);
579
580         void emitProfileControlFlow(int);
581         
582         RegisterID* emitLoadArrowFunctionLexicalEnvironment(const Identifier&);
583         RegisterID* ensureThis();
584         void emitLoadThisFromArrowFunctionLexicalEnvironment();
585         RegisterID* emitLoadNewTargetFromArrowFunctionLexicalEnvironment();
586
587         RegisterID* emitLoad(RegisterID* dst, bool);
588         RegisterID* emitLoad(RegisterID* dst, const Identifier&);
589         RegisterID* emitLoad(RegisterID* dst, JSValue, SourceCodeRepresentation = SourceCodeRepresentation::Other);
590         RegisterID* emitLoadGlobalObject(RegisterID* dst);
591
592         RegisterID* emitUnaryOp(OpcodeID, RegisterID* dst, RegisterID* src);
593         RegisterID* emitUnaryOp(OpcodeID, RegisterID* dst, RegisterID* src, OperandTypes);
594         RegisterID* emitUnaryOpProfiled(OpcodeID, RegisterID* dst, RegisterID* src);
595         RegisterID* emitBinaryOp(OpcodeID, RegisterID* dst, RegisterID* src1, RegisterID* src2, OperandTypes);
596         RegisterID* emitEqualityOp(OpcodeID, RegisterID* dst, RegisterID* src1, RegisterID* src2);
597         RegisterID* emitUnaryNoDstOp(OpcodeID, RegisterID* src);
598
599         RegisterID* emitCreateThis(RegisterID* dst);
600         void emitTDZCheck(RegisterID* target);
601         bool needsTDZCheck(const Variable&);
602         void emitTDZCheckIfNecessary(const Variable&, RegisterID* target, RegisterID* scope);
603         void liftTDZCheckIfPossible(const Variable&);
604         RegisterID* emitNewObject(RegisterID* dst);
605         RegisterID* emitNewArray(RegisterID* dst, ElementNode*, unsigned length); // stops at first elision
606         RegisterID* emitNewArrayWithSpread(RegisterID* dst, ElementNode*);
607         RegisterID* emitNewArrayWithSize(RegisterID* dst, RegisterID* length);
608
609         RegisterID* emitNewFunction(RegisterID* dst, FunctionMetadataNode*);
610         RegisterID* emitNewFunctionExpression(RegisterID* dst, FuncExprNode*);
611         RegisterID* emitNewDefaultConstructor(RegisterID* dst, ConstructorKind, const Identifier& name, const Identifier& ecmaName, const SourceCode& classSource);
612         RegisterID* emitNewArrowFunctionExpression(RegisterID*, ArrowFuncExprNode*);
613         RegisterID* emitNewMethodDefinition(RegisterID* dst, MethodDefinitionNode*);
614         RegisterID* emitNewRegExp(RegisterID* dst, RegExp*);
615
616         void emitSetFunctionNameIfNeeded(ExpressionNode* valueNode, RegisterID* value, RegisterID* name);
617
618         RegisterID* emitMoveLinkTimeConstant(RegisterID* dst, LinkTimeConstant);
619         RegisterID* emitMoveEmptyValue(RegisterID* dst);
620         RegisterID* emitMove(RegisterID* dst, RegisterID* src);
621
622         RegisterID* emitToNumber(RegisterID* dst, RegisterID* src) { return emitUnaryOpProfiled(op_to_number, dst, src); }
623         RegisterID* emitToString(RegisterID* dst, RegisterID* src) { return emitUnaryOp(op_to_string, dst, src); }
624         RegisterID* emitInc(RegisterID* srcDst);
625         RegisterID* emitDec(RegisterID* srcDst);
626
627         RegisterID* emitOverridesHasInstance(RegisterID* dst, RegisterID* constructor, RegisterID* hasInstanceValue);
628         RegisterID* emitInstanceOf(RegisterID* dst, RegisterID* value, RegisterID* basePrototype);
629         RegisterID* emitInstanceOfCustom(RegisterID* dst, RegisterID* value, RegisterID* constructor, RegisterID* hasInstanceValue);
630         RegisterID* emitTypeOf(RegisterID* dst, RegisterID* src) { return emitUnaryOp(op_typeof, dst, src); }
631         RegisterID* emitIn(RegisterID* dst, RegisterID* property, RegisterID* base);
632
633         RegisterID* emitTryGetById(RegisterID* dst, RegisterID* base, const Identifier& property);
634         RegisterID* emitGetById(RegisterID* dst, RegisterID* base, const Identifier& property);
635         RegisterID* emitGetById(RegisterID* dst, RegisterID* base, RegisterID* thisVal, const Identifier& property);
636         RegisterID* emitPutById(RegisterID* base, const Identifier& property, RegisterID* value);
637         RegisterID* emitPutById(RegisterID* base, RegisterID* thisValue, const Identifier& property, RegisterID* value);
638         RegisterID* emitDirectPutById(RegisterID* base, const Identifier& property, RegisterID* value, PropertyNode::PutType);
639         RegisterID* emitDeleteById(RegisterID* dst, RegisterID* base, const Identifier&);
640         RegisterID* emitGetByVal(RegisterID* dst, RegisterID* base, RegisterID* property);
641         RegisterID* emitGetByVal(RegisterID* dst, RegisterID* base, RegisterID* thisValue, RegisterID* property);
642         RegisterID* emitPutByVal(RegisterID* base, RegisterID* property, RegisterID* value);
643         RegisterID* emitPutByVal(RegisterID* base, RegisterID* thisValue, RegisterID* property, RegisterID* value);
644         RegisterID* emitDirectPutByVal(RegisterID* base, RegisterID* property, RegisterID* value);
645         RegisterID* emitDeleteByVal(RegisterID* dst, RegisterID* base, RegisterID* property);
646         RegisterID* emitPutByIndex(RegisterID* base, unsigned index, RegisterID* value);
647
648         RegisterID* emitAssert(RegisterID* condition, int line);
649
650         void emitPutGetterById(RegisterID* base, const Identifier& property, unsigned propertyDescriptorOptions, RegisterID* getter);
651         void emitPutSetterById(RegisterID* base, const Identifier& property, unsigned propertyDescriptorOptions, RegisterID* setter);
652         void emitPutGetterSetter(RegisterID* base, const Identifier& property, unsigned attributes, RegisterID* getter, RegisterID* setter);
653         void emitPutGetterByVal(RegisterID* base, RegisterID* property, unsigned propertyDescriptorOptions, RegisterID* getter);
654         void emitPutSetterByVal(RegisterID* base, RegisterID* property, unsigned propertyDescriptorOptions, RegisterID* setter);
655
656         RegisterID* emitGetArgument(RegisterID* dst, int32_t index);
657
658         // Initialize object with generator fields (@generatorThis, @generatorNext, @generatorState, @generatorFrame)
659         void emitPutGeneratorFields(RegisterID* nextFunction);
660
661         ExpectedFunction expectedFunctionForIdentifier(const Identifier&);
662         RegisterID* emitCall(RegisterID* dst, RegisterID* func, ExpectedFunction, CallArguments&, const JSTextPosition& divot, const JSTextPosition& divotStart, const JSTextPosition& divotEnd, DebuggableCall);
663         RegisterID* emitCallInTailPosition(RegisterID* dst, RegisterID* func, ExpectedFunction, CallArguments&, const JSTextPosition& divot, const JSTextPosition& divotStart, const JSTextPosition& divotEnd, DebuggableCall);
664         RegisterID* emitCallEval(RegisterID* dst, RegisterID* func, CallArguments&, const JSTextPosition& divot, const JSTextPosition& divotStart, const JSTextPosition& divotEnd, DebuggableCall);
665         RegisterID* emitCallVarargs(RegisterID* dst, RegisterID* func, RegisterID* thisRegister, RegisterID* arguments, RegisterID* firstFreeRegister, int32_t firstVarArgOffset, const JSTextPosition& divot, const JSTextPosition& divotStart, const JSTextPosition& divotEnd, DebuggableCall);
666         RegisterID* emitCallVarargsInTailPosition(RegisterID* dst, RegisterID* func, RegisterID* thisRegister, RegisterID* arguments, RegisterID* firstFreeRegister, int32_t firstVarArgOffset, const JSTextPosition& divot, const JSTextPosition& divotStart, const JSTextPosition& divotEnd, DebuggableCall);
667         RegisterID* emitCallForwardArgumentsInTailPosition(RegisterID* dst, RegisterID* func, RegisterID* thisRegister, RegisterID* firstFreeRegister, int32_t firstVarArgOffset, const JSTextPosition& divot, const JSTextPosition& divotStart, const JSTextPosition& divotEnd, DebuggableCall);
668
669         enum PropertyDescriptorOption {
670             PropertyConfigurable = 1,
671             PropertyWritable     = 1 << 1,
672             PropertyEnumerable   = 1 << 2,
673         };
674         void emitCallDefineProperty(RegisterID* newObj, RegisterID* propertyNameRegister,
675             RegisterID* valueRegister, RegisterID* getterRegister, RegisterID* setterRegister, unsigned options, const JSTextPosition&);
676
677         void emitEnumeration(ThrowableExpressionData* enumerationNode, ExpressionNode* subjectNode, const std::function<void(BytecodeGenerator&, RegisterID*)>& callBack, ForOfNode* = nullptr, RegisterID* forLoopSymbolTable = nullptr);
678
679         RegisterID* emitGetTemplateObject(RegisterID* dst, TaggedTemplateNode*);
680         RegisterID* emitGetGlobalPrivate(RegisterID* dst, const Identifier& property);
681
682         enum class ReturnFrom { Normal, Finally };
683         RegisterID* emitReturn(RegisterID* src, ReturnFrom = ReturnFrom::Normal);
684         RegisterID* emitEnd(RegisterID* src) { return emitUnaryNoDstOp(op_end, src); }
685
686         RegisterID* emitConstruct(RegisterID* dst, RegisterID* func, ExpectedFunction, CallArguments&, const JSTextPosition& divot, const JSTextPosition& divotStart, const JSTextPosition& divotEnd);
687         RegisterID* emitStrcat(RegisterID* dst, RegisterID* src, int count);
688         void emitToPrimitive(RegisterID* dst, RegisterID* src);
689
690         ResolveType resolveType();
691         RegisterID* emitResolveConstantLocal(RegisterID* dst, const Variable&);
692         RegisterID* emitResolveScope(RegisterID* dst, const Variable&);
693         RegisterID* emitGetFromScope(RegisterID* dst, RegisterID* scope, const Variable&, ResolveMode);
694         RegisterID* emitPutToScope(RegisterID* scope, const Variable&, RegisterID* value, ResolveMode, InitializationMode);
695
696         RegisterID* emitResolveScopeForHoistingFuncDeclInEval(RegisterID* dst, const Identifier&);
697
698         RegisterID* initializeVariable(const Variable&, RegisterID* value);
699
700         void emitLabel(Label&);
701         void emitLoopHint();
702         void emitJump(Label& target);
703         void emitJumpIfTrue(RegisterID* cond, Label& target);
704         void emitJumpIfFalse(RegisterID* cond, Label& target);
705         void emitJumpIfNotFunctionCall(RegisterID* cond, Label& target);
706         void emitJumpIfNotFunctionApply(RegisterID* cond, Label& target);
707
708         void emitEnter();
709         void emitCheckTraps();
710
711         RegisterID* emitHasIndexedProperty(RegisterID* dst, RegisterID* base, RegisterID* propertyName);
712         RegisterID* emitHasStructureProperty(RegisterID* dst, RegisterID* base, RegisterID* propertyName, RegisterID* enumerator);
713         RegisterID* emitHasGenericProperty(RegisterID* dst, RegisterID* base, RegisterID* propertyName);
714         RegisterID* emitGetPropertyEnumerator(RegisterID* dst, RegisterID* base);
715         RegisterID* emitGetEnumerableLength(RegisterID* dst, RegisterID* base);
716         RegisterID* emitGetStructurePropertyEnumerator(RegisterID* dst, RegisterID* base, RegisterID* length);
717         RegisterID* emitGetGenericPropertyEnumerator(RegisterID* dst, RegisterID* base, RegisterID* length, RegisterID* structureEnumerator);
718         RegisterID* emitEnumeratorStructurePropertyName(RegisterID* dst, RegisterID* enumerator, RegisterID* index);
719         RegisterID* emitEnumeratorGenericPropertyName(RegisterID* dst, RegisterID* enumerator, RegisterID* index);
720         RegisterID* emitToIndexString(RegisterID* dst, RegisterID* index);
721
722         RegisterID* emitIsCellWithType(RegisterID* dst, RegisterID* src, JSType);
723         RegisterID* emitIsJSArray(RegisterID* dst, RegisterID* src) { return emitIsCellWithType(dst, src, ArrayType); }
724         RegisterID* emitIsProxyObject(RegisterID* dst, RegisterID* src) { return emitIsCellWithType(dst, src, ProxyObjectType); }
725         RegisterID* emitIsRegExpObject(RegisterID* dst, RegisterID* src) { return emitIsCellWithType(dst, src, RegExpObjectType); }
726         RegisterID* emitIsMap(RegisterID* dst, RegisterID* src) { return emitIsCellWithType(dst, src, JSMapType); }
727         RegisterID* emitIsSet(RegisterID* dst, RegisterID* src) { return emitIsCellWithType(dst, src, JSSetType); }
728         RegisterID* emitIsObject(RegisterID* dst, RegisterID* src);
729         RegisterID* emitIsNumber(RegisterID* dst, RegisterID* src);
730         RegisterID* emitIsUndefined(RegisterID* dst, RegisterID* src);
731         RegisterID* emitIsEmpty(RegisterID* dst, RegisterID* src);
732         RegisterID* emitIsDerivedArray(RegisterID* dst, RegisterID* src) { return emitIsCellWithType(dst, src, DerivedArrayType); }
733         void emitRequireObjectCoercible(RegisterID* value, const String& error);
734
735         RegisterID* emitIteratorNext(RegisterID* dst, RegisterID* iterator, const ThrowableExpressionData* node);
736         RegisterID* emitIteratorNextWithValue(RegisterID* dst, RegisterID* iterator, RegisterID* value, const ThrowableExpressionData* node);
737         void emitIteratorClose(RegisterID* iterator, const ThrowableExpressionData* node);
738
739         RegisterID* emitRestParameter(RegisterID* result, unsigned numParametersToSkip);
740
741         bool emitReadOnlyExceptionIfNeeded(const Variable&);
742
743         // Start a try block. 'start' must have been emitted.
744         TryData* pushTry(Label& start, Label& handlerLabel, HandlerType);
745         // End a try block. 'end' must have been emitted.
746         void popTry(TryData*, Label& end);
747         void emitCatch(RegisterID* exceptionRegister, RegisterID* thrownValueRegister);
748
749     private:
750         static const int CurrentLexicalScopeIndex = -2;
751         static const int OutermostLexicalScopeIndex = -1;
752
753         int currentLexicalScopeIndex() const
754         {
755             int size = static_cast<int>(m_lexicalScopeStack.size());
756             ASSERT(static_cast<size_t>(size) == m_lexicalScopeStack.size());
757             ASSERT(size >= 0);
758             if (!size)
759                 return OutermostLexicalScopeIndex;
760             return size - 1;
761         }
762
763     public:
764         void restoreScopeRegister();
765         void restoreScopeRegister(int lexicalScopeIndex);
766
767         int labelScopeDepthToLexicalScopeIndex(int labelScopeDepth);
768
769         void emitThrow(RegisterID* exc)
770         { 
771             m_usesExceptions = true;
772             emitUnaryNoDstOp(op_throw, exc);
773         }
774
775         void emitThrowStaticError(ErrorType, RegisterID*);
776         void emitThrowStaticError(ErrorType, const Identifier& message);
777         void emitThrowReferenceError(const String& message);
778         void emitThrowTypeError(const String& message);
779         void emitThrowTypeError(const Identifier& message);
780         void emitThrowRangeError(const Identifier& message);
781         void emitThrowOutOfMemoryError();
782
783         void emitPushCatchScope(VariableEnvironment&);
784         void emitPopCatchScope(VariableEnvironment&);
785
786         void emitGetScope();
787         RegisterID* emitPushWithScope(RegisterID* objectScope);
788         void emitPopWithScope();
789         void emitPutThisToArrowFunctionContextScope();
790         void emitPutNewTargetToArrowFunctionContextScope();
791         void emitPutDerivedConstructorToArrowFunctionContextScope();
792         RegisterID* emitLoadDerivedConstructorFromArrowFunctionLexicalEnvironment();
793
794         void emitDebugHook(DebugHookType, const JSTextPosition&);
795         void emitDebugHook(DebugHookType, unsigned line, unsigned charOffset, unsigned lineStart);
796         void emitDebugHook(StatementNode*);
797         void emitDebugHook(ExpressionNode*);
798         void emitWillLeaveCallFrameDebugHook();
799
800         class CompletionRecordScope {
801         public:
802             CompletionRecordScope(BytecodeGenerator& generator, bool needCompletionRecordRegisters = true)
803                 : m_generator(generator)
804             {
805                 if (needCompletionRecordRegisters && m_generator.allocateCompletionRecordRegisters())
806                     m_needToReleaseOnDestruction = true;
807             }
808             ~CompletionRecordScope()
809             {
810                 if (m_needToReleaseOnDestruction)
811                     m_generator.releaseCompletionRecordRegisters();
812             }
813
814         private:
815             BytecodeGenerator& m_generator;
816             bool m_needToReleaseOnDestruction { false };
817         };
818
819         RegisterID* completionTypeRegister() const
820         {
821             ASSERT(m_completionTypeRegister);
822             return m_completionTypeRegister.get();
823         }
824         RegisterID* completionValueRegister() const
825         {
826             ASSERT(m_completionValueRegister);
827             return m_completionValueRegister.get();
828         }
829
830         void emitSetCompletionType(CompletionType type)
831         {
832             emitLoad(completionTypeRegister(), JSValue(static_cast<int>(type)));
833         }
834         void emitSetCompletionValue(RegisterID* reg)
835         {
836             emitMove(completionValueRegister(), reg);
837         }
838
839         void emitJumpIf(OpcodeID compareOpcode, RegisterID* completionTypeRegister, CompletionType, Label& jumpTarget);
840
841         bool emitJumpViaFinallyIfNeeded(int targetLabelScopeDepth, Label& jumpTarget);
842         bool emitReturnViaFinallyIfNeeded(RegisterID* returnRegister);
843         void emitFinallyCompletion(FinallyContext&, RegisterID* completionTypeRegister, Label& normalCompletionLabel);
844
845     private:
846         bool allocateCompletionRecordRegisters();
847         void releaseCompletionRecordRegisters();
848
849     public:
850         FinallyContext* pushFinallyControlFlowScope(Label& finallyLabel);
851         FinallyContext popFinallyControlFlowScope();
852
853         void pushIndexedForInScope(RegisterID* local, RegisterID* index);
854         void popIndexedForInScope(RegisterID* local);
855         void pushStructureForInScope(RegisterID* local, RegisterID* index, RegisterID* property, RegisterID* enumerator);
856         void popStructureForInScope(RegisterID* local);
857         void invalidateForInContextForLocal(RegisterID* local);
858
859         RefPtr<LabelScope> breakTarget(const Identifier&);
860         RefPtr<LabelScope> continueTarget(const Identifier&);
861
862         void beginSwitch(RegisterID*, SwitchInfo::SwitchType);
863         void endSwitch(uint32_t clauseCount, const Vector<Ref<Label>, 8>&, ExpressionNode**, Label& defaultLabel, int32_t min, int32_t range);
864
865         void emitYieldPoint(RegisterID*);
866
867         void emitGeneratorStateLabel();
868         void emitGeneratorStateChange(int32_t state);
869         RegisterID* emitYield(RegisterID* argument);
870         RegisterID* emitDelegateYield(RegisterID* argument, ThrowableExpressionData*);
871         RegisterID* generatorStateRegister() { return &m_parameters[static_cast<int32_t>(JSGeneratorFunction::GeneratorArgument::State)]; }
872         RegisterID* generatorValueRegister() { return &m_parameters[static_cast<int32_t>(JSGeneratorFunction::GeneratorArgument::Value)]; }
873         RegisterID* generatorResumeModeRegister() { return &m_parameters[static_cast<int32_t>(JSGeneratorFunction::GeneratorArgument::ResumeMode)]; }
874         RegisterID* generatorFrameRegister() { return &m_parameters[static_cast<int32_t>(JSGeneratorFunction::GeneratorArgument::Frame)]; }
875
876         CodeType codeType() const { return m_codeType; }
877
878         bool shouldEmitDebugHooks() { return m_shouldEmitDebugHooks; }
879         
880         bool isStrictMode() const { return m_codeBlock->isStrictMode(); }
881
882         SourceParseMode parseMode() const { return m_codeBlock->parseMode(); }
883         
884         bool isBuiltinFunction() const { return m_isBuiltinFunction; }
885
886         OpcodeID lastOpcodeID() const { return m_lastOpcodeID; }
887         
888         bool isDerivedConstructorContext() { return m_derivedContextType == DerivedContextType::DerivedConstructorContext; }
889         bool isDerivedClassContext() { return m_derivedContextType == DerivedContextType::DerivedMethodContext; }
890         bool isArrowFunction() { return m_codeBlock->isArrowFunction(); }
891
892         enum class TDZCheckOptimization { Optimize, DoNotOptimize };
893         enum class NestedScopeType { IsNested, IsNotNested };
894     private:
895         enum class TDZRequirement { UnderTDZ, NotUnderTDZ };
896         enum class ScopeType { CatchScope, LetConstScope, FunctionNameScope };
897         enum class ScopeRegisterType { Var, Block };
898         void pushLexicalScopeInternal(VariableEnvironment&, TDZCheckOptimization, NestedScopeType, RegisterID** constantSymbolTableResult, TDZRequirement, ScopeType, ScopeRegisterType);
899         void initializeBlockScopedFunctions(VariableEnvironment&, FunctionStack&, RegisterID* constantSymbolTable);
900         void popLexicalScopeInternal(VariableEnvironment&);
901         template<typename LookUpVarKindFunctor>
902         bool instantiateLexicalVariables(const VariableEnvironment&, SymbolTable*, ScopeRegisterType, LookUpVarKindFunctor);
903         void emitPrefillStackTDZVariables(const VariableEnvironment&, SymbolTable*);
904         void emitPopScope(RegisterID* dst, RegisterID* scope);
905         RegisterID* emitGetParentScope(RegisterID* dst, RegisterID* scope);
906         void emitPushFunctionNameScope(const Identifier& property, RegisterID* value, bool isCaptured);
907         void emitNewFunctionExpressionCommon(RegisterID*, FunctionMetadataNode*);
908         
909         bool isNewTargetUsedInInnerArrowFunction();
910         bool isArgumentsUsedInInnerArrowFunction();
911
912     public:
913         bool isSuperUsedInInnerArrowFunction();
914         bool isSuperCallUsedInInnerArrowFunction();
915         bool isThisUsedInInnerArrowFunction();
916         void pushLexicalScope(VariableEnvironmentNode*, TDZCheckOptimization, NestedScopeType = NestedScopeType::IsNotNested, RegisterID** constantSymbolTableResult = nullptr, bool shouldInitializeBlockScopedFunctions = true);
917         void popLexicalScope(VariableEnvironmentNode*);
918         void prepareLexicalScopeForNextForLoopIteration(VariableEnvironmentNode*, RegisterID* loopSymbolTable);
919         int labelScopeDepth() const;
920
921     private:
922         ParserError generate();
923         void reclaimFreeRegisters();
924         Variable variableForLocalEntry(const Identifier&, const SymbolTableEntry&, int symbolTableConstantIndex, bool isLexicallyScoped);
925
926         void emitOpcode(OpcodeID);
927         UnlinkedArrayAllocationProfile newArrayAllocationProfile();
928         UnlinkedObjectAllocationProfile newObjectAllocationProfile();
929         UnlinkedArrayProfile newArrayProfile();
930         UnlinkedValueProfile emitProfiledOpcode(OpcodeID);
931         int kill(RegisterID* dst)
932         {
933             int index = dst->index();
934             m_staticPropertyAnalyzer.kill(index);
935             return index;
936         }
937
938         void retrieveLastBinaryOp(int& dstIndex, int& src1Index, int& src2Index);
939         void retrieveLastUnaryOp(int& dstIndex, int& srcIndex);
940         ALWAYS_INLINE void rewindBinaryOp();
941         ALWAYS_INLINE void rewindUnaryOp();
942
943         void allocateCalleeSaveSpace();
944         void allocateAndEmitScope();
945
946         typedef HashMap<double, JSValue> NumberMap;
947         typedef HashMap<UniquedStringImpl*, JSString*, IdentifierRepHash> IdentifierStringMap;
948         typedef HashMap<Ref<TemplateRegistryKey>, RegisterID*> TemplateRegistryKeyMap;
949         
950         // Helper for emitCall() and emitConstruct(). This works because the set of
951         // expected functions have identical behavior for both call and construct
952         // (i.e. "Object()" is identical to "new Object()").
953         ExpectedFunction emitExpectedFunctionSnippet(RegisterID* dst, RegisterID* func, ExpectedFunction, CallArguments&, Label& done);
954         
955         RegisterID* emitCall(OpcodeID, RegisterID* dst, RegisterID* func, ExpectedFunction, CallArguments&, const JSTextPosition& divot, const JSTextPosition& divotStart, const JSTextPosition& divotEnd, DebuggableCall);
956
957         RegisterID* newRegister();
958
959         // Adds an anonymous local var slot. To give this slot a name, add it to symbolTable().
960         RegisterID* addVar()
961         {
962             ++m_codeBlock->m_numVars;
963             RegisterID* result = newRegister();
964             ASSERT(VirtualRegister(result->index()).toLocal() == m_codeBlock->m_numVars - 1);
965             result->ref(); // We should never free this slot.
966             return result;
967         }
968
969         // Initializes the stack form the parameter; does nothing for the symbol table.
970         RegisterID* initializeNextParameter();
971         UniquedStringImpl* visibleNameForParameter(DestructuringPatternNode*);
972         
973         RegisterID& registerFor(VirtualRegister reg)
974         {
975             if (reg.isLocal())
976                 return m_calleeLocals[reg.toLocal()];
977
978             if (reg.offset() == CallFrameSlot::callee)
979                 return m_calleeRegister;
980
981             ASSERT(m_parameters.size());
982             return m_parameters[reg.toArgument()];
983         }
984
985         bool hasConstant(const Identifier&) const;
986         unsigned addConstant(const Identifier&);
987         RegisterID* addConstantValue(JSValue, SourceCodeRepresentation = SourceCodeRepresentation::Other);
988         RegisterID* addConstantEmptyValue();
989         unsigned addRegExp(RegExp*);
990
991         unsigned addConstantBuffer(unsigned length);
992         
993         UnlinkedFunctionExecutable* makeFunction(FunctionMetadataNode* metadata)
994         {
995             DerivedContextType newDerivedContextType = DerivedContextType::None;
996
997             if (SourceParseModeSet(SourceParseMode::ArrowFunctionMode, SourceParseMode::AsyncArrowFunctionMode).contains(metadata->parseMode())) {
998                 if (constructorKind() == ConstructorKind::Extends || isDerivedConstructorContext())
999                     newDerivedContextType = DerivedContextType::DerivedConstructorContext;
1000                 else if (m_codeBlock->isClassContext() || isDerivedClassContext())
1001                     newDerivedContextType = DerivedContextType::DerivedMethodContext;
1002             }
1003
1004             VariableEnvironment variablesUnderTDZ;
1005             getVariablesUnderTDZ(variablesUnderTDZ);
1006
1007             // FIXME: These flags, ParserModes and propagation to XXXCodeBlocks should be reorganized.
1008             // https://bugs.webkit.org/show_bug.cgi?id=151547
1009             SourceParseMode parseMode = metadata->parseMode();
1010             ConstructAbility constructAbility = constructAbilityForParseMode(parseMode);
1011             if (parseMode == SourceParseMode::MethodMode && metadata->constructorKind() != ConstructorKind::None)
1012                 constructAbility = ConstructAbility::CanConstruct;
1013
1014             return UnlinkedFunctionExecutable::create(m_vm, m_scopeNode->source(), metadata, isBuiltinFunction() ? UnlinkedBuiltinFunction : UnlinkedNormalFunction, constructAbility, scriptMode(), variablesUnderTDZ, newDerivedContextType);
1015         }
1016
1017         void getVariablesUnderTDZ(VariableEnvironment&);
1018
1019         RegisterID* emitConstructVarargs(RegisterID* dst, RegisterID* func, RegisterID* thisRegister, RegisterID* arguments, RegisterID* firstFreeRegister, int32_t firstVarArgOffset, const JSTextPosition& divot, const JSTextPosition& divotStart, const JSTextPosition& divotEnd, DebuggableCall);
1020         RegisterID* emitCallVarargs(OpcodeID, RegisterID* dst, RegisterID* func, RegisterID* thisRegister, RegisterID* arguments, RegisterID* firstFreeRegister, int32_t firstVarArgOffset, const JSTextPosition& divot, const JSTextPosition& divotStart, const JSTextPosition& divotEnd, DebuggableCall);
1021         
1022         void emitLogShadowChickenPrologueIfNecessary();
1023         void emitLogShadowChickenTailIfNecessary();
1024
1025         void initializeParameters(FunctionParameters&);
1026         void initializeVarLexicalEnvironment(int symbolTableConstantIndex, SymbolTable* functionSymbolTable, bool hasCapturedVariables);
1027         void initializeDefaultParameterValuesAndSetupFunctionScopeStack(FunctionParameters&, bool isSimpleParameterList, FunctionNode*, SymbolTable*, int symbolTableConstantIndex, const std::function<bool (UniquedStringImpl*)>& captures, bool shouldCreateArgumentsVariableInParameterScope);
1028         void initializeArrowFunctionContextScopeIfNeeded(SymbolTable* functionSymbolTable = nullptr, bool canReuseLexicalEnvironment = false);
1029         bool needsDerivedConstructorInArrowFunctionLexicalEnvironment();
1030
1031     public:
1032         JSString* addStringConstant(const Identifier&);
1033         RegisterID* addTemplateRegistryKeyConstant(Ref<TemplateRegistryKey>&&);
1034
1035         Vector<UnlinkedInstruction, 0, UnsafeVectorOverflow>& instructions() { return m_instructions; }
1036
1037         RegisterID* emitThrowExpressionTooDeepException();
1038
1039     private:
1040         Vector<UnlinkedInstruction, 0, UnsafeVectorOverflow> m_instructions;
1041
1042         bool m_shouldEmitDebugHooks;
1043
1044         struct LexicalScopeStackEntry {
1045             SymbolTable* m_symbolTable;
1046             RegisterID* m_scope;
1047             bool m_isWithScope;
1048             int m_symbolTableConstantIndex;
1049         };
1050         Vector<LexicalScopeStackEntry> m_lexicalScopeStack;
1051         enum class TDZNecessityLevel {
1052             NotNeeded,
1053             Optimize,
1054             DoNotOptimize
1055         };
1056         typedef HashMap<RefPtr<UniquedStringImpl>, TDZNecessityLevel, IdentifierRepHash> TDZMap;
1057         Vector<TDZMap> m_TDZStack;
1058         std::optional<size_t> m_varScopeLexicalScopeStackIndex;
1059         void pushTDZVariables(const VariableEnvironment&, TDZCheckOptimization, TDZRequirement);
1060
1061         ScopeNode* const m_scopeNode;
1062         Strong<UnlinkedCodeBlock> m_codeBlock;
1063
1064         // Some of these objects keep pointers to one another. They are arranged
1065         // to ensure a sane destruction order that avoids references to freed memory.
1066         HashSet<RefPtr<UniquedStringImpl>, IdentifierRepHash> m_functions;
1067         RegisterID m_ignoredResultRegister;
1068         RegisterID m_thisRegister;
1069         RegisterID m_calleeRegister;
1070         RegisterID* m_scopeRegister { nullptr };
1071         RegisterID* m_topMostScope { nullptr };
1072         RegisterID* m_argumentsRegister { nullptr };
1073         RegisterID* m_lexicalEnvironmentRegister { nullptr };
1074         RegisterID* m_generatorRegister { nullptr };
1075         RegisterID* m_emptyValueRegister { nullptr };
1076         RegisterID* m_globalObjectRegister { nullptr };
1077         RegisterID* m_newTargetRegister { nullptr };
1078         RegisterID* m_isDerivedConstuctor { nullptr };
1079         RegisterID* m_linkTimeConstantRegisters[LinkTimeConstantCount];
1080         RegisterID* m_arrowFunctionContextLexicalEnvironmentRegister { nullptr };
1081         RegisterID* m_promiseCapabilityRegister { nullptr };
1082
1083         RefPtr<RegisterID> m_completionTypeRegister;
1084         RefPtr<RegisterID> m_completionValueRegister;
1085
1086         FinallyContext* m_currentFinallyContext { nullptr };
1087
1088         SegmentedVector<RegisterID*, 16> m_localRegistersForCalleeSaveRegisters;
1089         SegmentedVector<RegisterID, 32> m_constantPoolRegisters;
1090         SegmentedVector<RegisterID, 32> m_calleeLocals;
1091         SegmentedVector<RegisterID, 32> m_parameters;
1092         SegmentedVector<Label, 32> m_labels;
1093         SegmentedVector<LabelScope, 32> m_labelScopes;
1094         unsigned m_finallyDepth { 0 };
1095         int m_localScopeDepth { 0 };
1096         const CodeType m_codeType;
1097
1098         int localScopeDepth() const;
1099         void pushLocalControlFlowScope();
1100         void popLocalControlFlowScope();
1101
1102         // FIXME: Restore overflow checking with UnsafeVectorOverflow once SegmentVector supports it.
1103         // https://bugs.webkit.org/show_bug.cgi?id=165980
1104         SegmentedVector<ControlFlowScope, 16> m_controlFlowScopeStack;
1105         Vector<SwitchInfo> m_switchContextStack;
1106         Vector<Ref<ForInContext>> m_forInContextStack;
1107         Vector<TryContext> m_tryContextStack;
1108         unsigned m_yieldPoints { 0 };
1109
1110         Strong<SymbolTable> m_generatorFrameSymbolTable;
1111         int m_generatorFrameSymbolTableIndex { 0 };
1112
1113         enum FunctionVariableType : uint8_t { NormalFunctionVariable, TopLevelFunctionVariable };
1114         Vector<std::pair<FunctionMetadataNode*, FunctionVariableType>> m_functionsToInitialize;
1115         bool m_needToInitializeArguments { false };
1116         RestParameterNode* m_restParameter { nullptr };
1117         
1118         Vector<TryRange> m_tryRanges;
1119         SegmentedVector<TryData, 8> m_tryData;
1120
1121         int m_nextConstantOffset { 0 };
1122
1123         typedef HashMap<FunctionMetadataNode*, unsigned> FunctionOffsetMap;
1124         FunctionOffsetMap m_functionOffsets;
1125         
1126         // Constant pool
1127         IdentifierMap m_identifierMap;
1128
1129         typedef HashMap<EncodedJSValueWithRepresentation, unsigned, EncodedJSValueWithRepresentationHash, EncodedJSValueWithRepresentationHashTraits> JSValueMap;
1130         JSValueMap m_jsValueMap;
1131         IdentifierStringMap m_stringMap;
1132         TemplateRegistryKeyMap m_templateRegistryKeyMap;
1133
1134         StaticPropertyAnalyzer m_staticPropertyAnalyzer { &m_instructions };
1135
1136         VM* m_vm;
1137
1138         OpcodeID m_lastOpcodeID = op_end;
1139 #ifndef NDEBUG
1140         size_t m_lastOpcodePosition { 0 };
1141 #endif
1142
1143         bool m_usesExceptions { false };
1144         bool m_expressionTooDeep { false };
1145         bool m_isBuiltinFunction { false };
1146         bool m_usesNonStrictEval { false };
1147         bool m_inTailPosition { false };
1148         bool m_needsToUpdateArrowFunctionContext;
1149         DerivedContextType m_derivedContextType { DerivedContextType::None };
1150     };
1151
1152 } // namespace JSC
1153
1154 namespace WTF {
1155
1156 void printInternal(PrintStream&, JSC::Variable::VariableKind);
1157
1158 } // namespace WTF