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