[ES6] Implement LLInt/Baseline Support for ES6 Generators and enable this feature
[WebKit-https.git] / Source / JavaScriptCore / bytecode / CodeBlock.cpp
1 /*
2  * Copyright (C) 2008-2010, 2012-2015 Apple Inc. All rights reserved.
3  * Copyright (C) 2008 Cameron Zwarich <cwzwarich@uwaterloo.ca>
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  *
9  * 1.  Redistributions of source code must retain the above copyright
10  *     notice, this list of conditions and the following disclaimer.
11  * 2.  Redistributions in binary form must reproduce the above copyright
12  *     notice, this list of conditions and the following disclaimer in the
13  *     documentation and/or other materials provided with the distribution.
14  * 3.  Neither the name of Apple Inc. ("Apple") nor the names of
15  *     its contributors may be used to endorse or promote products derived
16  *     from this software without specific prior written permission.
17  *
18  * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
19  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
20  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
21  * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
22  * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
23  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
24  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
25  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
27  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28  */
29
30 #include "config.h"
31 #include "CodeBlock.h"
32
33 #include "BasicBlockLocation.h"
34 #include "BytecodeGenerator.h"
35 #include "BytecodeUseDef.h"
36 #include "CallLinkStatus.h"
37 #include "DFGCapabilities.h"
38 #include "DFGCommon.h"
39 #include "DFGDriver.h"
40 #include "DFGJITCode.h"
41 #include "DFGWorklist.h"
42 #include "Debugger.h"
43 #include "FunctionExecutableDump.h"
44 #include "GetPutInfo.h"
45 #include "InlineCallFrame.h"
46 #include "Interpreter.h"
47 #include "JIT.h"
48 #include "JSCJSValue.h"
49 #include "JSFunction.h"
50 #include "JSLexicalEnvironment.h"
51 #include "JSModuleEnvironment.h"
52 #include "LLIntEntrypoint.h"
53 #include "LowLevelInterpreter.h"
54 #include "JSCInlines.h"
55 #include "PolymorphicAccess.h"
56 #include "ProfilerDatabase.h"
57 #include "ReduceWhitespace.h"
58 #include "Repatch.h"
59 #include "SlotVisitorInlines.h"
60 #include "StackVisitor.h"
61 #include "TypeLocationCache.h"
62 #include "TypeProfiler.h"
63 #include "UnlinkedInstructionStream.h"
64 #include <wtf/BagToHashMap.h>
65 #include <wtf/CommaPrinter.h>
66 #include <wtf/StringExtras.h>
67 #include <wtf/StringPrintStream.h>
68 #include <wtf/text/UniquedStringImpl.h>
69
70 #if ENABLE(JIT)
71 #include "RegisterAtOffsetList.h"
72 #endif
73
74 #if ENABLE(DFG_JIT)
75 #include "DFGOperations.h"
76 #endif
77
78 #if ENABLE(FTL_JIT)
79 #include "FTLJITCode.h"
80 #endif
81
82 namespace JSC {
83
84 const ClassInfo CodeBlock::s_info = {
85     "CodeBlock", 0, 0,
86     CREATE_METHOD_TABLE(CodeBlock)
87 };
88
89 const ClassInfo FunctionCodeBlock::s_info = {
90     "FunctionCodeBlock", &Base::s_info, 0,
91     CREATE_METHOD_TABLE(FunctionCodeBlock)
92 };
93
94 #if ENABLE(WEBASSEMBLY)
95 const ClassInfo WebAssemblyCodeBlock::s_info = {
96     "WebAssemblyCodeBlock", &Base::s_info, 0,
97     CREATE_METHOD_TABLE(WebAssemblyCodeBlock)
98 };
99 #endif
100
101 const ClassInfo GlobalCodeBlock::s_info = {
102     "GlobalCodeBlock", &Base::s_info, 0,
103     CREATE_METHOD_TABLE(GlobalCodeBlock)
104 };
105
106 const ClassInfo ProgramCodeBlock::s_info = {
107     "ProgramCodeBlock", &Base::s_info, 0,
108     CREATE_METHOD_TABLE(ProgramCodeBlock)
109 };
110
111 const ClassInfo ModuleProgramCodeBlock::s_info = {
112     "ModuleProgramCodeBlock", &Base::s_info, 0,
113     CREATE_METHOD_TABLE(ModuleProgramCodeBlock)
114 };
115
116 const ClassInfo EvalCodeBlock::s_info = {
117     "EvalCodeBlock", &Base::s_info, 0,
118     CREATE_METHOD_TABLE(EvalCodeBlock)
119 };
120
121 void FunctionCodeBlock::destroy(JSCell* cell)
122 {
123     jsCast<FunctionCodeBlock*>(cell)->~FunctionCodeBlock();
124 }
125
126 #if ENABLE(WEBASSEMBLY)
127 void WebAssemblyCodeBlock::destroy(JSCell* cell)
128 {
129     jsCast<WebAssemblyCodeBlock*>(cell)->~WebAssemblyCodeBlock();
130 }
131 #endif
132
133 void ProgramCodeBlock::destroy(JSCell* cell)
134 {
135     jsCast<ProgramCodeBlock*>(cell)->~ProgramCodeBlock();
136 }
137
138 void ModuleProgramCodeBlock::destroy(JSCell* cell)
139 {
140     jsCast<ModuleProgramCodeBlock*>(cell)->~ModuleProgramCodeBlock();
141 }
142
143 void EvalCodeBlock::destroy(JSCell* cell)
144 {
145     jsCast<EvalCodeBlock*>(cell)->~EvalCodeBlock();
146 }
147
148 CString CodeBlock::inferredName() const
149 {
150     switch (codeType()) {
151     case GlobalCode:
152         return "<global>";
153     case EvalCode:
154         return "<eval>";
155     case FunctionCode:
156         return jsCast<FunctionExecutable*>(ownerExecutable())->inferredName().utf8();
157     case ModuleCode:
158         return "<module>";
159     default:
160         CRASH();
161         return CString("", 0);
162     }
163 }
164
165 bool CodeBlock::hasHash() const
166 {
167     return !!m_hash;
168 }
169
170 bool CodeBlock::isSafeToComputeHash() const
171 {
172     return !isCompilationThread();
173 }
174
175 CodeBlockHash CodeBlock::hash() const
176 {
177     if (!m_hash) {
178         RELEASE_ASSERT(isSafeToComputeHash());
179         m_hash = CodeBlockHash(ownerScriptExecutable()->source(), specializationKind());
180     }
181     return m_hash;
182 }
183
184 CString CodeBlock::sourceCodeForTools() const
185 {
186     if (codeType() != FunctionCode)
187         return ownerScriptExecutable()->source().toUTF8();
188     
189     SourceProvider* provider = source();
190     FunctionExecutable* executable = jsCast<FunctionExecutable*>(ownerExecutable());
191     UnlinkedFunctionExecutable* unlinked = executable->unlinkedExecutable();
192     unsigned unlinkedStartOffset = unlinked->startOffset();
193     unsigned linkedStartOffset = executable->source().startOffset();
194     int delta = linkedStartOffset - unlinkedStartOffset;
195     unsigned rangeStart = delta + unlinked->unlinkedFunctionNameStart();
196     unsigned rangeEnd = delta + unlinked->startOffset() + unlinked->sourceLength();
197     return toCString(
198         "function ",
199         provider->source().impl()->utf8ForRange(rangeStart, rangeEnd - rangeStart));
200 }
201
202 CString CodeBlock::sourceCodeOnOneLine() const
203 {
204     return reduceWhitespace(sourceCodeForTools());
205 }
206
207 CString CodeBlock::hashAsStringIfPossible() const
208 {
209     if (hasHash() || isSafeToComputeHash())
210         return toCString(hash());
211     return "<no-hash>";
212 }
213
214 void CodeBlock::dumpAssumingJITType(PrintStream& out, JITCode::JITType jitType) const
215 {
216     out.print(inferredName(), "#", hashAsStringIfPossible());
217     out.print(":[", RawPointer(this), "->");
218     if (!!m_alternative)
219         out.print(RawPointer(alternative()), "->");
220     out.print(RawPointer(ownerExecutable()), ", ", jitType, codeType());
221
222     if (codeType() == FunctionCode)
223         out.print(specializationKind());
224     out.print(", ", instructionCount());
225     if (this->jitType() == JITCode::BaselineJIT && m_shouldAlwaysBeInlined)
226         out.print(" (ShouldAlwaysBeInlined)");
227     if (ownerScriptExecutable()->neverInline())
228         out.print(" (NeverInline)");
229     if (ownerScriptExecutable()->neverOptimize())
230         out.print(" (NeverOptimize)");
231     if (ownerScriptExecutable()->didTryToEnterInLoop())
232         out.print(" (DidTryToEnterInLoop)");
233     if (ownerScriptExecutable()->isStrictMode())
234         out.print(" (StrictMode)");
235     if (this->jitType() == JITCode::BaselineJIT && m_didFailFTLCompilation)
236         out.print(" (FTLFail)");
237     if (this->jitType() == JITCode::BaselineJIT && m_hasBeenCompiledWithFTL)
238         out.print(" (HadFTLReplacement)");
239     out.print("]");
240 }
241
242 void CodeBlock::dump(PrintStream& out) const
243 {
244     dumpAssumingJITType(out, jitType());
245 }
246
247 static CString idName(int id0, const Identifier& ident)
248 {
249     return toCString(ident.impl(), "(@id", id0, ")");
250 }
251
252 CString CodeBlock::registerName(int r) const
253 {
254     if (isConstantRegisterIndex(r))
255         return constantName(r);
256
257     return toCString(VirtualRegister(r));
258 }
259
260 CString CodeBlock::constantName(int index) const
261 {
262     JSValue value = getConstant(index);
263     return toCString(value, "(", VirtualRegister(index), ")");
264 }
265
266 static CString regexpToSourceString(RegExp* regExp)
267 {
268     char postfix[5] = { '/', 0, 0, 0, 0 };
269     int index = 1;
270     if (regExp->global())
271         postfix[index++] = 'g';
272     if (regExp->ignoreCase())
273         postfix[index++] = 'i';
274     if (regExp->multiline())
275         postfix[index] = 'm';
276
277     return toCString("/", regExp->pattern().impl(), postfix);
278 }
279
280 static CString regexpName(int re, RegExp* regexp)
281 {
282     return toCString(regexpToSourceString(regexp), "(@re", re, ")");
283 }
284
285 NEVER_INLINE static const char* debugHookName(int debugHookID)
286 {
287     switch (static_cast<DebugHookID>(debugHookID)) {
288         case DidEnterCallFrame:
289             return "didEnterCallFrame";
290         case WillLeaveCallFrame:
291             return "willLeaveCallFrame";
292         case WillExecuteStatement:
293             return "willExecuteStatement";
294         case WillExecuteProgram:
295             return "willExecuteProgram";
296         case DidExecuteProgram:
297             return "didExecuteProgram";
298         case DidReachBreakpoint:
299             return "didReachBreakpoint";
300     }
301
302     RELEASE_ASSERT_NOT_REACHED();
303     return "";
304 }
305
306 void CodeBlock::printUnaryOp(PrintStream& out, ExecState* exec, int location, const Instruction*& it, const char* op)
307 {
308     int r0 = (++it)->u.operand;
309     int r1 = (++it)->u.operand;
310
311     printLocationAndOp(out, exec, location, it, op);
312     out.printf("%s, %s", registerName(r0).data(), registerName(r1).data());
313 }
314
315 void CodeBlock::printBinaryOp(PrintStream& out, ExecState* exec, int location, const Instruction*& it, const char* op)
316 {
317     int r0 = (++it)->u.operand;
318     int r1 = (++it)->u.operand;
319     int r2 = (++it)->u.operand;
320     printLocationAndOp(out, exec, location, it, op);
321     out.printf("%s, %s, %s", registerName(r0).data(), registerName(r1).data(), registerName(r2).data());
322 }
323
324 void CodeBlock::printConditionalJump(PrintStream& out, ExecState* exec, const Instruction*, const Instruction*& it, int location, const char* op)
325 {
326     int r0 = (++it)->u.operand;
327     int offset = (++it)->u.operand;
328     printLocationAndOp(out, exec, location, it, op);
329     out.printf("%s, %d(->%d)", registerName(r0).data(), offset, location + offset);
330 }
331
332 void CodeBlock::printGetByIdOp(PrintStream& out, ExecState* exec, int location, const Instruction*& it)
333 {
334     const char* op;
335     switch (exec->interpreter()->getOpcodeID(it->u.opcode)) {
336     case op_get_by_id:
337         op = "get_by_id";
338         break;
339     case op_get_array_length:
340         op = "array_length";
341         break;
342     default:
343         RELEASE_ASSERT_NOT_REACHED();
344 #if COMPILER_QUIRK(CONSIDERS_UNREACHABLE_CODE)
345         op = 0;
346 #endif
347     }
348     int r0 = (++it)->u.operand;
349     int r1 = (++it)->u.operand;
350     int id0 = (++it)->u.operand;
351     printLocationAndOp(out, exec, location, it, op);
352     out.printf("%s, %s, %s", registerName(r0).data(), registerName(r1).data(), idName(id0, identifier(id0)).data());
353     it += 4; // Increment up to the value profiler.
354 }
355
356 static void dumpStructure(PrintStream& out, const char* name, Structure* structure, const Identifier& ident)
357 {
358     if (!structure)
359         return;
360     
361     out.printf("%s = %p", name, structure);
362     
363     PropertyOffset offset = structure->getConcurrently(ident.impl());
364     if (offset != invalidOffset)
365         out.printf(" (offset = %d)", offset);
366 }
367
368 static void dumpChain(PrintStream& out, StructureChain* chain, const Identifier& ident)
369 {
370     out.printf("chain = %p: [", chain);
371     bool first = true;
372     for (WriteBarrier<Structure>* currentStructure = chain->head();
373          *currentStructure;
374          ++currentStructure) {
375         if (first)
376             first = false;
377         else
378             out.printf(", ");
379         dumpStructure(out, "struct", currentStructure->get(), ident);
380     }
381     out.printf("]");
382 }
383
384 void CodeBlock::printGetByIdCacheStatus(PrintStream& out, ExecState* exec, int location, const StubInfoMap& map)
385 {
386     Instruction* instruction = instructions().begin() + location;
387
388     const Identifier& ident = identifier(instruction[3].u.operand);
389     
390     UNUSED_PARAM(ident); // tell the compiler to shut up in certain platform configurations.
391     
392     if (exec->interpreter()->getOpcodeID(instruction[0].u.opcode) == op_get_array_length)
393         out.printf(" llint(array_length)");
394     else if (StructureID structureID = instruction[4].u.structureID) {
395         Structure* structure = m_vm->heap.structureIDTable().get(structureID);
396         out.printf(" llint(");
397         dumpStructure(out, "struct", structure, ident);
398         out.printf(")");
399     }
400
401 #if ENABLE(JIT)
402     if (StructureStubInfo* stubPtr = map.get(CodeOrigin(location))) {
403         StructureStubInfo& stubInfo = *stubPtr;
404         if (stubInfo.resetByGC)
405             out.print(" (Reset By GC)");
406         
407         out.printf(" jit(");
408             
409         Structure* baseStructure = nullptr;
410         PolymorphicAccess* stub = nullptr;
411             
412         switch (stubInfo.cacheType) {
413         case CacheType::GetByIdSelf:
414             out.printf("self");
415             baseStructure = stubInfo.u.byIdSelf.baseObjectStructure.get();
416             break;
417         case CacheType::Stub:
418             out.printf("stub");
419             stub = stubInfo.u.stub;
420             break;
421         case CacheType::Unset:
422             out.printf("unset");
423             break;
424         default:
425             RELEASE_ASSERT_NOT_REACHED();
426             break;
427         }
428             
429         if (baseStructure) {
430             out.printf(", ");
431             dumpStructure(out, "struct", baseStructure, ident);
432         }
433
434         if (stub)
435             out.print(", ", *stub);
436
437         out.printf(")");
438     }
439 #else
440     UNUSED_PARAM(map);
441 #endif
442 }
443
444 void CodeBlock::printPutByIdCacheStatus(PrintStream& out, int location, const StubInfoMap& map)
445 {
446     Instruction* instruction = instructions().begin() + location;
447
448     const Identifier& ident = identifier(instruction[2].u.operand);
449     
450     UNUSED_PARAM(ident); // tell the compiler to shut up in certain platform configurations.
451
452     out.print(", ", instruction[8].u.putByIdFlags);
453     
454     if (StructureID structureID = instruction[4].u.structureID) {
455         Structure* structure = m_vm->heap.structureIDTable().get(structureID);
456         out.print(" llint(");
457         if (StructureID newStructureID = instruction[6].u.structureID) {
458             Structure* newStructure = m_vm->heap.structureIDTable().get(newStructureID);
459             dumpStructure(out, "prev", structure, ident);
460             out.print(", ");
461             dumpStructure(out, "next", newStructure, ident);
462             if (StructureChain* chain = instruction[7].u.structureChain.get()) {
463                 out.print(", ");
464                 dumpChain(out, chain, ident);
465             }
466         } else
467             dumpStructure(out, "struct", structure, ident);
468         out.print(")");
469     }
470
471 #if ENABLE(JIT)
472     if (StructureStubInfo* stubPtr = map.get(CodeOrigin(location))) {
473         StructureStubInfo& stubInfo = *stubPtr;
474         if (stubInfo.resetByGC)
475             out.print(" (Reset By GC)");
476         
477         out.printf(" jit(");
478         
479         switch (stubInfo.cacheType) {
480         case CacheType::PutByIdReplace:
481             out.print("replace, ");
482             dumpStructure(out, "struct", stubInfo.u.byIdSelf.baseObjectStructure.get(), ident);
483             break;
484         case CacheType::Stub: {
485             out.print("stub, ", *stubInfo.u.stub);
486             break;
487         }
488         case CacheType::Unset:
489             out.printf("unset");
490             break;
491         default:
492             RELEASE_ASSERT_NOT_REACHED();
493             break;
494         }
495         out.printf(")");
496     }
497 #else
498     UNUSED_PARAM(map);
499 #endif
500 }
501
502 void CodeBlock::printCallOp(PrintStream& out, ExecState* exec, int location, const Instruction*& it, const char* op, CacheDumpMode cacheDumpMode, bool& hasPrintedProfiling, const CallLinkInfoMap& map)
503 {
504     int dst = (++it)->u.operand;
505     int func = (++it)->u.operand;
506     int argCount = (++it)->u.operand;
507     int registerOffset = (++it)->u.operand;
508     printLocationAndOp(out, exec, location, it, op);
509     out.printf("%s, %s, %d, %d", registerName(dst).data(), registerName(func).data(), argCount, registerOffset);
510     if (cacheDumpMode == DumpCaches) {
511         LLIntCallLinkInfo* callLinkInfo = it[1].u.callLinkInfo;
512         if (callLinkInfo->lastSeenCallee) {
513             out.printf(
514                 " llint(%p, exec %p)",
515                 callLinkInfo->lastSeenCallee.get(),
516                 callLinkInfo->lastSeenCallee->executable());
517         }
518 #if ENABLE(JIT)
519         if (CallLinkInfo* info = map.get(CodeOrigin(location))) {
520             JSFunction* target = info->lastSeenCallee();
521             if (target)
522                 out.printf(" jit(%p, exec %p)", target, target->executable());
523         }
524         
525         if (jitType() != JITCode::FTLJIT)
526             out.print(" status(", CallLinkStatus::computeFor(this, location, map), ")");
527 #else
528         UNUSED_PARAM(map);
529 #endif
530     }
531     ++it;
532     ++it;
533     dumpArrayProfiling(out, it, hasPrintedProfiling);
534     dumpValueProfiling(out, it, hasPrintedProfiling);
535 }
536
537 void CodeBlock::printPutByIdOp(PrintStream& out, ExecState* exec, int location, const Instruction*& it, const char* op)
538 {
539     int r0 = (++it)->u.operand;
540     int id0 = (++it)->u.operand;
541     int r1 = (++it)->u.operand;
542     printLocationAndOp(out, exec, location, it, op);
543     out.printf("%s, %s, %s", registerName(r0).data(), idName(id0, identifier(id0)).data(), registerName(r1).data());
544     it += 5;
545 }
546
547 void CodeBlock::dumpSource()
548 {
549     dumpSource(WTF::dataFile());
550 }
551
552 void CodeBlock::dumpSource(PrintStream& out)
553 {
554     ScriptExecutable* executable = ownerScriptExecutable();
555     if (executable->isFunctionExecutable()) {
556         FunctionExecutable* functionExecutable = reinterpret_cast<FunctionExecutable*>(executable);
557         String source = functionExecutable->source().provider()->getRange(
558             functionExecutable->parametersStartOffset(),
559             functionExecutable->typeProfilingEndOffset() + 1); // Type profiling end offset is the character before the '}'.
560         
561         out.print("function ", inferredName(), source);
562         return;
563     }
564     out.print(executable->source().toString());
565 }
566
567 void CodeBlock::dumpBytecode()
568 {
569     dumpBytecode(WTF::dataFile());
570 }
571
572 void CodeBlock::dumpBytecode(PrintStream& out)
573 {
574     // We only use the ExecState* for things that don't actually lead to JS execution,
575     // like converting a JSString to a String. Hence the globalExec is appropriate.
576     ExecState* exec = m_globalObject->globalExec();
577     
578     size_t instructionCount = 0;
579
580     for (size_t i = 0; i < instructions().size(); i += opcodeLengths[exec->interpreter()->getOpcodeID(instructions()[i].u.opcode)])
581         ++instructionCount;
582
583     out.print(*this);
584     out.printf(
585         ": %lu m_instructions; %lu bytes; %d parameter(s); %d callee register(s); %d variable(s)",
586         static_cast<unsigned long>(instructions().size()),
587         static_cast<unsigned long>(instructions().size() * sizeof(Instruction)),
588         m_numParameters, m_numCalleeLocals, m_numVars);
589     if (needsActivation() && codeType() == FunctionCode)
590         out.printf("; lexical environment in r%d", activationRegister().offset());
591     out.printf("\n");
592     
593     StubInfoMap stubInfos;
594     CallLinkInfoMap callLinkInfos;
595     getStubInfoMap(stubInfos);
596     getCallLinkInfoMap(callLinkInfos);
597     
598     const Instruction* begin = instructions().begin();
599     const Instruction* end = instructions().end();
600     for (const Instruction* it = begin; it != end; ++it)
601         dumpBytecode(out, exec, begin, it, stubInfos, callLinkInfos);
602     
603     if (numberOfIdentifiers()) {
604         out.printf("\nIdentifiers:\n");
605         size_t i = 0;
606         do {
607             out.printf("  id%u = %s\n", static_cast<unsigned>(i), identifier(i).string().utf8().data());
608             ++i;
609         } while (i != numberOfIdentifiers());
610     }
611
612     if (!m_constantRegisters.isEmpty()) {
613         out.printf("\nConstants:\n");
614         size_t i = 0;
615         do {
616             const char* sourceCodeRepresentationDescription = nullptr;
617             switch (m_constantsSourceCodeRepresentation[i]) {
618             case SourceCodeRepresentation::Double:
619                 sourceCodeRepresentationDescription = ": in source as double";
620                 break;
621             case SourceCodeRepresentation::Integer:
622                 sourceCodeRepresentationDescription = ": in source as integer";
623                 break;
624             case SourceCodeRepresentation::Other:
625                 sourceCodeRepresentationDescription = "";
626                 break;
627             }
628             out.printf("   k%u = %s%s\n", static_cast<unsigned>(i), toCString(m_constantRegisters[i].get()).data(), sourceCodeRepresentationDescription);
629             ++i;
630         } while (i < m_constantRegisters.size());
631     }
632
633     if (size_t count = m_unlinkedCode->numberOfRegExps()) {
634         out.printf("\nm_regexps:\n");
635         size_t i = 0;
636         do {
637             out.printf("  re%u = %s\n", static_cast<unsigned>(i), regexpToSourceString(m_unlinkedCode->regexp(i)).data());
638             ++i;
639         } while (i < count);
640     }
641
642     if (m_rareData && !m_rareData->m_exceptionHandlers.isEmpty()) {
643         out.printf("\nException Handlers:\n");
644         unsigned i = 0;
645         do {
646             HandlerInfo& handler = m_rareData->m_exceptionHandlers[i];
647             out.printf("\t %d: { start: [%4d] end: [%4d] target: [%4d] } %s\n",
648                 i + 1, handler.start, handler.end, handler.target, handler.typeName());
649             ++i;
650         } while (i < m_rareData->m_exceptionHandlers.size());
651     }
652     
653     if (m_rareData && !m_rareData->m_switchJumpTables.isEmpty()) {
654         out.printf("Switch Jump Tables:\n");
655         unsigned i = 0;
656         do {
657             out.printf("  %1d = {\n", i);
658             int entry = 0;
659             Vector<int32_t>::const_iterator end = m_rareData->m_switchJumpTables[i].branchOffsets.end();
660             for (Vector<int32_t>::const_iterator iter = m_rareData->m_switchJumpTables[i].branchOffsets.begin(); iter != end; ++iter, ++entry) {
661                 if (!*iter)
662                     continue;
663                 out.printf("\t\t%4d => %04d\n", entry + m_rareData->m_switchJumpTables[i].min, *iter);
664             }
665             out.printf("      }\n");
666             ++i;
667         } while (i < m_rareData->m_switchJumpTables.size());
668     }
669     
670     if (m_rareData && !m_rareData->m_stringSwitchJumpTables.isEmpty()) {
671         out.printf("\nString Switch Jump Tables:\n");
672         unsigned i = 0;
673         do {
674             out.printf("  %1d = {\n", i);
675             StringJumpTable::StringOffsetTable::const_iterator end = m_rareData->m_stringSwitchJumpTables[i].offsetTable.end();
676             for (StringJumpTable::StringOffsetTable::const_iterator iter = m_rareData->m_stringSwitchJumpTables[i].offsetTable.begin(); iter != end; ++iter)
677                 out.printf("\t\t\"%s\" => %04d\n", iter->key->utf8().data(), iter->value.branchOffset);
678             out.printf("      }\n");
679             ++i;
680         } while (i < m_rareData->m_stringSwitchJumpTables.size());
681     }
682
683     if (m_rareData && !m_rareData->m_liveCalleeLocalsAtYield.isEmpty()) {
684         out.printf("\nLive Callee Locals:\n");
685         unsigned i = 0;
686         do {
687             const FastBitVector& liveness = m_rareData->m_liveCalleeLocalsAtYield[i];
688             out.printf("  live%1u = ", i);
689             liveness.dump(out);
690             out.printf("\n");
691             ++i;
692         } while (i < m_rareData->m_liveCalleeLocalsAtYield.size());
693     }
694
695     out.printf("\n");
696 }
697
698 void CodeBlock::beginDumpProfiling(PrintStream& out, bool& hasPrintedProfiling)
699 {
700     if (hasPrintedProfiling) {
701         out.print("; ");
702         return;
703     }
704     
705     out.print("    ");
706     hasPrintedProfiling = true;
707 }
708
709 void CodeBlock::dumpValueProfiling(PrintStream& out, const Instruction*& it, bool& hasPrintedProfiling)
710 {
711     ConcurrentJITLocker locker(m_lock);
712     
713     ++it;
714     CString description = it->u.profile->briefDescription(locker);
715     if (!description.length())
716         return;
717     beginDumpProfiling(out, hasPrintedProfiling);
718     out.print(description);
719 }
720
721 void CodeBlock::dumpArrayProfiling(PrintStream& out, const Instruction*& it, bool& hasPrintedProfiling)
722 {
723     ConcurrentJITLocker locker(m_lock);
724     
725     ++it;
726     if (!it->u.arrayProfile)
727         return;
728     CString description = it->u.arrayProfile->briefDescription(locker, this);
729     if (!description.length())
730         return;
731     beginDumpProfiling(out, hasPrintedProfiling);
732     out.print(description);
733 }
734
735 void CodeBlock::dumpRareCaseProfile(PrintStream& out, const char* name, RareCaseProfile* profile, bool& hasPrintedProfiling)
736 {
737     if (!profile || !profile->m_counter)
738         return;
739
740     beginDumpProfiling(out, hasPrintedProfiling);
741     out.print(name, profile->m_counter);
742 }
743
744 void CodeBlock::printLocationAndOp(PrintStream& out, ExecState*, int location, const Instruction*&, const char* op)
745 {
746     out.printf("[%4d] %-17s ", location, op);
747 }
748
749 void CodeBlock::printLocationOpAndRegisterOperand(PrintStream& out, ExecState* exec, int location, const Instruction*& it, const char* op, int operand)
750 {
751     printLocationAndOp(out, exec, location, it, op);
752     out.printf("%s", registerName(operand).data());
753 }
754
755 void CodeBlock::dumpBytecode(
756     PrintStream& out, ExecState* exec, const Instruction* begin, const Instruction*& it,
757     const StubInfoMap& stubInfos, const CallLinkInfoMap& callLinkInfos)
758 {
759     int location = it - begin;
760     bool hasPrintedProfiling = false;
761     OpcodeID opcode = exec->interpreter()->getOpcodeID(it->u.opcode);
762     switch (opcode) {
763         case op_enter: {
764             printLocationAndOp(out, exec, location, it, "enter");
765             break;
766         }
767         case op_get_scope: {
768             int r0 = (++it)->u.operand;
769             printLocationOpAndRegisterOperand(out, exec, location, it, "get_scope", r0);
770             break;
771         }
772         case op_load_arrowfunction_this: {
773             int r0 = (++it)->u.operand;
774             printLocationOpAndRegisterOperand(out, exec, location, it, "load_arrowfunction_this", r0);
775             break;
776         }
777         case op_create_direct_arguments: {
778             int r0 = (++it)->u.operand;
779             printLocationAndOp(out, exec, location, it, "create_direct_arguments");
780             out.printf("%s", registerName(r0).data());
781             break;
782         }
783         case op_create_scoped_arguments: {
784             int r0 = (++it)->u.operand;
785             int r1 = (++it)->u.operand;
786             printLocationAndOp(out, exec, location, it, "create_scoped_arguments");
787             out.printf("%s, %s", registerName(r0).data(), registerName(r1).data());
788             break;
789         }
790         case op_create_out_of_band_arguments: {
791             int r0 = (++it)->u.operand;
792             printLocationAndOp(out, exec, location, it, "create_out_of_band_arguments");
793             out.printf("%s", registerName(r0).data());
794             break;
795         }
796         case op_copy_rest: {
797             int r0 = (++it)->u.operand;
798             int r1 = (++it)->u.operand;
799             unsigned argumentOffset = (++it)->u.unsignedValue;
800             printLocationAndOp(out, exec, location, it, "copy_rest");
801             out.printf("%s, %s, ", registerName(r0).data(), registerName(r1).data());
802             out.printf("ArgumentsOffset: %u", argumentOffset);
803             break;
804         }
805         case op_get_rest_length: {
806             int r0 = (++it)->u.operand;
807             printLocationAndOp(out, exec, location, it, "get_rest_length");
808             out.printf("%s, ", registerName(r0).data());
809             unsigned argumentOffset = (++it)->u.unsignedValue;
810             out.printf("ArgumentsOffset: %u", argumentOffset);
811             break;
812         }
813         case op_create_this: {
814             int r0 = (++it)->u.operand;
815             int r1 = (++it)->u.operand;
816             unsigned inferredInlineCapacity = (++it)->u.operand;
817             unsigned cachedFunction = (++it)->u.operand;
818             printLocationAndOp(out, exec, location, it, "create_this");
819             out.printf("%s, %s, %u, %u", registerName(r0).data(), registerName(r1).data(), inferredInlineCapacity, cachedFunction);
820             break;
821         }
822         case op_to_this: {
823             int r0 = (++it)->u.operand;
824             printLocationOpAndRegisterOperand(out, exec, location, it, "to_this", r0);
825             Structure* structure = (++it)->u.structure.get();
826             if (structure)
827                 out.print(", cache(struct = ", RawPointer(structure), ")");
828             out.print(", ", (++it)->u.toThisStatus);
829             break;
830         }
831         case op_check_tdz: {
832             int r0 = (++it)->u.operand;
833             printLocationOpAndRegisterOperand(out, exec, location, it, "op_check_tdz", r0);
834             break;
835         }
836         case op_new_object: {
837             int r0 = (++it)->u.operand;
838             unsigned inferredInlineCapacity = (++it)->u.operand;
839             printLocationAndOp(out, exec, location, it, "new_object");
840             out.printf("%s, %u", registerName(r0).data(), inferredInlineCapacity);
841             ++it; // Skip object allocation profile.
842             break;
843         }
844         case op_new_array: {
845             int dst = (++it)->u.operand;
846             int argv = (++it)->u.operand;
847             int argc = (++it)->u.operand;
848             printLocationAndOp(out, exec, location, it, "new_array");
849             out.printf("%s, %s, %d", registerName(dst).data(), registerName(argv).data(), argc);
850             ++it; // Skip array allocation profile.
851             break;
852         }
853         case op_new_array_with_size: {
854             int dst = (++it)->u.operand;
855             int length = (++it)->u.operand;
856             printLocationAndOp(out, exec, location, it, "new_array_with_size");
857             out.printf("%s, %s", registerName(dst).data(), registerName(length).data());
858             ++it; // Skip array allocation profile.
859             break;
860         }
861         case op_new_array_buffer: {
862             int dst = (++it)->u.operand;
863             int argv = (++it)->u.operand;
864             int argc = (++it)->u.operand;
865             printLocationAndOp(out, exec, location, it, "new_array_buffer");
866             out.printf("%s, %d, %d", registerName(dst).data(), argv, argc);
867             ++it; // Skip array allocation profile.
868             break;
869         }
870         case op_new_regexp: {
871             int r0 = (++it)->u.operand;
872             int re0 = (++it)->u.operand;
873             printLocationAndOp(out, exec, location, it, "new_regexp");
874             out.printf("%s, ", registerName(r0).data());
875             if (r0 >=0 && r0 < (int)m_unlinkedCode->numberOfRegExps())
876                 out.printf("%s", regexpName(re0, regexp(re0)).data());
877             else
878                 out.printf("bad_regexp(%d)", re0);
879             break;
880         }
881         case op_mov: {
882             int r0 = (++it)->u.operand;
883             int r1 = (++it)->u.operand;
884             printLocationAndOp(out, exec, location, it, "mov");
885             out.printf("%s, %s", registerName(r0).data(), registerName(r1).data());
886             break;
887         }
888         case op_profile_type: {
889             int r0 = (++it)->u.operand;
890             ++it;
891             ++it;
892             ++it;
893             ++it;
894             printLocationAndOp(out, exec, location, it, "op_profile_type");
895             out.printf("%s", registerName(r0).data());
896             break;
897         }
898         case op_profile_control_flow: {
899             BasicBlockLocation* basicBlockLocation = (++it)->u.basicBlockLocation;
900             printLocationAndOp(out, exec, location, it, "profile_control_flow");
901             out.printf("[%d, %d]", basicBlockLocation->startOffset(), basicBlockLocation->endOffset());
902             break;
903         }
904         case op_not: {
905             printUnaryOp(out, exec, location, it, "not");
906             break;
907         }
908         case op_eq: {
909             printBinaryOp(out, exec, location, it, "eq");
910             break;
911         }
912         case op_eq_null: {
913             printUnaryOp(out, exec, location, it, "eq_null");
914             break;
915         }
916         case op_neq: {
917             printBinaryOp(out, exec, location, it, "neq");
918             break;
919         }
920         case op_neq_null: {
921             printUnaryOp(out, exec, location, it, "neq_null");
922             break;
923         }
924         case op_stricteq: {
925             printBinaryOp(out, exec, location, it, "stricteq");
926             break;
927         }
928         case op_nstricteq: {
929             printBinaryOp(out, exec, location, it, "nstricteq");
930             break;
931         }
932         case op_less: {
933             printBinaryOp(out, exec, location, it, "less");
934             break;
935         }
936         case op_lesseq: {
937             printBinaryOp(out, exec, location, it, "lesseq");
938             break;
939         }
940         case op_greater: {
941             printBinaryOp(out, exec, location, it, "greater");
942             break;
943         }
944         case op_greatereq: {
945             printBinaryOp(out, exec, location, it, "greatereq");
946             break;
947         }
948         case op_inc: {
949             int r0 = (++it)->u.operand;
950             printLocationOpAndRegisterOperand(out, exec, location, it, "inc", r0);
951             break;
952         }
953         case op_dec: {
954             int r0 = (++it)->u.operand;
955             printLocationOpAndRegisterOperand(out, exec, location, it, "dec", r0);
956             break;
957         }
958         case op_to_number: {
959             printUnaryOp(out, exec, location, it, "to_number");
960             break;
961         }
962         case op_to_string: {
963             printUnaryOp(out, exec, location, it, "to_string");
964             break;
965         }
966         case op_negate: {
967             printUnaryOp(out, exec, location, it, "negate");
968             break;
969         }
970         case op_add: {
971             printBinaryOp(out, exec, location, it, "add");
972             ++it;
973             break;
974         }
975         case op_mul: {
976             printBinaryOp(out, exec, location, it, "mul");
977             ++it;
978             break;
979         }
980         case op_div: {
981             printBinaryOp(out, exec, location, it, "div");
982             ++it;
983             break;
984         }
985         case op_mod: {
986             printBinaryOp(out, exec, location, it, "mod");
987             break;
988         }
989         case op_sub: {
990             printBinaryOp(out, exec, location, it, "sub");
991             ++it;
992             break;
993         }
994         case op_lshift: {
995             printBinaryOp(out, exec, location, it, "lshift");
996             break;            
997         }
998         case op_rshift: {
999             printBinaryOp(out, exec, location, it, "rshift");
1000             break;
1001         }
1002         case op_urshift: {
1003             printBinaryOp(out, exec, location, it, "urshift");
1004             break;
1005         }
1006         case op_bitand: {
1007             printBinaryOp(out, exec, location, it, "bitand");
1008             ++it;
1009             break;
1010         }
1011         case op_bitxor: {
1012             printBinaryOp(out, exec, location, it, "bitxor");
1013             ++it;
1014             break;
1015         }
1016         case op_bitor: {
1017             printBinaryOp(out, exec, location, it, "bitor");
1018             ++it;
1019             break;
1020         }
1021         case op_check_has_instance: {
1022             int r0 = (++it)->u.operand;
1023             int r1 = (++it)->u.operand;
1024             int r2 = (++it)->u.operand;
1025             int offset = (++it)->u.operand;
1026             printLocationAndOp(out, exec, location, it, "check_has_instance");
1027             out.printf("%s, %s, %s, %d(->%d)", registerName(r0).data(), registerName(r1).data(), registerName(r2).data(), offset, location + offset);
1028             break;
1029         }
1030         case op_instanceof: {
1031             int r0 = (++it)->u.operand;
1032             int r1 = (++it)->u.operand;
1033             int r2 = (++it)->u.operand;
1034             printLocationAndOp(out, exec, location, it, "instanceof");
1035             out.printf("%s, %s, %s", registerName(r0).data(), registerName(r1).data(), registerName(r2).data());
1036             break;
1037         }
1038         case op_unsigned: {
1039             printUnaryOp(out, exec, location, it, "unsigned");
1040             break;
1041         }
1042         case op_typeof: {
1043             printUnaryOp(out, exec, location, it, "typeof");
1044             break;
1045         }
1046         case op_is_undefined: {
1047             printUnaryOp(out, exec, location, it, "is_undefined");
1048             break;
1049         }
1050         case op_is_boolean: {
1051             printUnaryOp(out, exec, location, it, "is_boolean");
1052             break;
1053         }
1054         case op_is_number: {
1055             printUnaryOp(out, exec, location, it, "is_number");
1056             break;
1057         }
1058         case op_is_string: {
1059             printUnaryOp(out, exec, location, it, "is_string");
1060             break;
1061         }
1062         case op_is_object: {
1063             printUnaryOp(out, exec, location, it, "is_object");
1064             break;
1065         }
1066         case op_is_object_or_null: {
1067             printUnaryOp(out, exec, location, it, "is_object_or_null");
1068             break;
1069         }
1070         case op_is_function: {
1071             printUnaryOp(out, exec, location, it, "is_function");
1072             break;
1073         }
1074         case op_in: {
1075             printBinaryOp(out, exec, location, it, "in");
1076             break;
1077         }
1078         case op_get_by_id:
1079         case op_get_array_length: {
1080             printGetByIdOp(out, exec, location, it);
1081             printGetByIdCacheStatus(out, exec, location, stubInfos);
1082             dumpValueProfiling(out, it, hasPrintedProfiling);
1083             break;
1084         }
1085         case op_put_by_id: {
1086             printPutByIdOp(out, exec, location, it, "put_by_id");
1087             printPutByIdCacheStatus(out, location, stubInfos);
1088             break;
1089         }
1090         case op_put_getter_by_id: {
1091             int r0 = (++it)->u.operand;
1092             int id0 = (++it)->u.operand;
1093             int n0 = (++it)->u.operand;
1094             int r1 = (++it)->u.operand;
1095             printLocationAndOp(out, exec, location, it, "put_getter_by_id");
1096             out.printf("%s, %s, %d, %s", registerName(r0).data(), idName(id0, identifier(id0)).data(), n0, registerName(r1).data());
1097             break;
1098         }
1099         case op_put_setter_by_id: {
1100             int r0 = (++it)->u.operand;
1101             int id0 = (++it)->u.operand;
1102             int n0 = (++it)->u.operand;
1103             int r1 = (++it)->u.operand;
1104             printLocationAndOp(out, exec, location, it, "put_setter_by_id");
1105             out.printf("%s, %s, %d, %s", registerName(r0).data(), idName(id0, identifier(id0)).data(), n0, registerName(r1).data());
1106             break;
1107         }
1108         case op_put_getter_setter_by_id: {
1109             int r0 = (++it)->u.operand;
1110             int id0 = (++it)->u.operand;
1111             int n0 = (++it)->u.operand;
1112             int r1 = (++it)->u.operand;
1113             int r2 = (++it)->u.operand;
1114             printLocationAndOp(out, exec, location, it, "put_getter_setter_by_id");
1115             out.printf("%s, %s, %d, %s, %s", registerName(r0).data(), idName(id0, identifier(id0)).data(), n0, registerName(r1).data(), registerName(r2).data());
1116             break;
1117         }
1118         case op_put_getter_by_val: {
1119             int r0 = (++it)->u.operand;
1120             int r1 = (++it)->u.operand;
1121             int n0 = (++it)->u.operand;
1122             int r2 = (++it)->u.operand;
1123             printLocationAndOp(out, exec, location, it, "put_getter_by_val");
1124             out.printf("%s, %s, %d, %s", registerName(r0).data(), registerName(r1).data(), n0, registerName(r2).data());
1125             break;
1126         }
1127         case op_put_setter_by_val: {
1128             int r0 = (++it)->u.operand;
1129             int r1 = (++it)->u.operand;
1130             int n0 = (++it)->u.operand;
1131             int r2 = (++it)->u.operand;
1132             printLocationAndOp(out, exec, location, it, "put_setter_by_val");
1133             out.printf("%s, %s, %d, %s", registerName(r0).data(), registerName(r1).data(), n0, registerName(r2).data());
1134             break;
1135         }
1136         case op_del_by_id: {
1137             int r0 = (++it)->u.operand;
1138             int r1 = (++it)->u.operand;
1139             int id0 = (++it)->u.operand;
1140             printLocationAndOp(out, exec, location, it, "del_by_id");
1141             out.printf("%s, %s, %s", registerName(r0).data(), registerName(r1).data(), idName(id0, identifier(id0)).data());
1142             break;
1143         }
1144         case op_get_by_val: {
1145             int r0 = (++it)->u.operand;
1146             int r1 = (++it)->u.operand;
1147             int r2 = (++it)->u.operand;
1148             printLocationAndOp(out, exec, location, it, "get_by_val");
1149             out.printf("%s, %s, %s", registerName(r0).data(), registerName(r1).data(), registerName(r2).data());
1150             dumpArrayProfiling(out, it, hasPrintedProfiling);
1151             dumpValueProfiling(out, it, hasPrintedProfiling);
1152             break;
1153         }
1154         case op_put_by_val: {
1155             int r0 = (++it)->u.operand;
1156             int r1 = (++it)->u.operand;
1157             int r2 = (++it)->u.operand;
1158             printLocationAndOp(out, exec, location, it, "put_by_val");
1159             out.printf("%s, %s, %s", registerName(r0).data(), registerName(r1).data(), registerName(r2).data());
1160             dumpArrayProfiling(out, it, hasPrintedProfiling);
1161             break;
1162         }
1163         case op_put_by_val_direct: {
1164             int r0 = (++it)->u.operand;
1165             int r1 = (++it)->u.operand;
1166             int r2 = (++it)->u.operand;
1167             printLocationAndOp(out, exec, location, it, "put_by_val_direct");
1168             out.printf("%s, %s, %s", registerName(r0).data(), registerName(r1).data(), registerName(r2).data());
1169             dumpArrayProfiling(out, it, hasPrintedProfiling);
1170             break;
1171         }
1172         case op_del_by_val: {
1173             int r0 = (++it)->u.operand;
1174             int r1 = (++it)->u.operand;
1175             int r2 = (++it)->u.operand;
1176             printLocationAndOp(out, exec, location, it, "del_by_val");
1177             out.printf("%s, %s, %s", registerName(r0).data(), registerName(r1).data(), registerName(r2).data());
1178             break;
1179         }
1180         case op_put_by_index: {
1181             int r0 = (++it)->u.operand;
1182             unsigned n0 = (++it)->u.operand;
1183             int r1 = (++it)->u.operand;
1184             printLocationAndOp(out, exec, location, it, "put_by_index");
1185             out.printf("%s, %u, %s", registerName(r0).data(), n0, registerName(r1).data());
1186             break;
1187         }
1188         case op_jmp: {
1189             int offset = (++it)->u.operand;
1190             printLocationAndOp(out, exec, location, it, "jmp");
1191             out.printf("%d(->%d)", offset, location + offset);
1192             break;
1193         }
1194         case op_jtrue: {
1195             printConditionalJump(out, exec, begin, it, location, "jtrue");
1196             break;
1197         }
1198         case op_jfalse: {
1199             printConditionalJump(out, exec, begin, it, location, "jfalse");
1200             break;
1201         }
1202         case op_jeq_null: {
1203             printConditionalJump(out, exec, begin, it, location, "jeq_null");
1204             break;
1205         }
1206         case op_jneq_null: {
1207             printConditionalJump(out, exec, begin, it, location, "jneq_null");
1208             break;
1209         }
1210         case op_jneq_ptr: {
1211             int r0 = (++it)->u.operand;
1212             Special::Pointer pointer = (++it)->u.specialPointer;
1213             int offset = (++it)->u.operand;
1214             printLocationAndOp(out, exec, location, it, "jneq_ptr");
1215             out.printf("%s, %d (%p), %d(->%d)", registerName(r0).data(), pointer, m_globalObject->actualPointerFor(pointer), offset, location + offset);
1216             break;
1217         }
1218         case op_jless: {
1219             int r0 = (++it)->u.operand;
1220             int r1 = (++it)->u.operand;
1221             int offset = (++it)->u.operand;
1222             printLocationAndOp(out, exec, location, it, "jless");
1223             out.printf("%s, %s, %d(->%d)", registerName(r0).data(), registerName(r1).data(), offset, location + offset);
1224             break;
1225         }
1226         case op_jlesseq: {
1227             int r0 = (++it)->u.operand;
1228             int r1 = (++it)->u.operand;
1229             int offset = (++it)->u.operand;
1230             printLocationAndOp(out, exec, location, it, "jlesseq");
1231             out.printf("%s, %s, %d(->%d)", registerName(r0).data(), registerName(r1).data(), offset, location + offset);
1232             break;
1233         }
1234         case op_jgreater: {
1235             int r0 = (++it)->u.operand;
1236             int r1 = (++it)->u.operand;
1237             int offset = (++it)->u.operand;
1238             printLocationAndOp(out, exec, location, it, "jgreater");
1239             out.printf("%s, %s, %d(->%d)", registerName(r0).data(), registerName(r1).data(), offset, location + offset);
1240             break;
1241         }
1242         case op_jgreatereq: {
1243             int r0 = (++it)->u.operand;
1244             int r1 = (++it)->u.operand;
1245             int offset = (++it)->u.operand;
1246             printLocationAndOp(out, exec, location, it, "jgreatereq");
1247             out.printf("%s, %s, %d(->%d)", registerName(r0).data(), registerName(r1).data(), offset, location + offset);
1248             break;
1249         }
1250         case op_jnless: {
1251             int r0 = (++it)->u.operand;
1252             int r1 = (++it)->u.operand;
1253             int offset = (++it)->u.operand;
1254             printLocationAndOp(out, exec, location, it, "jnless");
1255             out.printf("%s, %s, %d(->%d)", registerName(r0).data(), registerName(r1).data(), offset, location + offset);
1256             break;
1257         }
1258         case op_jnlesseq: {
1259             int r0 = (++it)->u.operand;
1260             int r1 = (++it)->u.operand;
1261             int offset = (++it)->u.operand;
1262             printLocationAndOp(out, exec, location, it, "jnlesseq");
1263             out.printf("%s, %s, %d(->%d)", registerName(r0).data(), registerName(r1).data(), offset, location + offset);
1264             break;
1265         }
1266         case op_jngreater: {
1267             int r0 = (++it)->u.operand;
1268             int r1 = (++it)->u.operand;
1269             int offset = (++it)->u.operand;
1270             printLocationAndOp(out, exec, location, it, "jngreater");
1271             out.printf("%s, %s, %d(->%d)", registerName(r0).data(), registerName(r1).data(), offset, location + offset);
1272             break;
1273         }
1274         case op_jngreatereq: {
1275             int r0 = (++it)->u.operand;
1276             int r1 = (++it)->u.operand;
1277             int offset = (++it)->u.operand;
1278             printLocationAndOp(out, exec, location, it, "jngreatereq");
1279             out.printf("%s, %s, %d(->%d)", registerName(r0).data(), registerName(r1).data(), offset, location + offset);
1280             break;
1281         }
1282         case op_loop_hint: {
1283             printLocationAndOp(out, exec, location, it, "loop_hint");
1284             break;
1285         }
1286         case op_switch_imm: {
1287             int tableIndex = (++it)->u.operand;
1288             int defaultTarget = (++it)->u.operand;
1289             int scrutineeRegister = (++it)->u.operand;
1290             printLocationAndOp(out, exec, location, it, "switch_imm");
1291             out.printf("%d, %d(->%d), %s", tableIndex, defaultTarget, location + defaultTarget, registerName(scrutineeRegister).data());
1292             break;
1293         }
1294         case op_switch_char: {
1295             int tableIndex = (++it)->u.operand;
1296             int defaultTarget = (++it)->u.operand;
1297             int scrutineeRegister = (++it)->u.operand;
1298             printLocationAndOp(out, exec, location, it, "switch_char");
1299             out.printf("%d, %d(->%d), %s", tableIndex, defaultTarget, location + defaultTarget, registerName(scrutineeRegister).data());
1300             break;
1301         }
1302         case op_switch_string: {
1303             int tableIndex = (++it)->u.operand;
1304             int defaultTarget = (++it)->u.operand;
1305             int scrutineeRegister = (++it)->u.operand;
1306             printLocationAndOp(out, exec, location, it, "switch_string");
1307             out.printf("%d, %d(->%d), %s", tableIndex, defaultTarget, location + defaultTarget, registerName(scrutineeRegister).data());
1308             break;
1309         }
1310         case op_new_func: {
1311             int r0 = (++it)->u.operand;
1312             int r1 = (++it)->u.operand;
1313             int f0 = (++it)->u.operand;
1314             printLocationAndOp(out, exec, location, it, "new_func");
1315             out.printf("%s, %s, f%d", registerName(r0).data(), registerName(r1).data(), f0);
1316             break;
1317         }
1318         case op_new_generator_func: {
1319             int r0 = (++it)->u.operand;
1320             int r1 = (++it)->u.operand;
1321             int f0 = (++it)->u.operand;
1322             printLocationAndOp(out, exec, location, it, "new_generator_func");
1323             out.printf("%s, %s, f%d", registerName(r0).data(), registerName(r1).data(), f0);
1324             break;
1325         }
1326         case op_new_arrow_func_exp: {
1327             int r0 = (++it)->u.operand;
1328             int r1 = (++it)->u.operand;
1329             int f0 = (++it)->u.operand;
1330             int r2 = (++it)->u.operand;
1331             printLocationAndOp(out, exec, location, it, "op_new_arrow_func_exp");
1332             out.printf("%s, %s, f%d, %s", registerName(r0).data(), registerName(r1).data(), f0, registerName(r2).data());
1333             break;
1334         }
1335         case op_new_func_exp: {
1336             int r0 = (++it)->u.operand;
1337             int r1 = (++it)->u.operand;
1338             int f0 = (++it)->u.operand;
1339             printLocationAndOp(out, exec, location, it, "new_func_exp");
1340             out.printf("%s, %s, f%d", registerName(r0).data(), registerName(r1).data(), f0);
1341             break;
1342         }
1343         case op_new_generator_func_exp: {
1344             int r0 = (++it)->u.operand;
1345             int r1 = (++it)->u.operand;
1346             int f0 = (++it)->u.operand;
1347             printLocationAndOp(out, exec, location, it, "new_generator_func_exp");
1348             out.printf("%s, %s, f%d", registerName(r0).data(), registerName(r1).data(), f0);
1349             break;
1350         }
1351         case op_call: {
1352             printCallOp(out, exec, location, it, "call", DumpCaches, hasPrintedProfiling, callLinkInfos);
1353             break;
1354         }
1355         case op_tail_call: {
1356             printCallOp(out, exec, location, it, "tail_call", DumpCaches, hasPrintedProfiling, callLinkInfos);
1357             break;
1358         }
1359         case op_call_eval: {
1360             printCallOp(out, exec, location, it, "call_eval", DontDumpCaches, hasPrintedProfiling, callLinkInfos);
1361             break;
1362         }
1363             
1364         case op_construct_varargs:
1365         case op_call_varargs:
1366         case op_tail_call_varargs: {
1367             int result = (++it)->u.operand;
1368             int callee = (++it)->u.operand;
1369             int thisValue = (++it)->u.operand;
1370             int arguments = (++it)->u.operand;
1371             int firstFreeRegister = (++it)->u.operand;
1372             int varArgOffset = (++it)->u.operand;
1373             ++it;
1374             printLocationAndOp(out, exec, location, it, opcode == op_call_varargs ? "call_varargs" : opcode == op_construct_varargs ? "construct_varargs" : "tail_call_varargs");
1375             out.printf("%s, %s, %s, %s, %d, %d", registerName(result).data(), registerName(callee).data(), registerName(thisValue).data(), registerName(arguments).data(), firstFreeRegister, varArgOffset);
1376             dumpValueProfiling(out, it, hasPrintedProfiling);
1377             break;
1378         }
1379
1380         case op_ret: {
1381             int r0 = (++it)->u.operand;
1382             printLocationOpAndRegisterOperand(out, exec, location, it, "ret", r0);
1383             break;
1384         }
1385         case op_construct: {
1386             printCallOp(out, exec, location, it, "construct", DumpCaches, hasPrintedProfiling, callLinkInfos);
1387             break;
1388         }
1389         case op_strcat: {
1390             int r0 = (++it)->u.operand;
1391             int r1 = (++it)->u.operand;
1392             int count = (++it)->u.operand;
1393             printLocationAndOp(out, exec, location, it, "strcat");
1394             out.printf("%s, %s, %d", registerName(r0).data(), registerName(r1).data(), count);
1395             break;
1396         }
1397         case op_to_primitive: {
1398             int r0 = (++it)->u.operand;
1399             int r1 = (++it)->u.operand;
1400             printLocationAndOp(out, exec, location, it, "to_primitive");
1401             out.printf("%s, %s", registerName(r0).data(), registerName(r1).data());
1402             break;
1403         }
1404         case op_get_enumerable_length: {
1405             int dst = it[1].u.operand;
1406             int base = it[2].u.operand;
1407             printLocationAndOp(out, exec, location, it, "op_get_enumerable_length");
1408             out.printf("%s, %s", registerName(dst).data(), registerName(base).data());
1409             it += OPCODE_LENGTH(op_get_enumerable_length) - 1;
1410             break;
1411         }
1412         case op_has_indexed_property: {
1413             int dst = it[1].u.operand;
1414             int base = it[2].u.operand;
1415             int propertyName = it[3].u.operand;
1416             ArrayProfile* arrayProfile = it[4].u.arrayProfile;
1417             printLocationAndOp(out, exec, location, it, "op_has_indexed_property");
1418             out.printf("%s, %s, %s, %p", registerName(dst).data(), registerName(base).data(), registerName(propertyName).data(), arrayProfile);
1419             it += OPCODE_LENGTH(op_has_indexed_property) - 1;
1420             break;
1421         }
1422         case op_has_structure_property: {
1423             int dst = it[1].u.operand;
1424             int base = it[2].u.operand;
1425             int propertyName = it[3].u.operand;
1426             int enumerator = it[4].u.operand;
1427             printLocationAndOp(out, exec, location, it, "op_has_structure_property");
1428             out.printf("%s, %s, %s, %s", registerName(dst).data(), registerName(base).data(), registerName(propertyName).data(), registerName(enumerator).data());
1429             it += OPCODE_LENGTH(op_has_structure_property) - 1;
1430             break;
1431         }
1432         case op_has_generic_property: {
1433             int dst = it[1].u.operand;
1434             int base = it[2].u.operand;
1435             int propertyName = it[3].u.operand;
1436             printLocationAndOp(out, exec, location, it, "op_has_generic_property");
1437             out.printf("%s, %s, %s", registerName(dst).data(), registerName(base).data(), registerName(propertyName).data());
1438             it += OPCODE_LENGTH(op_has_generic_property) - 1;
1439             break;
1440         }
1441         case op_get_direct_pname: {
1442             int dst = it[1].u.operand;
1443             int base = it[2].u.operand;
1444             int propertyName = it[3].u.operand;
1445             int index = it[4].u.operand;
1446             int enumerator = it[5].u.operand;
1447             ValueProfile* profile = it[6].u.profile;
1448             printLocationAndOp(out, exec, location, it, "op_get_direct_pname");
1449             out.printf("%s, %s, %s, %s, %s, %p", registerName(dst).data(), registerName(base).data(), registerName(propertyName).data(), registerName(index).data(), registerName(enumerator).data(), profile);
1450             it += OPCODE_LENGTH(op_get_direct_pname) - 1;
1451             break;
1452
1453         }
1454         case op_get_property_enumerator: {
1455             int dst = it[1].u.operand;
1456             int base = it[2].u.operand;
1457             printLocationAndOp(out, exec, location, it, "op_get_property_enumerator");
1458             out.printf("%s, %s", registerName(dst).data(), registerName(base).data());
1459             it += OPCODE_LENGTH(op_get_property_enumerator) - 1;
1460             break;
1461         }
1462         case op_enumerator_structure_pname: {
1463             int dst = it[1].u.operand;
1464             int enumerator = it[2].u.operand;
1465             int index = it[3].u.operand;
1466             printLocationAndOp(out, exec, location, it, "op_enumerator_structure_pname");
1467             out.printf("%s, %s, %s", registerName(dst).data(), registerName(enumerator).data(), registerName(index).data());
1468             it += OPCODE_LENGTH(op_enumerator_structure_pname) - 1;
1469             break;
1470         }
1471         case op_enumerator_generic_pname: {
1472             int dst = it[1].u.operand;
1473             int enumerator = it[2].u.operand;
1474             int index = it[3].u.operand;
1475             printLocationAndOp(out, exec, location, it, "op_enumerator_generic_pname");
1476             out.printf("%s, %s, %s", registerName(dst).data(), registerName(enumerator).data(), registerName(index).data());
1477             it += OPCODE_LENGTH(op_enumerator_generic_pname) - 1;
1478             break;
1479         }
1480         case op_to_index_string: {
1481             int dst = it[1].u.operand;
1482             int index = it[2].u.operand;
1483             printLocationAndOp(out, exec, location, it, "op_to_index_string");
1484             out.printf("%s, %s", registerName(dst).data(), registerName(index).data());
1485             it += OPCODE_LENGTH(op_to_index_string) - 1;
1486             break;
1487         }
1488         case op_push_with_scope: {
1489             int dst = (++it)->u.operand;
1490             int newScope = (++it)->u.operand;
1491             int currentScope = (++it)->u.operand;
1492             printLocationAndOp(out, exec, location, it, "push_with_scope");
1493             out.printf("%s, %s, %s", registerName(dst).data(), registerName(newScope).data(), registerName(currentScope).data());
1494             break;
1495         }
1496         case op_get_parent_scope: {
1497             int dst = (++it)->u.operand;
1498             int parentScope = (++it)->u.operand;
1499             printLocationAndOp(out, exec, location, it, "get_parent_scope");
1500             out.printf("%s, %s", registerName(dst).data(), registerName(parentScope).data());
1501             break;
1502         }
1503         case op_create_lexical_environment: {
1504             int dst = (++it)->u.operand;
1505             int scope = (++it)->u.operand;
1506             int symbolTable = (++it)->u.operand;
1507             int initialValue = (++it)->u.operand;
1508             printLocationAndOp(out, exec, location, it, "create_lexical_environment");
1509             out.printf("%s, %s, %s, %s", 
1510                 registerName(dst).data(), registerName(scope).data(), registerName(symbolTable).data(), registerName(initialValue).data());
1511             break;
1512         }
1513         case op_catch: {
1514             int r0 = (++it)->u.operand;
1515             int r1 = (++it)->u.operand;
1516             printLocationAndOp(out, exec, location, it, "catch");
1517             out.printf("%s, %s", registerName(r0).data(), registerName(r1).data());
1518             break;
1519         }
1520         case op_throw: {
1521             int r0 = (++it)->u.operand;
1522             printLocationOpAndRegisterOperand(out, exec, location, it, "throw", r0);
1523             break;
1524         }
1525         case op_throw_static_error: {
1526             int k0 = (++it)->u.operand;
1527             int k1 = (++it)->u.operand;
1528             printLocationAndOp(out, exec, location, it, "throw_static_error");
1529             out.printf("%s, %s", constantName(k0).data(), k1 ? "true" : "false");
1530             break;
1531         }
1532         case op_debug: {
1533             int debugHookID = (++it)->u.operand;
1534             int hasBreakpointFlag = (++it)->u.operand;
1535             printLocationAndOp(out, exec, location, it, "debug");
1536             out.printf("%s, %d", debugHookName(debugHookID), hasBreakpointFlag);
1537             break;
1538         }
1539         case op_save: {
1540             int generator = (++it)->u.operand;
1541             unsigned liveCalleeLocalsIndex = (++it)->u.unsignedValue;
1542             int offset = (++it)->u.operand;
1543             const FastBitVector& liveness = m_rareData->m_liveCalleeLocalsAtYield[liveCalleeLocalsIndex];
1544             printLocationAndOp(out, exec, location, it, "save");
1545             out.printf("%s, ", registerName(generator).data());
1546             liveness.dump(out);
1547             out.printf("(@live%1u), %d(->%d)", liveCalleeLocalsIndex, offset, location + offset);
1548             break;
1549         }
1550         case op_resume: {
1551             int generator = (++it)->u.operand;
1552             unsigned liveCalleeLocalsIndex = (++it)->u.unsignedValue;
1553             const FastBitVector& liveness = m_rareData->m_liveCalleeLocalsAtYield[liveCalleeLocalsIndex];
1554             printLocationAndOp(out, exec, location, it, "resume");
1555             out.printf("%s, ", registerName(generator).data());
1556             liveness.dump(out);
1557             out.printf("(@live%1u)", liveCalleeLocalsIndex);
1558             break;
1559         }
1560         case op_assert: {
1561             int condition = (++it)->u.operand;
1562             int line = (++it)->u.operand;
1563             printLocationAndOp(out, exec, location, it, "assert");
1564             out.printf("%s, %d", registerName(condition).data(), line);
1565             break;
1566         }
1567         case op_profile_will_call: {
1568             int function = (++it)->u.operand;
1569             printLocationOpAndRegisterOperand(out, exec, location, it, "profile_will_call", function);
1570             break;
1571         }
1572         case op_profile_did_call: {
1573             int function = (++it)->u.operand;
1574             printLocationOpAndRegisterOperand(out, exec, location, it, "profile_did_call", function);
1575             break;
1576         }
1577         case op_end: {
1578             int r0 = (++it)->u.operand;
1579             printLocationOpAndRegisterOperand(out, exec, location, it, "end", r0);
1580             break;
1581         }
1582         case op_resolve_scope: {
1583             int r0 = (++it)->u.operand;
1584             int scope = (++it)->u.operand;
1585             int id0 = (++it)->u.operand;
1586             ResolveType resolveType = static_cast<ResolveType>((++it)->u.operand);
1587             int depth = (++it)->u.operand;
1588             void* pointer = (++it)->u.pointer;
1589             printLocationAndOp(out, exec, location, it, "resolve_scope");
1590             out.printf("%s, %s, %s, <%s>, %d, %p", registerName(r0).data(), registerName(scope).data(), idName(id0, identifier(id0)).data(), resolveTypeName(resolveType), depth, pointer);
1591             break;
1592         }
1593         case op_get_from_scope: {
1594             int r0 = (++it)->u.operand;
1595             int r1 = (++it)->u.operand;
1596             int id0 = (++it)->u.operand;
1597             GetPutInfo getPutInfo = GetPutInfo((++it)->u.operand);
1598             ++it; // Structure
1599             int operand = (++it)->u.operand; // Operand
1600             printLocationAndOp(out, exec, location, it, "get_from_scope");
1601             out.print(registerName(r0), ", ", registerName(r1));
1602             if (static_cast<unsigned>(id0) == UINT_MAX)
1603                 out.print(", anonymous");
1604             else
1605                 out.print(", ", idName(id0, identifier(id0)));
1606             out.print(", ", getPutInfo.operand(), "<", resolveModeName(getPutInfo.resolveMode()), "|", resolveTypeName(getPutInfo.resolveType()), "|", initializationModeName(getPutInfo.initializationMode()), ">, ", operand);
1607             dumpValueProfiling(out, it, hasPrintedProfiling);
1608             break;
1609         }
1610         case op_put_to_scope: {
1611             int r0 = (++it)->u.operand;
1612             int id0 = (++it)->u.operand;
1613             int r1 = (++it)->u.operand;
1614             GetPutInfo getPutInfo = GetPutInfo((++it)->u.operand);
1615             ++it; // Structure
1616             int operand = (++it)->u.operand; // Operand
1617             printLocationAndOp(out, exec, location, it, "put_to_scope");
1618             out.print(registerName(r0));
1619             if (static_cast<unsigned>(id0) == UINT_MAX)
1620                 out.print(", anonymous");
1621             else
1622                 out.print(", ", idName(id0, identifier(id0)));
1623             out.print(", ", registerName(r1), ", ", getPutInfo.operand(), "<", resolveModeName(getPutInfo.resolveMode()), "|", resolveTypeName(getPutInfo.resolveType()), "|", initializationModeName(getPutInfo.initializationMode()), ">, <structure>, ", operand);
1624             break;
1625         }
1626         case op_get_from_arguments: {
1627             int r0 = (++it)->u.operand;
1628             int r1 = (++it)->u.operand;
1629             int offset = (++it)->u.operand;
1630             printLocationAndOp(out, exec, location, it, "get_from_arguments");
1631             out.printf("%s, %s, %d", registerName(r0).data(), registerName(r1).data(), offset);
1632             dumpValueProfiling(out, it, hasPrintedProfiling);
1633             break;
1634         }
1635         case op_put_to_arguments: {
1636             int r0 = (++it)->u.operand;
1637             int offset = (++it)->u.operand;
1638             int r1 = (++it)->u.operand;
1639             printLocationAndOp(out, exec, location, it, "put_to_arguments");
1640             out.printf("%s, %d, %s", registerName(r0).data(), offset, registerName(r1).data());
1641             break;
1642         }
1643         default:
1644             RELEASE_ASSERT_NOT_REACHED();
1645     }
1646
1647     dumpRareCaseProfile(out, "rare case: ", rareCaseProfileForBytecodeOffset(location), hasPrintedProfiling);
1648     dumpRareCaseProfile(out, "special fast case: ", specialFastCaseProfileForBytecodeOffset(location), hasPrintedProfiling);
1649     
1650 #if ENABLE(DFG_JIT)
1651     Vector<DFG::FrequentExitSite> exitSites = exitProfile().exitSitesFor(location);
1652     if (!exitSites.isEmpty()) {
1653         out.print(" !! frequent exits: ");
1654         CommaPrinter comma;
1655         for (unsigned i = 0; i < exitSites.size(); ++i)
1656             out.print(comma, exitSites[i].kind(), " ", exitSites[i].jitType());
1657     }
1658 #else // ENABLE(DFG_JIT)
1659     UNUSED_PARAM(location);
1660 #endif // ENABLE(DFG_JIT)
1661     out.print("\n");
1662 }
1663
1664 void CodeBlock::dumpBytecode(
1665     PrintStream& out, unsigned bytecodeOffset,
1666     const StubInfoMap& stubInfos, const CallLinkInfoMap& callLinkInfos)
1667 {
1668     ExecState* exec = m_globalObject->globalExec();
1669     const Instruction* it = instructions().begin() + bytecodeOffset;
1670     dumpBytecode(out, exec, instructions().begin(), it, stubInfos, callLinkInfos);
1671 }
1672
1673 #define FOR_EACH_MEMBER_VECTOR(macro) \
1674     macro(instructions) \
1675     macro(callLinkInfos) \
1676     macro(linkedCallerList) \
1677     macro(identifiers) \
1678     macro(functionExpressions) \
1679     macro(constantRegisters)
1680
1681 #define FOR_EACH_MEMBER_VECTOR_RARE_DATA(macro) \
1682     macro(regexps) \
1683     macro(functions) \
1684     macro(exceptionHandlers) \
1685     macro(switchJumpTables) \
1686     macro(stringSwitchJumpTables) \
1687     macro(evalCodeCache) \
1688     macro(expressionInfo) \
1689     macro(lineInfo) \
1690     macro(callReturnIndexVector)
1691
1692 template<typename T>
1693 static size_t sizeInBytes(const Vector<T>& vector)
1694 {
1695     return vector.capacity() * sizeof(T);
1696 }
1697
1698 namespace {
1699
1700 class PutToScopeFireDetail : public FireDetail {
1701 public:
1702     PutToScopeFireDetail(CodeBlock* codeBlock, const Identifier& ident)
1703         : m_codeBlock(codeBlock)
1704         , m_ident(ident)
1705     {
1706     }
1707     
1708     virtual void dump(PrintStream& out) const override
1709     {
1710         out.print("Linking put_to_scope in ", FunctionExecutableDump(jsCast<FunctionExecutable*>(m_codeBlock->ownerExecutable())), " for ", m_ident);
1711     }
1712     
1713 private:
1714     CodeBlock* m_codeBlock;
1715     const Identifier& m_ident;
1716 };
1717
1718 } // anonymous namespace
1719
1720 CodeBlock::CodeBlock(VM* vm, Structure* structure, CopyParsedBlockTag, CodeBlock& other)
1721     : JSCell(*vm, structure)
1722     , m_globalObject(other.m_globalObject)
1723     , m_heap(other.m_heap)
1724     , m_numCalleeLocals(other.m_numCalleeLocals)
1725     , m_numVars(other.m_numVars)
1726     , m_isConstructor(other.m_isConstructor)
1727     , m_shouldAlwaysBeInlined(true)
1728     , m_didFailFTLCompilation(false)
1729     , m_hasBeenCompiledWithFTL(false)
1730     , m_unlinkedCode(*other.m_vm, this, other.m_unlinkedCode.get())
1731     , m_hasDebuggerStatement(false)
1732     , m_steppingMode(SteppingModeDisabled)
1733     , m_numBreakpoints(0)
1734     , m_ownerExecutable(*other.m_vm, this, other.m_ownerExecutable.get())
1735     , m_vm(other.m_vm)
1736     , m_instructions(other.m_instructions)
1737     , m_thisRegister(other.m_thisRegister)
1738     , m_scopeRegister(other.m_scopeRegister)
1739     , m_lexicalEnvironmentRegister(other.m_lexicalEnvironmentRegister)
1740     , m_isStrictMode(other.m_isStrictMode)
1741     , m_needsActivation(other.m_needsActivation)
1742     , m_source(other.m_source)
1743     , m_sourceOffset(other.m_sourceOffset)
1744     , m_firstLineColumnOffset(other.m_firstLineColumnOffset)
1745     , m_codeType(other.m_codeType)
1746     , m_constantRegisters(other.m_constantRegisters)
1747     , m_constantsSourceCodeRepresentation(other.m_constantsSourceCodeRepresentation)
1748     , m_functionDecls(other.m_functionDecls)
1749     , m_functionExprs(other.m_functionExprs)
1750     , m_osrExitCounter(0)
1751     , m_optimizationDelayCounter(0)
1752     , m_reoptimizationRetryCounter(0)
1753     , m_creationTime(std::chrono::steady_clock::now())
1754     , m_hash(other.m_hash)
1755 #if ENABLE(JIT)
1756     , m_capabilityLevelState(DFG::CapabilityLevelNotSet)
1757 #endif
1758 {
1759     m_visitWeaklyHasBeenCalled.store(false, std::memory_order_relaxed);
1760
1761     ASSERT(m_heap->isDeferred());
1762     ASSERT(m_scopeRegister.isLocal());
1763
1764     setNumParameters(other.numParameters());
1765 }
1766
1767 void CodeBlock::finishCreation(VM& vm, CopyParsedBlockTag, CodeBlock& other)
1768 {
1769     Base::finishCreation(vm);
1770
1771     optimizeAfterWarmUp();
1772     jitAfterWarmUp();
1773
1774     if (other.m_rareData) {
1775         createRareDataIfNecessary();
1776         
1777         m_rareData->m_exceptionHandlers = other.m_rareData->m_exceptionHandlers;
1778         m_rareData->m_constantBuffers = other.m_rareData->m_constantBuffers;
1779         m_rareData->m_switchJumpTables = other.m_rareData->m_switchJumpTables;
1780         m_rareData->m_stringSwitchJumpTables = other.m_rareData->m_stringSwitchJumpTables;
1781         m_rareData->m_liveCalleeLocalsAtYield = other.m_rareData->m_liveCalleeLocalsAtYield;
1782     }
1783     
1784     m_heap->m_codeBlocks.add(this);
1785 }
1786
1787 CodeBlock::CodeBlock(VM* vm, Structure* structure, ScriptExecutable* ownerExecutable, UnlinkedCodeBlock* unlinkedCodeBlock,
1788     JSScope* scope, PassRefPtr<SourceProvider> sourceProvider, unsigned sourceOffset, unsigned firstLineColumnOffset)
1789     : JSCell(*vm, structure)
1790     , m_globalObject(scope->globalObject()->vm(), this, scope->globalObject())
1791     , m_heap(&m_globalObject->vm().heap)
1792     , m_numCalleeLocals(unlinkedCodeBlock->m_numCalleeLocals)
1793     , m_numVars(unlinkedCodeBlock->m_numVars)
1794     , m_isConstructor(unlinkedCodeBlock->isConstructor())
1795     , m_shouldAlwaysBeInlined(true)
1796     , m_didFailFTLCompilation(false)
1797     , m_hasBeenCompiledWithFTL(false)
1798     , m_unlinkedCode(m_globalObject->vm(), this, unlinkedCodeBlock)
1799     , m_hasDebuggerStatement(false)
1800     , m_steppingMode(SteppingModeDisabled)
1801     , m_numBreakpoints(0)
1802     , m_ownerExecutable(m_globalObject->vm(), this, ownerExecutable)
1803     , m_vm(unlinkedCodeBlock->vm())
1804     , m_thisRegister(unlinkedCodeBlock->thisRegister())
1805     , m_scopeRegister(unlinkedCodeBlock->scopeRegister())
1806     , m_lexicalEnvironmentRegister(unlinkedCodeBlock->activationRegister())
1807     , m_isStrictMode(unlinkedCodeBlock->isStrictMode())
1808     , m_needsActivation(unlinkedCodeBlock->hasActivationRegister() && unlinkedCodeBlock->codeType() == FunctionCode)
1809     , m_source(sourceProvider)
1810     , m_sourceOffset(sourceOffset)
1811     , m_firstLineColumnOffset(firstLineColumnOffset)
1812     , m_codeType(unlinkedCodeBlock->codeType())
1813     , m_osrExitCounter(0)
1814     , m_optimizationDelayCounter(0)
1815     , m_reoptimizationRetryCounter(0)
1816     , m_creationTime(std::chrono::steady_clock::now())
1817 #if ENABLE(JIT)
1818     , m_capabilityLevelState(DFG::CapabilityLevelNotSet)
1819 #endif
1820 {
1821     m_visitWeaklyHasBeenCalled.store(false, std::memory_order_relaxed);
1822
1823     ASSERT(m_heap->isDeferred());
1824     ASSERT(m_scopeRegister.isLocal());
1825
1826     ASSERT(m_source);
1827     setNumParameters(unlinkedCodeBlock->numParameters());
1828 }
1829
1830 void CodeBlock::finishCreation(VM& vm, ScriptExecutable* ownerExecutable, UnlinkedCodeBlock* unlinkedCodeBlock,
1831     JSScope* scope)
1832 {
1833     Base::finishCreation(vm);
1834
1835     if (vm.typeProfiler() || vm.controlFlowProfiler())
1836         vm.functionHasExecutedCache()->removeUnexecutedRange(ownerExecutable->sourceID(), ownerExecutable->typeProfilingStartOffset(), ownerExecutable->typeProfilingEndOffset());
1837
1838     setConstantRegisters(unlinkedCodeBlock->constantRegisters(), unlinkedCodeBlock->constantsSourceCodeRepresentation());
1839     if (unlinkedCodeBlock->usesGlobalObject())
1840         m_constantRegisters[unlinkedCodeBlock->globalObjectRegister().toConstantIndex()].set(*m_vm, this, m_globalObject.get());
1841
1842     for (unsigned i = 0; i < LinkTimeConstantCount; i++) {
1843         LinkTimeConstant type = static_cast<LinkTimeConstant>(i);
1844         if (unsigned registerIndex = unlinkedCodeBlock->registerIndexForLinkTimeConstant(type))
1845             m_constantRegisters[registerIndex].set(*m_vm, this, m_globalObject->jsCellForLinkTimeConstant(type));
1846     }
1847
1848     HashSet<int, WTF::IntHash<int>, WTF::UnsignedWithZeroKeyHashTraits<int>> clonedConstantSymbolTables;
1849     {
1850         HashSet<SymbolTable*> clonedSymbolTables;
1851         for (unsigned i = 0; i < m_constantRegisters.size(); i++) {
1852             if (m_constantRegisters[i].get().isEmpty())
1853                 continue;
1854             if (SymbolTable* symbolTable = jsDynamicCast<SymbolTable*>(m_constantRegisters[i].get())) {
1855                 RELEASE_ASSERT(clonedSymbolTables.add(symbolTable).isNewEntry);
1856                 if (m_vm->typeProfiler()) {
1857                     ConcurrentJITLocker locker(symbolTable->m_lock);
1858                     symbolTable->prepareForTypeProfiling(locker);
1859                 }
1860                 m_constantRegisters[i].set(*m_vm, this, symbolTable->cloneScopePart(*m_vm));
1861                 clonedConstantSymbolTables.add(i + FirstConstantRegisterIndex);
1862             }
1863         }
1864     }
1865
1866     // We already have the cloned symbol table for the module environment since we need to instantiate
1867     // the module environments before linking the code block. We replace the stored symbol table with the already cloned one.
1868     if (UnlinkedModuleProgramCodeBlock* unlinkedModuleProgramCodeBlock = jsDynamicCast<UnlinkedModuleProgramCodeBlock*>(unlinkedCodeBlock)) {
1869         SymbolTable* clonedSymbolTable = jsCast<ModuleProgramExecutable*>(ownerExecutable)->moduleEnvironmentSymbolTable();
1870         if (m_vm->typeProfiler()) {
1871             ConcurrentJITLocker locker(clonedSymbolTable->m_lock);
1872             clonedSymbolTable->prepareForTypeProfiling(locker);
1873         }
1874         replaceConstant(unlinkedModuleProgramCodeBlock->moduleEnvironmentSymbolTableConstantRegisterOffset(), clonedSymbolTable);
1875     }
1876
1877     m_functionDecls.resizeToFit(unlinkedCodeBlock->numberOfFunctionDecls());
1878     for (size_t count = unlinkedCodeBlock->numberOfFunctionDecls(), i = 0; i < count; ++i) {
1879         UnlinkedFunctionExecutable* unlinkedExecutable = unlinkedCodeBlock->functionDecl(i);
1880         if (vm.typeProfiler() || vm.controlFlowProfiler())
1881             vm.functionHasExecutedCache()->insertUnexecutedRange(ownerExecutable->sourceID(), unlinkedExecutable->typeProfilingStartOffset(), unlinkedExecutable->typeProfilingEndOffset());
1882         m_functionDecls[i].set(*m_vm, this, unlinkedExecutable->link(*m_vm, ownerExecutable->source()));
1883     }
1884
1885     m_functionExprs.resizeToFit(unlinkedCodeBlock->numberOfFunctionExprs());
1886     for (size_t count = unlinkedCodeBlock->numberOfFunctionExprs(), i = 0; i < count; ++i) {
1887         UnlinkedFunctionExecutable* unlinkedExecutable = unlinkedCodeBlock->functionExpr(i);
1888         if (vm.typeProfiler() || vm.controlFlowProfiler())
1889             vm.functionHasExecutedCache()->insertUnexecutedRange(ownerExecutable->sourceID(), unlinkedExecutable->typeProfilingStartOffset(), unlinkedExecutable->typeProfilingEndOffset());
1890         m_functionExprs[i].set(*m_vm, this, unlinkedExecutable->link(*m_vm, ownerExecutable->source()));
1891     }
1892
1893     if (unlinkedCodeBlock->hasRareData()) {
1894         createRareDataIfNecessary();
1895         if (size_t count = unlinkedCodeBlock->constantBufferCount()) {
1896             m_rareData->m_constantBuffers.grow(count);
1897             for (size_t i = 0; i < count; i++) {
1898                 const UnlinkedCodeBlock::ConstantBuffer& buffer = unlinkedCodeBlock->constantBuffer(i);
1899                 m_rareData->m_constantBuffers[i] = buffer;
1900             }
1901         }
1902         if (size_t count = unlinkedCodeBlock->numberOfExceptionHandlers()) {
1903             m_rareData->m_exceptionHandlers.resizeToFit(count);
1904             for (size_t i = 0; i < count; i++) {
1905                 const UnlinkedHandlerInfo& unlinkedHandler = unlinkedCodeBlock->exceptionHandler(i);
1906                 HandlerInfo& handler = m_rareData->m_exceptionHandlers[i];
1907 #if ENABLE(JIT)
1908                 handler.initialize(unlinkedHandler, CodeLocationLabel(MacroAssemblerCodePtr::createFromExecutableAddress(LLInt::getCodePtr(op_catch))));
1909 #else
1910                 handler.initialize(unlinkedHandler);
1911 #endif
1912             }
1913         }
1914
1915         if (size_t count = unlinkedCodeBlock->numberOfStringSwitchJumpTables()) {
1916             m_rareData->m_stringSwitchJumpTables.grow(count);
1917             for (size_t i = 0; i < count; i++) {
1918                 UnlinkedStringJumpTable::StringOffsetTable::iterator ptr = unlinkedCodeBlock->stringSwitchJumpTable(i).offsetTable.begin();
1919                 UnlinkedStringJumpTable::StringOffsetTable::iterator end = unlinkedCodeBlock->stringSwitchJumpTable(i).offsetTable.end();
1920                 for (; ptr != end; ++ptr) {
1921                     OffsetLocation offset;
1922                     offset.branchOffset = ptr->value;
1923                     m_rareData->m_stringSwitchJumpTables[i].offsetTable.add(ptr->key, offset);
1924                 }
1925             }
1926         }
1927
1928         if (size_t count = unlinkedCodeBlock->numberOfSwitchJumpTables()) {
1929             m_rareData->m_switchJumpTables.grow(count);
1930             for (size_t i = 0; i < count; i++) {
1931                 UnlinkedSimpleJumpTable& sourceTable = unlinkedCodeBlock->switchJumpTable(i);
1932                 SimpleJumpTable& destTable = m_rareData->m_switchJumpTables[i];
1933                 destTable.branchOffsets = sourceTable.branchOffsets;
1934                 destTable.min = sourceTable.min;
1935             }
1936         }
1937     }
1938
1939     // Allocate metadata buffers for the bytecode
1940     if (size_t size = unlinkedCodeBlock->numberOfLLintCallLinkInfos())
1941         m_llintCallLinkInfos.resizeToFit(size);
1942     if (size_t size = unlinkedCodeBlock->numberOfArrayProfiles())
1943         m_arrayProfiles.grow(size);
1944     if (size_t size = unlinkedCodeBlock->numberOfArrayAllocationProfiles())
1945         m_arrayAllocationProfiles.resizeToFit(size);
1946     if (size_t size = unlinkedCodeBlock->numberOfValueProfiles())
1947         m_valueProfiles.resizeToFit(size);
1948     if (size_t size = unlinkedCodeBlock->numberOfObjectAllocationProfiles())
1949         m_objectAllocationProfiles.resizeToFit(size);
1950
1951 #if ENABLE(JIT)
1952     setCalleeSaveRegisters(RegisterSet::llintBaselineCalleeSaveRegisters());
1953 #endif
1954
1955     // Copy and translate the UnlinkedInstructions
1956     unsigned instructionCount = unlinkedCodeBlock->instructions().count();
1957     UnlinkedInstructionStream::Reader instructionReader(unlinkedCodeBlock->instructions());
1958
1959     // Bookkeep the strongly referenced module environments.
1960     HashSet<JSModuleEnvironment*> stronglyReferencedModuleEnvironments;
1961
1962     // Bookkeep the merge point bytecode offsets.
1963     Vector<size_t> mergePointBytecodeOffsets;
1964
1965     RefCountedArray<Instruction> instructions(instructionCount);
1966
1967     for (unsigned i = 0; !instructionReader.atEnd(); ) {
1968         const UnlinkedInstruction* pc = instructionReader.next();
1969
1970         unsigned opLength = opcodeLength(pc[0].u.opcode);
1971
1972         instructions[i] = vm.interpreter->getOpcode(pc[0].u.opcode);
1973         for (size_t j = 1; j < opLength; ++j) {
1974             if (sizeof(int32_t) != sizeof(intptr_t))
1975                 instructions[i + j].u.pointer = 0;
1976             instructions[i + j].u.operand = pc[j].u.operand;
1977         }
1978         switch (pc[0].u.opcode) {
1979         case op_has_indexed_property: {
1980             int arrayProfileIndex = pc[opLength - 1].u.operand;
1981             m_arrayProfiles[arrayProfileIndex] = ArrayProfile(i);
1982
1983             instructions[i + opLength - 1] = &m_arrayProfiles[arrayProfileIndex];
1984             break;
1985         }
1986         case op_call_varargs:
1987         case op_tail_call_varargs:
1988         case op_construct_varargs:
1989         case op_get_by_val: {
1990             int arrayProfileIndex = pc[opLength - 2].u.operand;
1991             m_arrayProfiles[arrayProfileIndex] = ArrayProfile(i);
1992
1993             instructions[i + opLength - 2] = &m_arrayProfiles[arrayProfileIndex];
1994             FALLTHROUGH;
1995         }
1996         case op_get_direct_pname:
1997         case op_get_by_id:
1998         case op_get_from_arguments: {
1999             ValueProfile* profile = &m_valueProfiles[pc[opLength - 1].u.operand];
2000             ASSERT(profile->m_bytecodeOffset == -1);
2001             profile->m_bytecodeOffset = i;
2002             instructions[i + opLength - 1] = profile;
2003             break;
2004         }
2005         case op_put_by_val: {
2006             int arrayProfileIndex = pc[opLength - 1].u.operand;
2007             m_arrayProfiles[arrayProfileIndex] = ArrayProfile(i);
2008             instructions[i + opLength - 1] = &m_arrayProfiles[arrayProfileIndex];
2009             break;
2010         }
2011         case op_put_by_val_direct: {
2012             int arrayProfileIndex = pc[opLength - 1].u.operand;
2013             m_arrayProfiles[arrayProfileIndex] = ArrayProfile(i);
2014             instructions[i + opLength - 1] = &m_arrayProfiles[arrayProfileIndex];
2015             break;
2016         }
2017
2018         case op_new_array:
2019         case op_new_array_buffer:
2020         case op_new_array_with_size: {
2021             int arrayAllocationProfileIndex = pc[opLength - 1].u.operand;
2022             instructions[i + opLength - 1] = &m_arrayAllocationProfiles[arrayAllocationProfileIndex];
2023             break;
2024         }
2025         case op_new_object: {
2026             int objectAllocationProfileIndex = pc[opLength - 1].u.operand;
2027             ObjectAllocationProfile* objectAllocationProfile = &m_objectAllocationProfiles[objectAllocationProfileIndex];
2028             int inferredInlineCapacity = pc[opLength - 2].u.operand;
2029
2030             instructions[i + opLength - 1] = objectAllocationProfile;
2031             objectAllocationProfile->initialize(vm,
2032                 this, m_globalObject->objectPrototype(), inferredInlineCapacity);
2033             break;
2034         }
2035
2036         case op_call:
2037         case op_tail_call:
2038         case op_call_eval: {
2039             ValueProfile* profile = &m_valueProfiles[pc[opLength - 1].u.operand];
2040             ASSERT(profile->m_bytecodeOffset == -1);
2041             profile->m_bytecodeOffset = i;
2042             instructions[i + opLength - 1] = profile;
2043             int arrayProfileIndex = pc[opLength - 2].u.operand;
2044             m_arrayProfiles[arrayProfileIndex] = ArrayProfile(i);
2045             instructions[i + opLength - 2] = &m_arrayProfiles[arrayProfileIndex];
2046             instructions[i + 5] = &m_llintCallLinkInfos[pc[5].u.operand];
2047             break;
2048         }
2049         case op_construct: {
2050             instructions[i + 5] = &m_llintCallLinkInfos[pc[5].u.operand];
2051             ValueProfile* profile = &m_valueProfiles[pc[opLength - 1].u.operand];
2052             ASSERT(profile->m_bytecodeOffset == -1);
2053             profile->m_bytecodeOffset = i;
2054             instructions[i + opLength - 1] = profile;
2055             break;
2056         }
2057         case op_get_array_length:
2058             CRASH();
2059
2060         case op_create_lexical_environment: {
2061             int symbolTableIndex = pc[3].u.operand;
2062             RELEASE_ASSERT(clonedConstantSymbolTables.contains(symbolTableIndex));
2063             break;
2064         }
2065
2066         case op_resolve_scope: {
2067             const Identifier& ident = identifier(pc[3].u.operand);
2068             ResolveType type = static_cast<ResolveType>(pc[4].u.operand);
2069             RELEASE_ASSERT(type != LocalClosureVar);
2070             int localScopeDepth = pc[5].u.operand;
2071
2072             ResolveOp op = JSScope::abstractResolve(m_globalObject->globalExec(), localScopeDepth, scope, ident, Get, type, NotInitialization);
2073             instructions[i + 4].u.operand = op.type;
2074             instructions[i + 5].u.operand = op.depth;
2075             if (op.lexicalEnvironment) {
2076                 if (op.type == ModuleVar) {
2077                     // Keep the linked module environment strongly referenced.
2078                     if (stronglyReferencedModuleEnvironments.add(jsCast<JSModuleEnvironment*>(op.lexicalEnvironment)).isNewEntry)
2079                         addConstant(op.lexicalEnvironment);
2080                     instructions[i + 6].u.jsCell.set(vm, this, op.lexicalEnvironment);
2081                 } else
2082                     instructions[i + 6].u.symbolTable.set(vm, this, op.lexicalEnvironment->symbolTable());
2083             } else if (JSScope* constantScope = JSScope::constantScopeForCodeBlock(op.type, this))
2084                 instructions[i + 6].u.jsCell.set(vm, this, constantScope);
2085             else
2086                 instructions[i + 6].u.pointer = nullptr;
2087             break;
2088         }
2089
2090         case op_get_from_scope: {
2091             ValueProfile* profile = &m_valueProfiles[pc[opLength - 1].u.operand];
2092             ASSERT(profile->m_bytecodeOffset == -1);
2093             profile->m_bytecodeOffset = i;
2094             instructions[i + opLength - 1] = profile;
2095
2096             // get_from_scope dst, scope, id, GetPutInfo, Structure, Operand
2097
2098             int localScopeDepth = pc[5].u.operand;
2099             instructions[i + 5].u.pointer = nullptr;
2100
2101             GetPutInfo getPutInfo = GetPutInfo(pc[4].u.operand);
2102             ASSERT(getPutInfo.initializationMode() == NotInitialization);
2103             if (getPutInfo.resolveType() == LocalClosureVar) {
2104                 instructions[i + 4] = GetPutInfo(getPutInfo.resolveMode(), ClosureVar, getPutInfo.initializationMode()).operand();
2105                 break;
2106             }
2107
2108             const Identifier& ident = identifier(pc[3].u.operand);
2109             ResolveOp op = JSScope::abstractResolve(m_globalObject->globalExec(), localScopeDepth, scope, ident, Get, getPutInfo.resolveType(), NotInitialization);
2110
2111             instructions[i + 4].u.operand = GetPutInfo(getPutInfo.resolveMode(), op.type, getPutInfo.initializationMode()).operand();
2112             if (op.type == ModuleVar)
2113                 instructions[i + 4].u.operand = GetPutInfo(getPutInfo.resolveMode(), ClosureVar, getPutInfo.initializationMode()).operand();
2114             if (op.type == GlobalVar || op.type == GlobalVarWithVarInjectionChecks || op.type == GlobalLexicalVar || op.type == GlobalLexicalVarWithVarInjectionChecks)
2115                 instructions[i + 5].u.watchpointSet = op.watchpointSet;
2116             else if (op.structure)
2117                 instructions[i + 5].u.structure.set(vm, this, op.structure);
2118             instructions[i + 6].u.pointer = reinterpret_cast<void*>(op.operand);
2119             break;
2120         }
2121
2122         case op_put_to_scope: {
2123             // put_to_scope scope, id, value, GetPutInfo, Structure, Operand
2124             GetPutInfo getPutInfo = GetPutInfo(pc[4].u.operand);
2125             if (getPutInfo.resolveType() == LocalClosureVar) {
2126                 // Only do watching if the property we're putting to is not anonymous.
2127                 if (static_cast<unsigned>(pc[2].u.operand) != UINT_MAX) {
2128                     int symbolTableIndex = pc[5].u.operand;
2129                     RELEASE_ASSERT(clonedConstantSymbolTables.contains(symbolTableIndex));
2130                     SymbolTable* symbolTable = jsCast<SymbolTable*>(getConstant(symbolTableIndex));
2131                     const Identifier& ident = identifier(pc[2].u.operand);
2132                     ConcurrentJITLocker locker(symbolTable->m_lock);
2133                     auto iter = symbolTable->find(locker, ident.impl());
2134                     RELEASE_ASSERT(iter != symbolTable->end(locker));
2135                     iter->value.prepareToWatch();
2136                     instructions[i + 5].u.watchpointSet = iter->value.watchpointSet();
2137                 } else
2138                     instructions[i + 5].u.watchpointSet = nullptr;
2139                 break;
2140             }
2141
2142             const Identifier& ident = identifier(pc[2].u.operand);
2143             int localScopeDepth = pc[5].u.operand;
2144             instructions[i + 5].u.pointer = nullptr;
2145             ResolveOp op = JSScope::abstractResolve(m_globalObject->globalExec(), localScopeDepth, scope, ident, Put, getPutInfo.resolveType(), getPutInfo.initializationMode());
2146
2147             instructions[i + 4].u.operand = GetPutInfo(getPutInfo.resolveMode(), op.type, getPutInfo.initializationMode()).operand();
2148             if (op.type == GlobalVar || op.type == GlobalVarWithVarInjectionChecks || op.type == GlobalLexicalVar || op.type == GlobalLexicalVarWithVarInjectionChecks)
2149                 instructions[i + 5].u.watchpointSet = op.watchpointSet;
2150             else if (op.type == ClosureVar || op.type == ClosureVarWithVarInjectionChecks) {
2151                 if (op.watchpointSet)
2152                     op.watchpointSet->invalidate(PutToScopeFireDetail(this, ident));
2153             } else if (op.structure)
2154                 instructions[i + 5].u.structure.set(vm, this, op.structure);
2155             instructions[i + 6].u.pointer = reinterpret_cast<void*>(op.operand);
2156
2157             break;
2158         }
2159
2160         case op_profile_type: {
2161             RELEASE_ASSERT(vm.typeProfiler());
2162             // The format of this instruction is: op_profile_type regToProfile, TypeLocation*, flag, identifier?, resolveType?
2163             size_t instructionOffset = i + opLength - 1;
2164             unsigned divotStart, divotEnd;
2165             GlobalVariableID globalVariableID = 0;
2166             RefPtr<TypeSet> globalTypeSet;
2167             bool shouldAnalyze = m_unlinkedCode->typeProfilerExpressionInfoForBytecodeOffset(instructionOffset, divotStart, divotEnd);
2168             VirtualRegister profileRegister(pc[1].u.operand);
2169             ProfileTypeBytecodeFlag flag = static_cast<ProfileTypeBytecodeFlag>(pc[3].u.operand);
2170             SymbolTable* symbolTable = nullptr;
2171
2172             switch (flag) {
2173             case ProfileTypeBytecodeClosureVar: {
2174                 const Identifier& ident = identifier(pc[4].u.operand);
2175                 int localScopeDepth = pc[2].u.operand;
2176                 ResolveType type = static_cast<ResolveType>(pc[5].u.operand);
2177                 // Even though type profiling may be profiling either a Get or a Put, we can always claim a Get because
2178                 // we're abstractly "read"ing from a JSScope.
2179                 ResolveOp op = JSScope::abstractResolve(m_globalObject->globalExec(), localScopeDepth, scope, ident, Get, type, NotInitialization);
2180
2181                 if (op.type == ClosureVar || op.type == ModuleVar)
2182                     symbolTable = op.lexicalEnvironment->symbolTable();
2183                 else if (op.type == GlobalVar)
2184                     symbolTable = m_globalObject.get()->symbolTable();
2185
2186                 UniquedStringImpl* impl = (op.type == ModuleVar) ? op.importedName.get() : ident.impl();
2187                 if (symbolTable) {
2188                     ConcurrentJITLocker locker(symbolTable->m_lock);
2189                     // If our parent scope was created while profiling was disabled, it will not have prepared for profiling yet.
2190                     symbolTable->prepareForTypeProfiling(locker);
2191                     globalVariableID = symbolTable->uniqueIDForVariable(locker, impl, vm);
2192                     globalTypeSet = symbolTable->globalTypeSetForVariable(locker, impl, vm);
2193                 } else
2194                     globalVariableID = TypeProfilerNoGlobalIDExists;
2195
2196                 break;
2197             }
2198             case ProfileTypeBytecodeLocallyResolved: {
2199                 int symbolTableIndex = pc[2].u.operand;
2200                 RELEASE_ASSERT(clonedConstantSymbolTables.contains(symbolTableIndex));
2201                 SymbolTable* symbolTable = jsCast<SymbolTable*>(getConstant(symbolTableIndex));
2202                 const Identifier& ident = identifier(pc[4].u.operand);
2203                 ConcurrentJITLocker locker(symbolTable->m_lock);
2204                 // If our parent scope was created while profiling was disabled, it will not have prepared for profiling yet.
2205                 globalVariableID = symbolTable->uniqueIDForVariable(locker, ident.impl(), vm);
2206                 globalTypeSet = symbolTable->globalTypeSetForVariable(locker, ident.impl(), vm);
2207
2208                 break;
2209             }
2210             case ProfileTypeBytecodeDoesNotHaveGlobalID: 
2211             case ProfileTypeBytecodeFunctionArgument: {
2212                 globalVariableID = TypeProfilerNoGlobalIDExists;
2213                 break;
2214             }
2215             case ProfileTypeBytecodeFunctionReturnStatement: {
2216                 RELEASE_ASSERT(ownerExecutable->isFunctionExecutable());
2217                 globalTypeSet = jsCast<FunctionExecutable*>(ownerExecutable)->returnStatementTypeSet();
2218                 globalVariableID = TypeProfilerReturnStatement;
2219                 if (!shouldAnalyze) {
2220                     // Because a return statement can be added implicitly to return undefined at the end of a function,
2221                     // and these nodes don't emit expression ranges because they aren't in the actual source text of
2222                     // the user's program, give the type profiler some range to identify these return statements.
2223                     // Currently, the text offset that is used as identification is "f" in the function keyword
2224                     // and is stored on TypeLocation's m_divotForFunctionOffsetIfReturnStatement member variable.
2225                     divotStart = divotEnd = ownerExecutable->typeProfilingStartOffset();
2226                     shouldAnalyze = true;
2227                 }
2228                 break;
2229             }
2230             }
2231
2232             std::pair<TypeLocation*, bool> locationPair = vm.typeProfiler()->typeLocationCache()->getTypeLocation(globalVariableID,
2233                 ownerExecutable->sourceID(), divotStart, divotEnd, globalTypeSet, &vm);
2234             TypeLocation* location = locationPair.first;
2235             bool isNewLocation = locationPair.second;
2236
2237             if (flag == ProfileTypeBytecodeFunctionReturnStatement)
2238                 location->m_divotForFunctionOffsetIfReturnStatement = ownerExecutable->typeProfilingStartOffset();
2239
2240             if (shouldAnalyze && isNewLocation)
2241                 vm.typeProfiler()->insertNewLocation(location);
2242
2243             instructions[i + 2].u.location = location;
2244             break;
2245         }
2246
2247         case op_debug: {
2248             if (pc[1].u.index == DidReachBreakpoint)
2249                 m_hasDebuggerStatement = true;
2250             break;
2251         }
2252
2253         case op_save: {
2254             unsigned liveCalleeLocalsIndex = pc[2].u.index;
2255             int offset = pc[3].u.operand;
2256             if (liveCalleeLocalsIndex >= mergePointBytecodeOffsets.size())
2257                 mergePointBytecodeOffsets.resize(liveCalleeLocalsIndex + 1);
2258             mergePointBytecodeOffsets[liveCalleeLocalsIndex] = i + offset;
2259             break;
2260         }
2261
2262         default:
2263             break;
2264         }
2265         i += opLength;
2266     }
2267
2268     if (vm.controlFlowProfiler())
2269         insertBasicBlockBoundariesForControlFlowProfiler(instructions);
2270
2271     m_instructions = WTF::move(instructions);
2272
2273     // Perform bytecode liveness analysis to determine which locals are live and should be resumed when executing op_resume.
2274     if (unlinkedCodeBlock->parseMode() == SourceParseMode::GeneratorBodyMode) {
2275         if (size_t count = mergePointBytecodeOffsets.size()) {
2276             createRareDataIfNecessary();
2277             BytecodeLivenessAnalysis liveness(this);
2278             m_rareData->m_liveCalleeLocalsAtYield.grow(count);
2279             size_t liveCalleeLocalsIndex = 0;
2280             for (size_t bytecodeOffset : mergePointBytecodeOffsets) {
2281                 m_rareData->m_liveCalleeLocalsAtYield[liveCalleeLocalsIndex] = liveness.getLivenessInfoAtBytecodeOffset(bytecodeOffset);
2282                 ++liveCalleeLocalsIndex;
2283             }
2284         }
2285     }
2286
2287     // Set optimization thresholds only after m_instructions is initialized, since these
2288     // rely on the instruction count (and are in theory permitted to also inspect the
2289     // instruction stream to more accurate assess the cost of tier-up).
2290     optimizeAfterWarmUp();
2291     jitAfterWarmUp();
2292
2293     // If the concurrent thread will want the code block's hash, then compute it here
2294     // synchronously.
2295     if (Options::alwaysComputeHash())
2296         hash();
2297
2298     if (Options::dumpGeneratedBytecodes())
2299         dumpBytecode();
2300     
2301     m_heap->m_codeBlocks.add(this);
2302     m_heap->reportExtraMemoryAllocated(m_instructions.size() * sizeof(Instruction));
2303 }
2304
2305 #if ENABLE(WEBASSEMBLY)
2306 CodeBlock::CodeBlock(VM* vm, Structure* structure, WebAssemblyExecutable* ownerExecutable, JSGlobalObject* globalObject)
2307     : JSCell(*vm, structure)
2308     , m_globalObject(globalObject->vm(), this, globalObject)
2309     , m_heap(&m_globalObject->vm().heap)
2310     , m_numCalleeLocals(0)
2311     , m_numVars(0)
2312     , m_isConstructor(false)
2313     , m_shouldAlwaysBeInlined(false)
2314     , m_didFailFTLCompilation(false)
2315     , m_hasBeenCompiledWithFTL(false)
2316     , m_hasDebuggerStatement(false)
2317     , m_steppingMode(SteppingModeDisabled)
2318     , m_numBreakpoints(0)
2319     , m_ownerExecutable(m_globalObject->vm(), this, ownerExecutable)
2320     , m_vm(vm)
2321     , m_isStrictMode(false)
2322     , m_needsActivation(false)
2323     , m_codeType(FunctionCode)
2324     , m_osrExitCounter(0)
2325     , m_optimizationDelayCounter(0)
2326     , m_reoptimizationRetryCounter(0)
2327     , m_creationTime(std::chrono::steady_clock::now())
2328 #if ENABLE(JIT)
2329     , m_capabilityLevelState(DFG::CannotCompile)
2330 #endif
2331 {
2332     ASSERT(m_heap->isDeferred());
2333 }
2334
2335 void CodeBlock::finishCreation(VM& vm, WebAssemblyExecutable*, JSGlobalObject*)
2336 {
2337     Base::finishCreation(vm);
2338
2339     m_heap->m_codeBlocks.add(this);
2340 }
2341 #endif
2342
2343 CodeBlock::~CodeBlock()
2344 {
2345     if (m_vm->m_perBytecodeProfiler)
2346         m_vm->m_perBytecodeProfiler->notifyDestruction(this);
2347     
2348 #if ENABLE(VERBOSE_VALUE_PROFILE)
2349     dumpValueProfiles();
2350 #endif
2351
2352     // We may be destroyed before any CodeBlocks that refer to us are destroyed.
2353     // Consider that two CodeBlocks become unreachable at the same time. There
2354     // is no guarantee about the order in which the CodeBlocks are destroyed.
2355     // So, if we don't remove incoming calls, and get destroyed before the
2356     // CodeBlock(s) that have calls into us, then the CallLinkInfo vector's
2357     // destructor will try to remove nodes from our (no longer valid) linked list.
2358     unlinkIncomingCalls();
2359     
2360     // Note that our outgoing calls will be removed from other CodeBlocks'
2361     // m_incomingCalls linked lists through the execution of the ~CallLinkInfo
2362     // destructors.
2363
2364 #if ENABLE(JIT)
2365     for (Bag<StructureStubInfo>::iterator iter = m_stubInfos.begin(); !!iter; ++iter) {
2366         StructureStubInfo* stub = *iter;
2367         stub->aboutToDie();
2368         stub->deref();
2369     }
2370 #endif // ENABLE(JIT)
2371 }
2372
2373 void CodeBlock::setAlternative(VM& vm, CodeBlock* alternative)
2374 {
2375     m_alternative.set(vm, this, alternative);
2376 }
2377
2378 void CodeBlock::setNumParameters(int newValue)
2379 {
2380     m_numParameters = newValue;
2381
2382     m_argumentValueProfiles.resizeToFit(newValue);
2383 }
2384
2385 void EvalCodeCache::visitAggregate(SlotVisitor& visitor)
2386 {
2387     EvalCacheMap::iterator end = m_cacheMap.end();
2388     for (EvalCacheMap::iterator ptr = m_cacheMap.begin(); ptr != end; ++ptr)
2389         visitor.append(&ptr->value);
2390 }
2391
2392 CodeBlock* CodeBlock::specialOSREntryBlockOrNull()
2393 {
2394 #if ENABLE(FTL_JIT)
2395     if (jitType() != JITCode::DFGJIT)
2396         return 0;
2397     DFG::JITCode* jitCode = m_jitCode->dfg();
2398     return jitCode->osrEntryBlock();
2399 #else // ENABLE(FTL_JIT)
2400     return 0;
2401 #endif // ENABLE(FTL_JIT)
2402 }
2403
2404 void CodeBlock::visitWeakly(SlotVisitor& visitor)
2405 {
2406     bool setByMe = m_visitWeaklyHasBeenCalled.compareExchangeStrong(false, true);
2407     if (!setByMe)
2408         return;
2409
2410     if (Heap::isMarked(this))
2411         return;
2412
2413     if (shouldVisitStrongly()) {
2414         visitor.appendUnbarrieredReadOnlyPointer(this);
2415         return;
2416     }
2417
2418     // There are two things that may use unconditional finalizers: inline cache clearing
2419     // and jettisoning. The probability of us wanting to do at least one of those things
2420     // is probably quite close to 1. So we add one no matter what and when it runs, it
2421     // figures out whether it has any work to do.
2422     visitor.addUnconditionalFinalizer(&m_unconditionalFinalizer);
2423
2424     if (!JITCode::isOptimizingJIT(jitType()))
2425         return;
2426
2427     // If we jettison ourselves we'll install our alternative, so make sure that it
2428     // survives GC even if we don't.
2429     visitor.append(&m_alternative);
2430     
2431     // There are two things that we use weak reference harvesters for: DFG fixpoint for
2432     // jettisoning, and trying to find structures that would be live based on some
2433     // inline cache. So it makes sense to register them regardless.
2434     visitor.addWeakReferenceHarvester(&m_weakReferenceHarvester);
2435
2436 #if ENABLE(DFG_JIT)
2437     // We get here if we're live in the sense that our owner executable is live,
2438     // but we're not yet live for sure in another sense: we may yet decide that this
2439     // code block should be jettisoned based on its outgoing weak references being
2440     // stale. Set a flag to indicate that we're still assuming that we're dead, and
2441     // perform one round of determining if we're live. The GC may determine, based on
2442     // either us marking additional objects, or by other objects being marked for
2443     // other reasons, that this iteration should run again; it will notify us of this
2444     // decision by calling harvestWeakReferences().
2445
2446     m_allTransitionsHaveBeenMarked = false;
2447     propagateTransitions(visitor);
2448
2449     m_jitCode->dfgCommon()->livenessHasBeenProved = false;
2450     determineLiveness(visitor);
2451 #endif // ENABLE(DFG_JIT)
2452 }
2453
2454 void CodeBlock::visitChildren(JSCell* cell, SlotVisitor& visitor)
2455 {
2456     CodeBlock* thisObject = jsCast<CodeBlock*>(cell);
2457     ASSERT_GC_OBJECT_INHERITS(thisObject, info());
2458     JSCell::visitChildren(thisObject, visitor);
2459     thisObject->visitChildren(visitor);
2460 }
2461
2462 void CodeBlock::visitChildren(SlotVisitor& visitor)
2463 {
2464     // There are two things that may use unconditional finalizers: inline cache clearing
2465     // and jettisoning. The probability of us wanting to do at least one of those things
2466     // is probably quite close to 1. So we add one no matter what and when it runs, it
2467     // figures out whether it has any work to do.
2468     visitor.addUnconditionalFinalizer(&m_unconditionalFinalizer);
2469
2470     if (CodeBlock* otherBlock = specialOSREntryBlockOrNull())
2471         visitor.appendUnbarrieredReadOnlyPointer(otherBlock);
2472
2473     if (m_jitCode)
2474         visitor.reportExtraMemoryVisited(m_jitCode->size());
2475     if (m_instructions.size())
2476         visitor.reportExtraMemoryVisited(m_instructions.size() * sizeof(Instruction) / m_instructions.refCount());
2477
2478     visitor.append(&m_unlinkedCode);
2479
2480     stronglyVisitStrongReferences(visitor);
2481     stronglyVisitWeakReferences(visitor);
2482
2483     m_allTransitionsHaveBeenMarked = false;
2484     propagateTransitions(visitor);
2485 }
2486
2487 bool CodeBlock::shouldVisitStrongly()
2488 {
2489     if (Options::forceCodeBlockLiveness())
2490         return true;
2491
2492     if (shouldJettisonDueToOldAge())
2493         return false;
2494
2495     // Interpreter and Baseline JIT CodeBlocks don't need to be jettisoned when
2496     // their weak references go stale. So if a basline JIT CodeBlock gets
2497     // scanned, we can assume that this means that it's live.
2498     if (!JITCode::isOptimizingJIT(jitType()))
2499         return true;
2500
2501     return false;
2502 }
2503
2504 bool CodeBlock::shouldJettisonDueToWeakReference()
2505 {
2506     if (!JITCode::isOptimizingJIT(jitType()))
2507         return false;
2508     return !Heap::isMarked(this);
2509 }
2510
2511 bool CodeBlock::shouldJettisonDueToOldAge()
2512 {
2513     return false;
2514 }
2515
2516 #if ENABLE(DFG_JIT)
2517 static bool shouldMarkTransition(DFG::WeakReferenceTransition& transition)
2518 {
2519     if (transition.m_codeOrigin && !Heap::isMarked(transition.m_codeOrigin.get()))
2520         return false;
2521     
2522     if (!Heap::isMarked(transition.m_from.get()))
2523         return false;
2524     
2525     return true;
2526 }
2527 #endif // ENABLE(DFG_JIT)
2528
2529 void CodeBlock::propagateTransitions(SlotVisitor& visitor)
2530 {
2531     UNUSED_PARAM(visitor);
2532
2533     if (m_allTransitionsHaveBeenMarked)
2534         return;
2535
2536     bool allAreMarkedSoFar = true;
2537         
2538     Interpreter* interpreter = m_vm->interpreter;
2539     if (jitType() == JITCode::InterpreterThunk) {
2540         const Vector<unsigned>& propertyAccessInstructions = m_unlinkedCode->propertyAccessInstructions();
2541         for (size_t i = 0; i < propertyAccessInstructions.size(); ++i) {
2542             Instruction* instruction = &instructions()[propertyAccessInstructions[i]];
2543             switch (interpreter->getOpcodeID(instruction[0].u.opcode)) {
2544             case op_put_by_id: {
2545                 StructureID oldStructureID = instruction[4].u.structureID;
2546                 StructureID newStructureID = instruction[6].u.structureID;
2547                 if (!oldStructureID || !newStructureID)
2548                     break;
2549                 Structure* oldStructure =
2550                     m_vm->heap.structureIDTable().get(oldStructureID);
2551                 Structure* newStructure =
2552                     m_vm->heap.structureIDTable().get(newStructureID);
2553                 if (Heap::isMarked(oldStructure))
2554                     visitor.appendUnbarrieredReadOnlyPointer(newStructure);
2555                 else
2556                     allAreMarkedSoFar = false;
2557                 break;
2558             }
2559             default:
2560                 break;
2561             }
2562         }
2563     }
2564
2565 #if ENABLE(JIT)
2566     if (JITCode::isJIT(jitType())) {
2567         for (Bag<StructureStubInfo>::iterator iter = m_stubInfos.begin(); !!iter; ++iter) {
2568             StructureStubInfo& stubInfo = **iter;
2569             if (stubInfo.cacheType != CacheType::Stub)
2570                 continue;
2571             PolymorphicAccess* list = stubInfo.u.stub;
2572             JSCell* origin = stubInfo.codeOrigin.codeOriginOwner();
2573             if (origin && !Heap::isMarked(origin)) {
2574                 allAreMarkedSoFar = false;
2575                 continue;
2576             }
2577             for (unsigned j = list->size(); j--;) {
2578                 const AccessCase& access = list->at(j);
2579                 if (access.type() != AccessCase::Transition)
2580                     continue;
2581                 if (Heap::isMarked(access.structure()))
2582                     visitor.appendUnbarrieredReadOnlyPointer(access.newStructure());
2583                 else
2584                     allAreMarkedSoFar = false;
2585             }
2586         }
2587     }
2588 #endif // ENABLE(JIT)
2589     
2590 #if ENABLE(DFG_JIT)
2591     if (JITCode::isOptimizingJIT(jitType())) {
2592         DFG::CommonData* dfgCommon = m_jitCode->dfgCommon();
2593         
2594         for (unsigned i = 0; i < dfgCommon->transitions.size(); ++i) {
2595             if (shouldMarkTransition(dfgCommon->transitions[i])) {
2596                 // If the following three things are live, then the target of the
2597                 // transition is also live:
2598                 //
2599                 // - This code block. We know it's live already because otherwise
2600                 //   we wouldn't be scanning ourselves.
2601                 //
2602                 // - The code origin of the transition. Transitions may arise from
2603                 //   code that was inlined. They are not relevant if the user's
2604                 //   object that is required for the inlinee to run is no longer
2605                 //   live.
2606                 //
2607                 // - The source of the transition. The transition checks if some
2608                 //   heap location holds the source, and if so, stores the target.
2609                 //   Hence the source must be live for the transition to be live.
2610                 //
2611                 // We also short-circuit the liveness if the structure is harmless
2612                 // to mark (i.e. its global object and prototype are both already
2613                 // live).
2614                 
2615                 visitor.append(&dfgCommon->transitions[i].m_to);
2616             } else
2617                 allAreMarkedSoFar = false;
2618         }
2619     }
2620 #endif // ENABLE(DFG_JIT)
2621     
2622     if (allAreMarkedSoFar)
2623         m_allTransitionsHaveBeenMarked = true;
2624 }
2625
2626 void CodeBlock::determineLiveness(SlotVisitor& visitor)
2627 {
2628     UNUSED_PARAM(visitor);
2629     
2630 #if ENABLE(DFG_JIT)
2631     // Check if we have any remaining work to do.
2632     DFG::CommonData* dfgCommon = m_jitCode->dfgCommon();
2633     if (dfgCommon->livenessHasBeenProved)
2634         return;
2635     
2636     // Now check all of our weak references. If all of them are live, then we
2637     // have proved liveness and so we scan our strong references. If at end of
2638     // GC we still have not proved liveness, then this code block is toast.
2639     bool allAreLiveSoFar = true;
2640     for (unsigned i = 0; i < dfgCommon->weakReferences.size(); ++i) {
2641         if (!Heap::isMarked(dfgCommon->weakReferences[i].get())) {
2642             allAreLiveSoFar = false;
2643             break;
2644         }
2645     }
2646     if (allAreLiveSoFar) {
2647         for (unsigned i = 0; i < dfgCommon->weakStructureReferences.size(); ++i) {
2648             if (!Heap::isMarked(dfgCommon->weakStructureReferences[i].get())) {
2649                 allAreLiveSoFar = false;
2650                 break;
2651             }
2652         }
2653     }
2654     
2655     // If some weak references are dead, then this fixpoint iteration was
2656     // unsuccessful.
2657     if (!allAreLiveSoFar)
2658         return;
2659     
2660     // All weak references are live. Record this information so we don't
2661     // come back here again, and scan the strong references.
2662     dfgCommon->livenessHasBeenProved = true;
2663     visitor.appendUnbarrieredReadOnlyPointer(this);
2664 #endif // ENABLE(DFG_JIT)
2665 }
2666
2667 void CodeBlock::WeakReferenceHarvester::visitWeakReferences(SlotVisitor& visitor)
2668 {
2669     CodeBlock* codeBlock =
2670         bitwise_cast<CodeBlock*>(
2671             bitwise_cast<char*>(this) - OBJECT_OFFSETOF(CodeBlock, m_weakReferenceHarvester));
2672
2673     codeBlock->propagateTransitions(visitor);
2674     codeBlock->determineLiveness(visitor);
2675 }
2676
2677 void CodeBlock::finalizeLLIntInlineCaches()
2678 {
2679 #if ENABLE(WEBASSEMBLY)
2680     if (m_ownerExecutable->isWebAssemblyExecutable())
2681         return;
2682 #endif
2683
2684     Interpreter* interpreter = m_vm->interpreter;
2685     const Vector<unsigned>& propertyAccessInstructions = m_unlinkedCode->propertyAccessInstructions();
2686     for (size_t size = propertyAccessInstructions.size(), i = 0; i < size; ++i) {
2687         Instruction* curInstruction = &instructions()[propertyAccessInstructions[i]];
2688         switch (interpreter->getOpcodeID(curInstruction[0].u.opcode)) {
2689         case op_get_by_id: {
2690             StructureID oldStructureID = curInstruction[4].u.structureID;
2691             if (!oldStructureID || Heap::isMarked(m_vm->heap.structureIDTable().get(oldStructureID)))
2692                 break;
2693             if (Options::verboseOSR())
2694                 dataLogF("Clearing LLInt property access.\n");
2695             curInstruction[4].u.structureID = 0;
2696             curInstruction[5].u.operand = 0;
2697             break;
2698         }
2699         case op_put_by_id: {
2700             StructureID oldStructureID = curInstruction[4].u.structureID;
2701             StructureID newStructureID = curInstruction[6].u.structureID;
2702             StructureChain* chain = curInstruction[7].u.structureChain.get();
2703             if ((!oldStructureID || Heap::isMarked(m_vm->heap.structureIDTable().get(oldStructureID))) &&
2704                 (!newStructureID || Heap::isMarked(m_vm->heap.structureIDTable().get(newStructureID))) &&
2705                 (!chain || Heap::isMarked(chain)))
2706                 break;
2707             if (Options::verboseOSR())
2708                 dataLogF("Clearing LLInt put transition.\n");
2709             curInstruction[4].u.structureID = 0;
2710             curInstruction[5].u.operand = 0;
2711             curInstruction[6].u.structureID = 0;
2712             curInstruction[7].u.structureChain.clear();
2713             break;
2714         }
2715         case op_get_array_length:
2716             break;
2717         case op_to_this:
2718             if (!curInstruction[2].u.structure || Heap::isMarked(curInstruction[2].u.structure.get()))
2719                 break;
2720             if (Options::verboseOSR())
2721                 dataLogF("Clearing LLInt to_this with structure %p.\n", curInstruction[2].u.structure.get());
2722             curInstruction[2].u.structure.clear();
2723             curInstruction[3].u.toThisStatus = merge(
2724                 curInstruction[3].u.toThisStatus, ToThisClearedByGC);
2725             break;
2726         case op_create_this: {
2727             auto& cacheWriteBarrier = curInstruction[4].u.jsCell;
2728             if (!cacheWriteBarrier || cacheWriteBarrier.unvalidatedGet() == JSCell::seenMultipleCalleeObjects())
2729                 break;
2730             JSCell* cachedFunction = cacheWriteBarrier.get();
2731             if (Heap::isMarked(cachedFunction))
2732                 break;
2733             if (Options::verboseOSR())
2734                 dataLogF("Clearing LLInt create_this with cached callee %p.\n", cachedFunction);
2735             cacheWriteBarrier.clear();
2736             break;
2737         }
2738         case op_resolve_scope: {
2739             // Right now this isn't strictly necessary. Any symbol tables that this will refer to
2740             // are for outer functions, and we refer to those functions strongly, and they refer
2741             // to the symbol table strongly. But it's nice to be on the safe side.
2742             WriteBarrierBase<SymbolTable>& symbolTable = curInstruction[6].u.symbolTable;
2743             if (!symbolTable || Heap::isMarked(symbolTable.get()))
2744                 break;
2745             if (Options::verboseOSR())
2746                 dataLogF("Clearing dead symbolTable %p.\n", symbolTable.get());
2747             symbolTable.clear();
2748             break;
2749         }
2750         case op_get_from_scope:
2751         case op_put_to_scope: {
2752             GetPutInfo getPutInfo = GetPutInfo(curInstruction[4].u.operand);
2753             if (getPutInfo.resolveType() == GlobalVar || getPutInfo.resolveType() == GlobalVarWithVarInjectionChecks 
2754                 || getPutInfo.resolveType() == LocalClosureVar || getPutInfo.resolveType() == GlobalLexicalVar || getPutInfo.resolveType() == GlobalLexicalVarWithVarInjectionChecks)
2755                 continue;
2756             WriteBarrierBase<Structure>& structure = curInstruction[5].u.structure;
2757             if (!structure || Heap::isMarked(structure.get()))
2758                 break;
2759             if (Options::verboseOSR())
2760                 dataLogF("Clearing scope access with structure %p.\n", structure.get());
2761             structure.clear();
2762             break;
2763         }
2764         default:
2765             OpcodeID opcodeID = interpreter->getOpcodeID(curInstruction[0].u.opcode);
2766             ASSERT_WITH_MESSAGE_UNUSED(opcodeID, false, "Unhandled opcode in CodeBlock::finalizeUnconditionally, %s(%d) at bc %u", opcodeNames[opcodeID], opcodeID, propertyAccessInstructions[i]);
2767         }
2768     }
2769
2770     for (unsigned i = 0; i < m_llintCallLinkInfos.size(); ++i) {
2771         if (m_llintCallLinkInfos[i].isLinked() && !Heap::isMarked(m_llintCallLinkInfos[i].callee.get())) {
2772             if (Options::verboseOSR())
2773                 dataLog("Clearing LLInt call from ", *this, "\n");
2774             m_llintCallLinkInfos[i].unlink();
2775         }
2776         if (!!m_llintCallLinkInfos[i].lastSeenCallee && !Heap::isMarked(m_llintCallLinkInfos[i].lastSeenCallee.get()))
2777             m_llintCallLinkInfos[i].lastSeenCallee.clear();
2778     }
2779 }
2780
2781 void CodeBlock::finalizeBaselineJITInlineCaches()
2782 {
2783 #if ENABLE(JIT)
2784     for (auto iter = callLinkInfosBegin(); !!iter; ++iter)
2785         (*iter)->visitWeak(*vm());
2786
2787     for (Bag<StructureStubInfo>::iterator iter = m_stubInfos.begin(); !!iter; ++iter) {
2788         StructureStubInfo& stubInfo = **iter;
2789         stubInfo.visitWeakReferences(this);
2790     }
2791 #endif
2792 }
2793
2794 void CodeBlock::UnconditionalFinalizer::finalizeUnconditionally()
2795 {
2796     CodeBlock* codeBlock = bitwise_cast<CodeBlock*>(
2797         bitwise_cast<char*>(this) - OBJECT_OFFSETOF(CodeBlock, m_unconditionalFinalizer));
2798
2799 #if ENABLE(DFG_JIT)
2800     if (codeBlock->shouldJettisonDueToWeakReference()) {
2801         codeBlock->jettison(Profiler::JettisonDueToWeakReference);
2802         return;
2803     }
2804 #endif // ENABLE(DFG_JIT)
2805
2806     if (codeBlock->shouldJettisonDueToOldAge()) {
2807         codeBlock->jettison(Profiler::JettisonDueToOldAge);
2808         return;
2809     }
2810
2811     if (JITCode::couldBeInterpreted(codeBlock->jitType()))
2812         codeBlock->finalizeLLIntInlineCaches();
2813
2814 #if ENABLE(JIT)
2815     if (!!codeBlock->jitCode())
2816         codeBlock->finalizeBaselineJITInlineCaches();
2817 #endif
2818 }
2819
2820 void CodeBlock::getStubInfoMap(const ConcurrentJITLocker&, StubInfoMap& result)
2821 {
2822 #if ENABLE(JIT)
2823     toHashMap(m_stubInfos, getStructureStubInfoCodeOrigin, result);
2824 #else
2825     UNUSED_PARAM(result);
2826 #endif
2827 }
2828
2829 void CodeBlock::getStubInfoMap(StubInfoMap& result)
2830 {
2831     ConcurrentJITLocker locker(m_lock);
2832     getStubInfoMap(locker, result);
2833 }
2834
2835 void CodeBlock::getCallLinkInfoMap(const ConcurrentJITLocker&, CallLinkInfoMap& result)
2836 {
2837 #if ENABLE(JIT)
2838     toHashMap(m_callLinkInfos, getCallLinkInfoCodeOrigin, result);
2839 #else
2840     UNUSED_PARAM(result);
2841 #endif
2842 }
2843
2844 void CodeBlock::getCallLinkInfoMap(CallLinkInfoMap& result)
2845 {
2846     ConcurrentJITLocker locker(m_lock);
2847     getCallLinkInfoMap(locker, result);
2848 }
2849
2850 void CodeBlock::getByValInfoMap(const ConcurrentJITLocker&, ByValInfoMap& result)
2851 {
2852 #if ENABLE(JIT)
2853     for (auto* byValInfo : m_byValInfos)
2854         result.add(CodeOrigin(byValInfo->bytecodeIndex), byValInfo);
2855 #else
2856     UNUSED_PARAM(result);
2857 #endif
2858 }
2859
2860 void CodeBlock::getByValInfoMap(ByValInfoMap& result)
2861 {
2862     ConcurrentJITLocker locker(m_lock);
2863     getByValInfoMap(locker, result);
2864 }
2865
2866 #if ENABLE(JIT)
2867 StructureStubInfo* CodeBlock::addStubInfo(AccessType accessType)
2868 {
2869     ConcurrentJITLocker locker(m_lock);
2870     return m_stubInfos.add(accessType);
2871 }
2872
2873 StructureStubInfo* CodeBlock::findStubInfo(CodeOrigin codeOrigin)
2874 {
2875     for (StructureStubInfo* stubInfo : m_stubInfos) {
2876         if (stubInfo->codeOrigin == codeOrigin)
2877             return stubInfo;
2878     }
2879     return nullptr;
2880 }
2881
2882 ByValInfo* CodeBlock::addByValInfo()
2883 {
2884     ConcurrentJITLocker locker(m_lock);
2885     return m_byValInfos.add();
2886 }
2887
2888 CallLinkInfo* CodeBlock::addCallLinkInfo()
2889 {
2890     ConcurrentJITLocker locker(m_lock);
2891     return m_callLinkInfos.add();
2892 }
2893
2894 CallLinkInfo* CodeBlock::getCallLinkInfoForBytecodeIndex(unsigned index)
2895 {
2896     for (auto iter = m_callLinkInfos.begin(); !!iter; ++iter) {
2897         if ((*iter)->codeOrigin() == CodeOrigin(index))
2898             return *iter;
2899     }
2900     return nullptr;
2901 }
2902 #endif
2903
2904 void CodeBlock::visitOSRExitTargets(SlotVisitor& visitor)
2905 {
2906     // We strongly visit OSR exits targets because we don't want to deal with
2907     // the complexity of generating an exit target CodeBlock on demand and
2908     // guaranteeing that it matches the details of the CodeBlock we compiled
2909     // the OSR exit against.
2910
2911     visitor.append(&m_alternative);
2912
2913 #if ENABLE(DFG_JIT)
2914     DFG::CommonData* dfgCommon = m_jitCode->dfgCommon();
2915     if (dfgCommon->inlineCallFrames) {
2916         for (auto* inlineCallFrame : *dfgCommon->inlineCallFrames) {
2917             ASSERT(inlineCallFrame->baselineCodeBlock);
2918             visitor.append(&inlineCallFrame->baselineCodeBlock);
2919         }
2920     }
2921 #endif
2922 }
2923
2924 void CodeBlock::stronglyVisitStrongReferences(SlotVisitor& visitor)
2925 {
2926     visitor.append(&m_globalObject);
2927     visitor.append(&m_ownerExecutable);
2928     visitor.append(&m_unlinkedCode);
2929     if (m_rareData)
2930         m_rareData->m_evalCodeCache.visitAggregate(visitor);
2931     visitor.appendValues(m_constantRegisters.data(), m_constantRegisters.size());
2932     for (size_t i = 0; i < m_functionExprs.size(); ++i)
2933         visitor.append(&m_functionExprs[i]);
2934     for (size_t i = 0; i < m_functionDecls.size(); ++i)
2935         visitor.append(&m_functionDecls[i]);
2936     for (unsigned i = 0; i < m_objectAllocationProfiles.size(); ++i)
2937         m_objectAllocationProfiles[i].visitAggregate(visitor);
2938
2939 #if ENABLE(DFG_JIT)
2940     if (JITCode::isOptimizingJIT(jitType()))
2941         visitOSRExitTargets(visitor);
2942 #endif
2943
2944     updateAllPredictions();
2945 }
2946
2947 void CodeBlock::stronglyVisitWeakReferences(SlotVisitor& visitor)
2948 {
2949     UNUSED_PARAM(visitor);
2950
2951 #if ENABLE(DFG_JIT)
2952     if (!JITCode::isOptimizingJIT(jitType()))
2953         return;
2954     
2955     DFG::CommonData* dfgCommon = m_jitCode->dfgCommon();
2956
2957     for (unsigned i = 0; i < dfgCommon->transitions.size(); ++i) {
2958         if (!!dfgCommon->transitions[i].m_codeOrigin)
2959             visitor.append(&dfgCommon->transitions[i].m_codeOrigin); // Almost certainly not necessary, since the code origin should also be a weak reference. Better to be safe, though.
2960         visitor.append(&dfgCommon->transitions[i].m_from);
2961         visitor.append(&dfgCommon->transitions[i].m_to);
2962     }
2963     
2964     for (unsigned i = 0; i < dfgCommon->weakReferences.size(); ++i)
2965         visitor.append(&dfgCommon->weakReferences[i]);
2966
2967     for (unsigned i = 0; i < dfgCommon->weakStructureReferences.size(); ++i)
2968         visitor.append(&dfgCommon->weakStructureReferences[i]);
2969
2970     dfgCommon->livenessHasBeenProved = true;
2971 #endif    
2972 }
2973
2974 CodeBlock* CodeBlock::baselineAlternative()
2975 {
2976 #if ENABLE(JIT)
2977     CodeBlock* result = this;
2978     while (result->alternative())
2979         result = result->alternative();
2980     RELEASE_ASSERT(result);
2981     RELEASE_ASSERT(JITCode::isBaselineCode(result->jitType()) || result->jitType() == JITCode::None);
2982     return result;
2983 #else
2984     return this;
2985 #endif
2986 }
2987
2988 CodeBlock* CodeBlock::baselineVersion()
2989 {
2990 #if ENABLE(JIT)
2991     if (JITCode::isBaselineCode(jitType()))
2992         return this;
2993     CodeBlock* result = replacement();
2994     if (!result) {
2995         // This can happen if we're creating the original CodeBlock for an executable.
2996         // Assume that we're the baseline CodeBlock.
2997         RELEASE_ASSERT(jitType() == JITCode::None);
2998         return this;
2999     }
3000     result = result->baselineAlternative();
3001     return result;
3002 #else
3003     return this;
3004 #endif
3005 }
3006
3007 #if ENABLE(JIT)
3008 bool CodeBlock::hasOptimizedReplacement(JITCode::JITType typeToReplace)
3009 {
3010     return JITCode::isHigherTier(replacement()->jitType(), typeToReplace);
3011 }
3012
3013 bool CodeBlock::hasOptimizedReplacement()
3014 {
3015     return hasOptimizedReplacement(jitType());
3016 }
3017 #endif
3018
3019 HandlerInfo* CodeBlock::handlerForBytecodeOffset(unsigned bytecodeOffset, RequiredHandler requiredHandler)
3020 {
3021     RELEASE_ASSERT(bytecodeOffset < instructions().size());
3022     return handlerForIndex(bytecodeOffset, requiredHandler);
3023 }
3024
3025 HandlerInfo* CodeBlock::handlerForIndex(unsigned index, RequiredHandler requiredHandler)
3026 {
3027     if (!m_rareData)
3028         return 0;
3029     
3030     Vector<HandlerInfo>& exceptionHandlers = m_rareData->m_exceptionHandlers;
3031     for (size_t i = 0; i < exceptionHandlers.size(); ++i) {
3032         HandlerInfo& handler = exceptionHandlers[i];
3033         if ((requiredHandler == RequiredHandler::CatchHandler) && !handler.isCatchHandler())
3034             continue;
3035
3036         // Handlers are ordered innermost first, so the first handler we encounter
3037         // that contains the source address is the correct handler to use.
3038         // This index used is either the BytecodeOffset or a CallSiteIndex.
3039         if (handler.start <= index && handler.end > index)
3040             return &handler;
3041     }
3042
3043     return 0;
3044 }
3045
3046 CallSiteIndex CodeBlock::newExceptionHandlingCallSiteIndex(CallSiteIndex originalCallSite)
3047 {
3048 #if ENABLE(DFG_JIT)
3049     RELEASE_ASSERT(JITCode::isOptimizingJIT(jitType()));
3050     RELEASE_ASSERT(canGetCodeOrigin(originalCallSite));
3051     ASSERT(!!handlerForIndex(originalCallSite.bits()));
3052     CodeOrigin originalOrigin = codeOrigin(originalCallSite);
3053     return m_jitCode->dfgCommon()->addUniqueCallSiteIndex(originalOrigin);
3054 #else
3055     // We never create new on-the-fly exception handling
3056     // call sites outside the DFG/FTL inline caches.
3057     UNUSED_PARAM(originalCallSite);
3058     RELEASE_ASSERT_NOT_REACHED();
3059     return CallSiteIndex(0u);
3060 #endif
3061 }
3062
3063 void CodeBlock::removeExceptionHandlerForCallSite(CallSiteIndex callSiteIndex)
3064 {
3065     RELEASE_ASSERT(m_rareData);
3066     Vector<HandlerInfo>& exceptionHandlers = m_rareData->m_exceptionHandlers;
3067     unsigned index = callSiteIndex.bits();
3068     for (size_t i = 0; i < exceptionHandlers.size(); ++i) {
3069         HandlerInfo& handler = exceptionHandlers[i];
3070         if (handler.start <= index && handler.end > index) {
3071             exceptionHandlers.remove(i);
3072             return;
3073         }
3074     }
3075
3076     RELEASE_ASSERT_NOT_REACHED();
3077 }
3078
3079 unsigned CodeBlock::lineNumberForBytecodeOffset(unsigned bytecodeOffset)
3080 {
3081     RELEASE_ASSERT(bytecodeOffset < instructions().size());
3082     return ownerScriptExecutable()->firstLine() + m_unlinkedCode->lineNumberForBytecodeOffset(bytecodeOffset);
3083 }
3084
3085 unsigned CodeBlock::columnNumberForBytecodeOffset(unsigned bytecodeOffset)
3086 {
3087     int divot;
3088     int startOffset;
3089     int endOffset;
3090     unsigned line;
3091     unsigned column;
3092     expressionRangeForBytecodeOffset(bytecodeOffset, divot, startOffset, endOffset, line, column);
3093     return column;
3094 }
3095
3096 void CodeBlock::expressionRangeForBytecodeOffset(unsigned bytecodeOffset, int& divot, int& startOffset, int& endOffset, unsigned& line, unsigned& column)
3097 {
3098     m_unlinkedCode->expressionRangeForBytecodeOffset(bytecodeOffset, divot, startOffset, endOffset, line, column);
3099     divot += m_sourceOffset;
3100     column += line ? 1 : firstLineColumnOffset();
3101     line += ownerScriptExecutable()->firstLine();
3102 }
3103
3104 bool CodeBlock::hasOpDebugForLineAndColumn(unsigned line, unsigned column)
3105 {
3106     Interpreter* interpreter = vm()->interpreter;
3107     const Instruction* begin = instructions().begin();
3108     const Instruction* end = instructions().end();
3109     for (const Instruction* it = begin; it != end;) {
3110         OpcodeID opcodeID = interpreter->getOpcodeID(it->u.opcode);
3111         if (opcodeID == op_debug) {
3112             unsigned bytecodeOffset = it - begin;
3113             int unused;
3114             unsigned opDebugLine;
3115             unsigned opDebugColumn;
3116             expressionRangeForBytecodeOffset(bytecodeOffset, unused, unused, unused, opDebugLine, opDebugColumn);
3117             if (line == opDebugLine && (column == Breakpoint::unspecifiedColumn || column == opDebugColumn))
3118                 return true;
3119         }
3120         it += opcodeLengths[opcodeID];
3121     }
3122     return false;
3123 }
3124
3125 void CodeBlock::shrinkToFit(ShrinkMode shrinkMode)
3126 {
3127     m_rareCaseProfiles.shrinkToFit();
3128     m_specialFastCaseProfiles.shrinkToFit();
3129     
3130     if (shrinkMode == EarlyShrink) {
3131         m_constantRegisters.shrinkToFit();
3132         m_constantsSourceCodeRepresentation.shrinkToFit();
3133         
3134         if (m_rareData) {
3135             m_rareData->m_switchJumpTables.shrinkToFit();
3136             m_rareData->m_stringSwitchJumpTables.shrinkToFit();
3137             m_rareData->m_liveCalleeLocalsAtYield.shrinkToFit();
3138         }
3139     } // else don't shrink these, because we would have already pointed pointers into these tables.
3140 }
3141
3142 #if ENABLE(JIT)
3143 void CodeBlock::linkIncomingCall(ExecState* callerFrame, CallLinkInfo* incoming)
3144 {
3145     noticeIncomingCall(callerFrame);
3146     m_incomingCalls.push(incoming);
3147 }
3148
3149 void CodeBlock::linkIncomingPolymorphicCall(ExecState* callerFrame, PolymorphicCallNode* incoming)
3150 {
3151     noticeIncomingCall(callerFrame);
3152     m_incomingPolymorphicCalls.push(incoming);
3153 }
3154 #endif // ENABLE(JIT)
3155
3156 void CodeBlock::unlinkIncomingCalls()
3157 {
3158     while (m_incomingLLIntCalls.begin() != m_incomingLLIntCalls.end())
3159         m_incomingLLIntCalls.begin()->unlink();
3160 #if ENABLE(JIT)
3161     while (m_incomingCalls.begin() != m_incomingCalls.end())
3162         m_incomingCalls.begin()->unlink(*vm());
3163     while (m_incomingPolymorphicCalls.begin() != m_incomingPolymorphicCalls.end())
3164         m_incomingPolymorphicCalls.begin()->unlink(*vm());
3165 #endif // ENABLE(JIT)
3166 }
3167
3168 void CodeBlock::linkIncomingCall(ExecState* callerFrame, LLIntCallLinkInfo* incoming)
3169 {
3170     noticeIncomingCall(callerFrame);
3171     m_incomingLLIntCalls.push(incoming);
3172 }
3173
3174 CodeBlock* CodeBlock::newReplacement()
3175 {
3176     return ownerScriptExecutable()->newReplacementCodeBlockFor(specializationKind());
3177 }
3178
3179 #if ENABLE(JIT)
3180 CodeBlock* CodeBlock::replacement()
3181 {
3182     const ClassInfo* classInfo = this->classInfo();
3183
3184     if (classInfo == FunctionCodeBlock::info())
3185         return jsCast<FunctionExecutable*>(ownerExecutable())->codeBlockFor(m_isConstructor ? CodeForConstruct : CodeForCall);
3186
3187     if (classInfo == EvalCodeBlock::info())
3188         return jsCast<EvalExecutable*>(ownerExecutable())->codeBlock();
3189
3190     if (classInfo == ProgramCodeBlock::info())
3191         return jsCast<ProgramExecutable*>(ownerExecutable())->codeBlock();
3192
3193     if (classInfo == ModuleProgramCodeBlock::info())
3194         return jsCast<ModuleProgramExecutable*>(ownerExecutable())->codeBlock();
3195
3196 #if ENABLE(WEBASSEMBLY)
3197     if (classInfo == WebAssemblyCodeBlock::info())
3198         return nullptr;
3199 #endif
3200
3201     RELEASE_ASSERT_NOT_REACHED();
3202     return nullptr;
3203 }
3204
3205 DFG::CapabilityLevel CodeBlock::computeCapabilityLevel()
3206 {
3207     const ClassInfo* classInfo = this->classInfo();
3208
3209     if (classInfo == FunctionCodeBlock::info()) {
3210         if (m_isConstructor)
3211             return DFG::functionForConstructCapabilityLevel(this);
3212         return DFG::functionForCallCapabilityLevel(this);
3213     }
3214
3215     if (classInfo == EvalCodeBlock::info())
3216         return DFG::evalCapabilityLevel(this);
3217
3218     if (classInfo == ProgramCodeBlock::info())
3219         return DFG::programCapabilityLevel(this);
3220
3221     if (classInfo == ModuleProgramCodeBlock::info())
3222         return DFG::programCapabilityLevel(this);
3223
3224 #if ENABLE(WEBASSEMBLY)
3225     if (classInfo == WebAssemblyCodeBlock::info())
3226         return DFG::CannotCompile;
3227 #endif
3228
3229     RELEASE_ASSERT_NOT_REACHED();
3230     return DFG::CannotCompile;
3231 }
3232
3233 #endif // ENABLE(JIT)
3234
3235 void CodeBlock::jettison(Profiler::JettisonReason reason, ReoptimizationMode mode, const FireDetail* detail)
3236 {
3237 #if !ENABLE(DFG_JIT)
3238     UNUSED_PARAM(mode);
3239     UNUSED_PARAM(detail);
3240 #endif
3241
3242     RELEASE_ASSERT(reason != Profiler::NotJettisoned);
3243     
3244 #if ENABLE(DFG_JIT)
3245     if (DFG::shouldDumpDisassembly()) {
3246         dataLog("Jettisoning ", *this);
3247         if (mode == CountReoptimization)
3248             dataLog(" and counting reoptimization");
3249         dataLog(" due to ", reason);
3250         if (detail)
3251             dataLog(", ", *detail);
3252         dataLog(".\n");
3253     }
3254     
3255     if (reason == Profiler::JettisonDueToWeakReference) {
3256         if (DFG::shouldDumpDisassembly()) {
3257             dataLog(*this, " will be jettisoned because of the following dead references:\n");
3258             DFG::CommonData* dfgCommon = m_jitCode->dfgCommon();
3259             for (unsigned i = 0; i < dfgCommon->transitions.size(); ++i) {
3260                 DFG::WeakReferenceTransition& transition = dfgCommon->transitions[i];
3261                 JSCell* origin = transition.m_codeOrigin.get();
3262                 JSCell* from = transition.m_from.get();
3263                 JSCell* to = transition.m_to.get();
3264                 if ((!origin || Heap::isMarked(origin)) && Heap::isMarked(from))
3265                     continue;
3266                 dataLog("    Transition under ", RawPointer(origin), ", ", RawPointer(from), " -> ", RawPointer(to), ".\n");
3267             }
3268             for (unsigned i = 0; i < dfgCommon->weakReferences.size(); ++i) {
3269                 JSCell* weak = dfgCommon->weakReferences[i].get();
3270                 if (Heap::isMarked(weak))
3271                     continue;
3272                 dataLog("    Weak reference ", RawPointer(weak), ".\n");
3273             }
3274         }
3275     }
3276 #endif // ENABLE(DFG_JIT)
3277
3278     DeferGCForAWhile deferGC(*m_heap);
3279     
3280     // We want to accomplish two things here:
3281     // 1) Make sure that if this CodeBlock is on the stack right now, then if we return to it
3282     //    we should OSR exit at the top of the next bytecode instruction after the return.
3283     // 2) Make sure that if we call the owner executable, then we shouldn't call this CodeBlock.
3284
3285 #if ENABLE(DFG_JIT)
3286     if (reason != Profiler::JettisonDueToOldAge) {
3287         if (Profiler::Compilation* compilation = jitCode()->dfgCommon()->compilation.get())
3288             compilation->setJettisonReason(reason, detail);
3289         
3290         // This accomplishes (1), and does its own book-keeping about whether it has already happened.
3291         if (!jitCode()->dfgCommon()->invalidate()) {
3292             // We've already been invalidated.
3293             RELEASE_ASSERT(this != replacement());
3294             return;
3295         }
3296     }
3297     
3298     if (DFG::shouldDumpDisassembly())
3299         dataLog("    Did invalidate ", *this, "\n");
3300     
3301     // Count the reoptimization if that's what the user wanted.
3302     if (mode == CountReoptimization) {
3303         // FIXME: Maybe this should call alternative().
3304         // https://bugs.webkit.org/show_bug.cgi?id=123677
3305         baselineAlternative()->countReoptimization();
3306         if (DFG::shouldDumpDisassembly())
3307             dataLog("    Did count reoptimization for ", *this, "\n");
3308     }
3309     
3310     if (this != replacement()) {
3311         // This means that we were never the entrypoint. This can happen for OSR entry code
3312         // blocks.
3313         return;
3314     }
3315
3316     if (alternative())
3317         alternative()->optimizeAfterWarmUp();
3318
3319     if (reason != Profiler::JettisonDueToOldAge)
3320         tallyFrequentExitSites();
3321 #endif // ENABLE(DFG_JIT)
3322
3323     // This accomplishes (2).
3324     ownerScriptExecutable()->installCode(
3325         m_globalObject->vm(), alternative(), codeType(), specializationKind());
3326
3327 #if ENABLE(DFG_JIT)
3328     if (DFG::shouldDumpDisassembly())
3329         dataLog("    Did install baseline version of ", *this, "\n");
3330 #endif // ENABLE(DFG_JIT)
3331 }
3332
3333 JSGlobalObject* CodeBlock::globalObjectFor(CodeOrigin codeOrigin)
3334 {
3335     if (!codeOrigin.inlineCallFrame)
3336         return globalObject();
3337     return codeOrigin.inlineCallFrame->baselineCodeBlock->globalObject();
3338 }
3339
3340 class RecursionCheckFunctor {
3341 public:
3342     RecursionCheckFunctor(CallFrame* startCallFrame, CodeBlock* codeBlock, unsigned depthToCheck)
3343         : m_startCallFrame(startCallFrame)
3344         , m_codeBlock(codeBlock)
3345         , m_depthToCheck(depthToCheck)
3346         , m_foundStartCallFrame(false)
3347         , m_didRecurse(false)
3348     { }
3349
3350     StackVisitor::Status operator()(StackVisitor& visitor)
3351     {
3352         CallFrame* currentCallFrame = visitor->callFrame();
3353
3354         if (currentCallFrame == m_startCallFrame)
3355             m_foundStartCallFrame = true;
3356
3357         if (m_foundStartCallFrame) {
3358             if (visitor->callFrame()->codeBlock() == m_codeBlock) {
3359                 m_didRecurse = true;
3360                 return StackVisitor::Done;
3361             }
3362
3363             if (!m_depthToCheck--)
3364                 return StackVisitor::Done;
3365         }
3366
3367         return StackVisitor::Continue;
3368     }
3369
3370     bool didRecurse() const { return m_didRecurse; }
3371
3372 private:
3373     CallFrame* m_startCallFrame;
3374     CodeBlock* m_codeBlock;
3375     unsigned m_depthToCheck;
3376     bool m_foundStartCallFrame;
3377     bool m_didRecurse;
3378 };
3379
3380 void CodeBlock::noticeIncomingCall(ExecState* callerFrame)
3381 {
3382     CodeBlock* callerCodeBlock = callerFrame->codeBlock();
3383     
3384     if (Options::verboseCallLink())
3385         dataLog("Noticing call link from ", pointerDump(callerCodeBlock), " to ", *this, "\n");
3386     
3387 #if ENABLE(DFG_JIT)
3388     if (!m_shouldAlwaysBeInlined)
3389         return;
3390     
3391     if (!callerCodeBlock) {
3392         m_shouldAlwaysBeInlined = false;
3393         if (Options::verboseCallLink())
3394             dataLog("    Clearing SABI because caller is native.\n");
3395         return;
3396     }
3397
3398     if (!hasBaselineJITProfiling())
3399         return;
3400
3401     if (!DFG::mightInlineFunction(this))
3402         return;
3403
3404     if (!canInline(m_capabilityLevelState))
3405         return;
3406     
3407     if (!DFG::isSmallEnoughToInlineCodeInto(callerCodeBlock)) {
3408         m_shouldAlwaysBeInlined = false;
3409         if (Options::verboseCallLink())
3410             dataLog("    Clearing SABI because caller is too large.\n");
3411         return;
3412     }
3413
3414     if (callerCodeBlock->jitType() == JITCode::InterpreterThunk) {
3415         // If the caller is still in the interpreter, then we can't expect inlining to
3416         // happen anytime soon. Assume it's profitable to optimize it separately. This
3417         // ensures that a function is SABI only if it is called no more frequently than
3418         // any of its callers.
3419         m_shouldAlwaysBeInlined = false;
3420         if (Options::verboseCallLink())
3421             dataLog("    Clearing SABI because caller is in LLInt.\n");
3422         return;
3423     }
3424     
3425     if (JITCode::isOptimizingJIT(callerCodeBlock->jitType())) {
3426         m_shouldAlwaysBeInlined = false;
3427         if (Options::verboseCallLink())
3428             dataLog("    Clearing SABI bcause caller was already optimized.\n");
3429         return;
3430     }
3431     
3432     if (callerCodeBlock->codeType() != FunctionCode) {
3433         // If the caller is either eval or global code, assume that that won't be
3434         // optimized anytime soon. For eval code this is particularly true since we
3435         // delay eval optimization by a *lot*.
3436         m_shouldAlwaysBeInlined = false;
3437         if (Options::verboseCallLink())
3438             dataLog("    Clearing SABI because caller is not a function.\n");
3439         return;
3440     }
3441
3442     // Recursive calls won't be inlined.
3443     RecursionCheckFunctor functor(callerFrame, this, Options::maximumInliningDepth());
3444     vm()->topCallFrame->iterate(functor);
3445
3446     if (functor.didRecurse()) {
3447         if (Options::verboseCallLink())
3448             dataLog("    Clearing SABI because recursion was detected.\n");
3449         m_shouldAlwaysBeInlined = false;
3450         return;
3451     }
3452     
3453     if (callerCodeBlock->m_capabilityLevelState == DFG::CapabilityLevelNotSet) {
3454         dataLog("In call from ", *callerCodeBlock, " ", callerFrame->codeOrigin(), " to ", *this, ": caller's DFG capability level is not set.\n");
3455         CRASH();
3456     }
3457     
3458     if (canCompile(callerCodeBlock->m_capabilityLevelState))
3459         return;
3460     
3461     if (Options::verboseCallLink())
3462         dataLog("    Clearing SABI because the caller is not a DFG candidate.\n");
3463     
3464     m_shouldAlwaysBeInlined = false;
3465 #endif
3466 }
3467
3468 unsigned CodeBlock::reoptimizationRetryCounter() const
3469 {
3470 #if ENABLE(JIT)
3471     ASSERT(m_reoptimizationRetryCounter <= Options::reoptimizationRetryCounterMax());
3472     return m_reoptimizationRetryCounter;
3473 #else
3474     return 0;
3475 #endif // ENABLE(JIT)
3476 }
3477
3478 #if ENABLE(JIT)
3479 void CodeBlock::setCalleeSaveRegisters(RegisterSet calleeSaveRegisters)
3480 {
3481     m_calleeSaveRegisters = std::make_unique<RegisterAtOffsetList>(calleeSaveRegisters);
3482 }
3483
3484 void CodeBlock::setCalleeSaveRegisters(std::unique_ptr<RegisterAtOffsetList> registerAtOffsetList)
3485 {
3486     m_calleeSaveRegisters = WTF::move(registerAtOffsetList);
3487 }
3488     
3489 static size_t roundCalleeSaveSpaceAsVirtualRegisters(size_t calleeSaveRegisters)
3490 {
3491     static const unsigned cpuRegisterSize = sizeof(void*);
3492     return (WTF::roundUpToMultipleOf(sizeof(Register), calleeSaveRegisters * cpuRegisterSize) / sizeof(Register));
3493
3494 }
3495
3496 size_t CodeBlock::llintBaselineCalleeSaveSpaceAsVirtualRegisters()
3497 {
3498     return roundCalleeSaveSpaceAsVirtualRegisters(numberOfLLIntBaselineCalleeSaveRegisters());
3499 }
3500
3501 size_t CodeBlock::calleeSaveSpaceAsVirtualRegisters()
3502 {
3503     return roundCalleeSaveSpaceAsVirtualRegisters(m_calleeSaveRegisters->size());
3504 }
3505
3506 void CodeBlock::countReoptimization()
3507 {
3508     m_reoptimizationRetryCounter++;
3509     if (m_reoptimizationRetryCounter > Options::reoptimizationRetryCounterMax())
3510         m_reoptimizationRetryCounter = Options::reoptimizationRetryCounterMax();
3511 }
3512
3513 unsigned CodeBlock::numberOfDFGCompiles()
3514 {
3515     ASSERT(JITCode::isBaselineCode(jitType()));
3516     if (Options::testTheFTL()) {
3517         if (m_didFailFTLCompilation)
3518             return 1000000;
3519         return (m_hasBeenCompiledWithFTL ? 1 : 0) + m_reoptimizationRetryCounter;
3520     }
3521     return (JITCode::isOptimizingJIT(replacement()->jitType()) ? 1 : 0) + m_reoptimizationRetryCounter;
3522 }
3523
3524 int32_t CodeBlock::codeTypeThresholdMultiplier() const
3525 {
3526     if (codeType() == EvalCode)
3527         return Options::evalThresholdMultiplier();
3528     
3529     return 1;
3530 }
3531
3532 double CodeBlock::optimizationThresholdScalingFactor()
3533 {
3534     // This expression arises from doing a least-squares fit of
3535     //
3536     // F[x_] =: a * Sqrt[x + b] + Abs[c * x] + d
3537     //
3538     // against the data points:
3539     //
3540     //    x       F[x_]
3541     //    10       0.9          (smallest reasonable code block)
3542     //   200       1.0          (typical small-ish code block)
3543     //   320       1.2          (something I saw in 3d-cube that I wanted to optimize)
3544     //  1268       5.0          (something I saw in 3d-cube that I didn't want to optimize)
3545     //  4000       5.5          (random large size, used to cause the function to converge to a shallow curve of some sort)
3546     // 10000       6.0          (similar to above)
3547     //
3548     // I achieve the minimization using the following Mathematica code:
3549     //
3550     // MyFunctionTemplate[x_, a_, b_, c_, d_] := a*Sqrt[x + b] + Abs[c*x] + d
3551     //
3552     // samples = {{10, 0.9}, {200, 1}, {320, 1.2}, {1268, 5}, {4000, 5.5}, {10000, 6}}
3553     //
3554     // solution = 
3555     //     Minimize[Plus @@ ((MyFunctionTemplate[#[[1]], a, b, c, d] - #[[2]])^2 & /@ samples),
3556     //         {a, b, c, d}][[2]]
3557     //
3558     // And the code below (to initialize a, b, c, d) is generated by:
3559     //
3560     // Print["const double " <> ToString[#[[1]]] <> " = " <>
3561     //     If[#[[2]] < 0.00001, "0.0", ToString[#[[2]]]] <> ";"] & /@ solution
3562     //
3563     // We've long known the following to be true:
3564     // - Small code blocks are cheap to optimize and so we should do it sooner rather
3565     //   than later.
3566     // - Large code blocks are expensive to optimize and so we should postpone doing so,
3567     //   and sometimes have a large enough threshold that we never optimize them.
3568     // - The difference in cost is not totally linear because (a) just invoking the
3569     //   DFG incurs some base cost and (b) for large code blocks there is enough slop
3570     //   in the correlation between instruction count and the actual compilation cost
3571     //   that for those large blocks, the instruction count should not have a strong
3572     //   influence on our threshold.
3573     //
3574     // I knew the goals but I didn't know how to achieve them; so I picked an interesting
3575     // example where the heuristics were right (code block in 3d-cube with instruction
3576     // count 320, which got compiled early as it should have been) and one where they were
3577     // totally wrong (code block in 3d-cube with instruction count 1268, which was expensive
3578     // to compile and didn't run often enough to warrant compilation in my opinion), and
3579     // then threw in additional data points that represented my own guess of what our
3580     // heuristics should do for some round-numbered examples.
3581     //
3582     // The expression to which I decided to fit the data arose because I started with an
3583     // affine function, and then did two things: put the linear part in an Abs to ensure
3584     // that the fit didn't end up choosing a negative value of c (which would result in
3585     // the function turning over and going negative for large x) and I threw in a Sqrt
3586     // term because Sqrt represents my intution that the function should be more sensitive
3587     // to small changes in small values of x, but less sensitive when x gets large.
3588     
3589     // Note that the current fit essentially eliminates the linear portion of the
3590     // expression (c == 0.0).
3591     const double a = 0.061504;
3592     const double b = 1.02406;
3593     const double c = 0.0;
3594     const double d = 0.825914;
3595     
3596     double instructionCount = this->instructionCount();
3597     
3598     ASSERT(instructionCount); // Make sure this is called only after we have an instruction stream; otherwise it'll just return the value of d, which makes no sense.
3599     
3600     double result = d + a * sqrt(instructionCount + b) + c * instructionCount;
3601     
3602     result *= codeTypeThresholdMultiplier();
3603     
3604     if (Options::verboseOSR()) {
3605         dataLog(
3606             *this, ": instruction count is ", instructionCount,
3607             ", scaling execution counter by ", result, " * ", codeTypeThresholdMultiplier(),
3608             "\n");
3609     }
3610     return result;
3611 }
3612
3613 static int32_t clipThreshold(double threshold)
3614 {
3615     if (threshold < 1.0)
3616         return 1;
3617     
3618     if (threshold > static_cast<double>(std::numeric_limits<int32_t>::max()))
3619         return std::numeric_limits<int32_t>::max();
3620     
3621     return static_cast<int32_t>(threshold);
3622 }
3623
3624 int32_t CodeBlock::adjustedCounterValue(int32_t desiredThreshold)
3625 {
3626     return clipThreshold(
3627         static_cast<double>(desiredThreshold) *
3628         optimizationThresholdScalingFactor() *
3629         (1 << reoptimizationRetryCounter()));
3630 }
3631
3632 bool CodeBlock::checkIfOptimizationThresholdReached()
3633 {
3634 #if ENABLE(DFG_JIT)
3635     if (DFG::Worklist* worklist = DFG::existingGlobalDFGWorklistOrNull()) {
3636         if (worklist->compilationState(DFG::CompilationKey(this, DFG::DFGMode))
3637             == DFG::Worklist::Compiled) {
3638             optimizeNextInvocation();
3639             return true;
3640         }
3641     }
3642 #endif
3643     
3644     return m_jitExecuteCounter.checkIfThresholdCrossedAndSet(this);
3645 }
3646
3647 void CodeBlock::optimizeNextInvocation()
3648 {
3649     if (Options::verboseOSR())
3650         dataLog(*this, ": Optimizing next invocation.\n");
3651     m_jitExecuteCounter.setNewThreshold(0, this);
3652 }
3653
3654 void CodeBlock::dontOptimizeAnytimeSoon()
3655 {
3656     if (Options::verboseOSR())
3657         dataLog(*this, ": Not optimizing anytime soon.\n");
3658     m_jitExecuteCounter.deferIndefinitely();
3659 }
3660
3661 void CodeBlock::optimizeAfterWarmUp()
3662 {
3663     if (Options::verboseOSR())
3664         dataLog(*this, ": Optimizing after warm-up.\n");
3665 #if ENABLE(DFG_JIT)
3666     m_jitExecuteCounter.setNewThreshold(
3667         adjustedCounterValue(Options::thresholdForOptimizeAfterWarmUp()), this);
3668 #endif
3669 }
3670
3671 void CodeBlock::optimizeAfterLongWarmUp()
3672 {
3673     if (Options::verboseOSR())
3674         dataLog(*this, ": Optimizing after long warm-up.\n");
3675 #if ENABLE(DFG_JIT)
3676     m_jitExecuteCounter.setNewThreshold(
3677         adjustedCounterValue(Options::thresholdForOptimizeAfterLongWarmUp()), this);
3678 #endif
3679 }
3680
3681 void CodeBlock::optimizeSoon()
3682 {
3683     if (Options::verboseOSR())
3684         dataLog(*this, ": Optimizing soon.\n");
3685 #if ENABLE(DFG_JIT)
3686     m_jitExecuteCounter.setNewThreshold(
3687         adjustedCounterValue(Options::thresholdForOptimizeSoon()), this);
3688 #endif
3689 }
3690
3691 void CodeBlock::forceOptimizationSlowPathConcurrently()
3692 {
3693     if (Options::verboseOSR())
3694         dataLog(*this, ": Forcing slow path concurrently.\n");
3695     m_jitExecuteCounter.forceSlowPathConcurrently();
3696 }
3697
3698 #if ENABLE(DFG_JIT)
3699 void CodeBlock::setOptimizationThresholdBasedOnCompilationResult(CompilationResult result)
3700 {
3701     JITCode::JITType type = jitType();
3702     if (type != JITCode::BaselineJIT) {
3703         dataLog(*this, ": expected to have baseline code but have ", type, "\n");
3704         RELEASE_ASSERT_NOT_REACHED();
3705     }
3706     
3707     CodeBlock* theReplacement = replacement();
3708     if ((result == CompilationSuccessful) != (theReplacement != this)) {
3709         dataLog(*this, ": we have result = ", result, " but ");
3710         if (theReplacement == this)
3711             dataLog("we are our own replacement.\n");
3712         else
3713             dataLog("our replacement is ", pointerDump(theReplacement), "\n");
3714         RELEASE_ASSERT_NOT_REACHED();
3715     }
3716     
3717     switch (result) {
3718     case CompilationSuccessful:
3719         RELEASE_ASSERT(JITCode::isOptimizingJIT(replacement()->jitType()));
3720         optimizeNextInvocation();
3721         return;
3722     case CompilationFailed:
3723         dontOptimizeAnytimeSoon();
3724         return;
3725     case CompilationDeferred:
3726         // We'd like to do dontOptimizeAnytimeSoon() but we cannot because
3727         // forceOptimizationSlowPathConcurrently() is inherently racy. It won't
3728         // necessarily guarantee anything. So, we make sure that even if that
3729         // function ends up being a no-op, we still eventually retry and realize
3730         // that we have optimized code ready.
3731         optimizeAfterWarmUp();
3732         return;
3733     case CompilationInvalidated:
3734         // Retry with exponential backoff.
3735         countReoptimization();
3736         optimizeAfterWarmUp();
3737         return;
3738     }
3739     
3740     dataLog("Unrecognized result: ", static_cast<int>(result), "\n");
3741     RELEASE_ASSERT_NOT_REACHED();
3742 }
3743
3744 #endif
3745     
3746 uint32_t CodeBlock::adjustedExitCountThreshold(uint32_t desiredThreshold)
3747 {
3748     ASSERT(JITCode::isOptimizingJIT(jitType()));
3749     // Compute this the lame way so we don't saturate. This is called infrequently
3750     // enough that this loop won't hurt us.
3751     unsigned result = desiredThreshold;
3752     for (unsigned n = baselineVersion()->reoptimizationRetryCounter(); n--;) {
3753         unsigned newResult = result << 1;