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