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