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