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