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