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