get_by_id should support caching unset properties in the LLInt
[WebKit.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_arrow_func_exp: {
1427             int r0 = (++it)->u.operand;
1428             int r1 = (++it)->u.operand;
1429             int f0 = (++it)->u.operand;
1430             printLocationAndOp(out, exec, location, it, "op_new_arrow_func_exp");
1431             out.printf("%s, %s, f%d", registerName(r0).data(), registerName(r1).data(), f0);
1432             break;
1433         }
1434         case op_new_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_func_exp");
1439             out.printf("%s, %s, f%d", registerName(r0).data(), registerName(r1).data(), f0);
1440             break;
1441         }
1442         case op_new_generator_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_generator_func_exp");
1447             out.printf("%s, %s, f%d", registerName(r0).data(), registerName(r1).data(), f0);
1448             break;
1449         }
1450         case op_set_function_name: {
1451             int funcReg = (++it)->u.operand;
1452             int nameReg = (++it)->u.operand;
1453             printLocationAndOp(out, exec, location, it, "set_function_name");
1454             out.printf("%s, %s", registerName(funcReg).data(), registerName(nameReg).data());
1455             break;
1456         }
1457         case op_call: {
1458             printCallOp(out, exec, location, it, "call", DumpCaches, hasPrintedProfiling, callLinkInfos);
1459             break;
1460         }
1461         case op_tail_call: {
1462             printCallOp(out, exec, location, it, "tail_call", DumpCaches, hasPrintedProfiling, callLinkInfos);
1463             break;
1464         }
1465         case op_call_eval: {
1466             printCallOp(out, exec, location, it, "call_eval", DontDumpCaches, hasPrintedProfiling, callLinkInfos);
1467             break;
1468         }
1469             
1470         case op_construct_varargs:
1471         case op_call_varargs:
1472         case op_tail_call_varargs: {
1473             int result = (++it)->u.operand;
1474             int callee = (++it)->u.operand;
1475             int thisValue = (++it)->u.operand;
1476             int arguments = (++it)->u.operand;
1477             int firstFreeRegister = (++it)->u.operand;
1478             int varArgOffset = (++it)->u.operand;
1479             ++it;
1480             printLocationAndOp(out, exec, location, it, opcode == op_call_varargs ? "call_varargs" : opcode == op_construct_varargs ? "construct_varargs" : "tail_call_varargs");
1481             out.printf("%s, %s, %s, %s, %d, %d", registerName(result).data(), registerName(callee).data(), registerName(thisValue).data(), registerName(arguments).data(), firstFreeRegister, varArgOffset);
1482             dumpValueProfiling(out, it, hasPrintedProfiling);
1483             break;
1484         }
1485
1486         case op_ret: {
1487             int r0 = (++it)->u.operand;
1488             printLocationOpAndRegisterOperand(out, exec, location, it, "ret", r0);
1489             break;
1490         }
1491         case op_construct: {
1492             printCallOp(out, exec, location, it, "construct", DumpCaches, hasPrintedProfiling, callLinkInfos);
1493             break;
1494         }
1495         case op_strcat: {
1496             int r0 = (++it)->u.operand;
1497             int r1 = (++it)->u.operand;
1498             int count = (++it)->u.operand;
1499             printLocationAndOp(out, exec, location, it, "strcat");
1500             out.printf("%s, %s, %d", registerName(r0).data(), registerName(r1).data(), count);
1501             break;
1502         }
1503         case op_to_primitive: {
1504             int r0 = (++it)->u.operand;
1505             int r1 = (++it)->u.operand;
1506             printLocationAndOp(out, exec, location, it, "to_primitive");
1507             out.printf("%s, %s", registerName(r0).data(), registerName(r1).data());
1508             break;
1509         }
1510         case op_get_enumerable_length: {
1511             int dst = it[1].u.operand;
1512             int base = it[2].u.operand;
1513             printLocationAndOp(out, exec, location, it, "op_get_enumerable_length");
1514             out.printf("%s, %s", registerName(dst).data(), registerName(base).data());
1515             it += OPCODE_LENGTH(op_get_enumerable_length) - 1;
1516             break;
1517         }
1518         case op_has_indexed_property: {
1519             int dst = it[1].u.operand;
1520             int base = it[2].u.operand;
1521             int propertyName = it[3].u.operand;
1522             ArrayProfile* arrayProfile = it[4].u.arrayProfile;
1523             printLocationAndOp(out, exec, location, it, "op_has_indexed_property");
1524             out.printf("%s, %s, %s, %p", registerName(dst).data(), registerName(base).data(), registerName(propertyName).data(), arrayProfile);
1525             it += OPCODE_LENGTH(op_has_indexed_property) - 1;
1526             break;
1527         }
1528         case op_has_structure_property: {
1529             int dst = it[1].u.operand;
1530             int base = it[2].u.operand;
1531             int propertyName = it[3].u.operand;
1532             int enumerator = it[4].u.operand;
1533             printLocationAndOp(out, exec, location, it, "op_has_structure_property");
1534             out.printf("%s, %s, %s, %s", registerName(dst).data(), registerName(base).data(), registerName(propertyName).data(), registerName(enumerator).data());
1535             it += OPCODE_LENGTH(op_has_structure_property) - 1;
1536             break;
1537         }
1538         case op_has_generic_property: {
1539             int dst = it[1].u.operand;
1540             int base = it[2].u.operand;
1541             int propertyName = it[3].u.operand;
1542             printLocationAndOp(out, exec, location, it, "op_has_generic_property");
1543             out.printf("%s, %s, %s", registerName(dst).data(), registerName(base).data(), registerName(propertyName).data());
1544             it += OPCODE_LENGTH(op_has_generic_property) - 1;
1545             break;
1546         }
1547         case op_get_direct_pname: {
1548             int dst = it[1].u.operand;
1549             int base = it[2].u.operand;
1550             int propertyName = it[3].u.operand;
1551             int index = it[4].u.operand;
1552             int enumerator = it[5].u.operand;
1553             ValueProfile* profile = it[6].u.profile;
1554             printLocationAndOp(out, exec, location, it, "op_get_direct_pname");
1555             out.printf("%s, %s, %s, %s, %s, %p", registerName(dst).data(), registerName(base).data(), registerName(propertyName).data(), registerName(index).data(), registerName(enumerator).data(), profile);
1556             it += OPCODE_LENGTH(op_get_direct_pname) - 1;
1557             break;
1558
1559         }
1560         case op_get_property_enumerator: {
1561             int dst = it[1].u.operand;
1562             int base = it[2].u.operand;
1563             printLocationAndOp(out, exec, location, it, "op_get_property_enumerator");
1564             out.printf("%s, %s", registerName(dst).data(), registerName(base).data());
1565             it += OPCODE_LENGTH(op_get_property_enumerator) - 1;
1566             break;
1567         }
1568         case op_enumerator_structure_pname: {
1569             int dst = it[1].u.operand;
1570             int enumerator = it[2].u.operand;
1571             int index = it[3].u.operand;
1572             printLocationAndOp(out, exec, location, it, "op_enumerator_structure_pname");
1573             out.printf("%s, %s, %s", registerName(dst).data(), registerName(enumerator).data(), registerName(index).data());
1574             it += OPCODE_LENGTH(op_enumerator_structure_pname) - 1;
1575             break;
1576         }
1577         case op_enumerator_generic_pname: {
1578             int dst = it[1].u.operand;
1579             int enumerator = it[2].u.operand;
1580             int index = it[3].u.operand;
1581             printLocationAndOp(out, exec, location, it, "op_enumerator_generic_pname");
1582             out.printf("%s, %s, %s", registerName(dst).data(), registerName(enumerator).data(), registerName(index).data());
1583             it += OPCODE_LENGTH(op_enumerator_generic_pname) - 1;
1584             break;
1585         }
1586         case op_to_index_string: {
1587             int dst = it[1].u.operand;
1588             int index = it[2].u.operand;
1589             printLocationAndOp(out, exec, location, it, "op_to_index_string");
1590             out.printf("%s, %s", registerName(dst).data(), registerName(index).data());
1591             it += OPCODE_LENGTH(op_to_index_string) - 1;
1592             break;
1593         }
1594         case op_push_with_scope: {
1595             int dst = (++it)->u.operand;
1596             int newScope = (++it)->u.operand;
1597             int currentScope = (++it)->u.operand;
1598             printLocationAndOp(out, exec, location, it, "push_with_scope");
1599             out.printf("%s, %s, %s", registerName(dst).data(), registerName(newScope).data(), registerName(currentScope).data());
1600             break;
1601         }
1602         case op_get_parent_scope: {
1603             int dst = (++it)->u.operand;
1604             int parentScope = (++it)->u.operand;
1605             printLocationAndOp(out, exec, location, it, "get_parent_scope");
1606             out.printf("%s, %s", registerName(dst).data(), registerName(parentScope).data());
1607             break;
1608         }
1609         case op_create_lexical_environment: {
1610             int dst = (++it)->u.operand;
1611             int scope = (++it)->u.operand;
1612             int symbolTable = (++it)->u.operand;
1613             int initialValue = (++it)->u.operand;
1614             printLocationAndOp(out, exec, location, it, "create_lexical_environment");
1615             out.printf("%s, %s, %s, %s", 
1616                 registerName(dst).data(), registerName(scope).data(), registerName(symbolTable).data(), registerName(initialValue).data());
1617             break;
1618         }
1619         case op_catch: {
1620             int r0 = (++it)->u.operand;
1621             int r1 = (++it)->u.operand;
1622             printLocationAndOp(out, exec, location, it, "catch");
1623             out.printf("%s, %s", registerName(r0).data(), registerName(r1).data());
1624             break;
1625         }
1626         case op_throw: {
1627             int r0 = (++it)->u.operand;
1628             printLocationOpAndRegisterOperand(out, exec, location, it, "throw", r0);
1629             break;
1630         }
1631         case op_throw_static_error: {
1632             int k0 = (++it)->u.operand;
1633             int k1 = (++it)->u.operand;
1634             printLocationAndOp(out, exec, location, it, "throw_static_error");
1635             out.printf("%s, %s", constantName(k0).data(), k1 ? "true" : "false");
1636             break;
1637         }
1638         case op_debug: {
1639             int debugHookID = (++it)->u.operand;
1640             int hasBreakpointFlag = (++it)->u.operand;
1641             printLocationAndOp(out, exec, location, it, "debug");
1642             out.printf("%s, %d", debugHookName(debugHookID), hasBreakpointFlag);
1643             break;
1644         }
1645         case op_save: {
1646             int generator = (++it)->u.operand;
1647             unsigned liveCalleeLocalsIndex = (++it)->u.unsignedValue;
1648             int offset = (++it)->u.operand;
1649             const FastBitVector& liveness = m_rareData->m_liveCalleeLocalsAtYield[liveCalleeLocalsIndex];
1650             printLocationAndOp(out, exec, location, it, "save");
1651             out.printf("%s, ", registerName(generator).data());
1652             liveness.dump(out);
1653             out.printf("(@live%1u), %d(->%d)", liveCalleeLocalsIndex, offset, location + offset);
1654             break;
1655         }
1656         case op_resume: {
1657             int generator = (++it)->u.operand;
1658             unsigned liveCalleeLocalsIndex = (++it)->u.unsignedValue;
1659             const FastBitVector& liveness = m_rareData->m_liveCalleeLocalsAtYield[liveCalleeLocalsIndex];
1660             printLocationAndOp(out, exec, location, it, "resume");
1661             out.printf("%s, ", registerName(generator).data());
1662             liveness.dump(out);
1663             out.printf("(@live%1u)", liveCalleeLocalsIndex);
1664             break;
1665         }
1666         case op_assert: {
1667             int condition = (++it)->u.operand;
1668             int line = (++it)->u.operand;
1669             printLocationAndOp(out, exec, location, it, "assert");
1670             out.printf("%s, %d", registerName(condition).data(), line);
1671             break;
1672         }
1673         case op_end: {
1674             int r0 = (++it)->u.operand;
1675             printLocationOpAndRegisterOperand(out, exec, location, it, "end", r0);
1676             break;
1677         }
1678         case op_resolve_scope: {
1679             int r0 = (++it)->u.operand;
1680             int scope = (++it)->u.operand;
1681             int id0 = (++it)->u.operand;
1682             ResolveType resolveType = static_cast<ResolveType>((++it)->u.operand);
1683             int depth = (++it)->u.operand;
1684             void* pointer = (++it)->u.pointer;
1685             printLocationAndOp(out, exec, location, it, "resolve_scope");
1686             out.printf("%s, %s, %s, <%s>, %d, %p", registerName(r0).data(), registerName(scope).data(), idName(id0, identifier(id0)).data(), resolveTypeName(resolveType), depth, pointer);
1687             break;
1688         }
1689         case op_get_from_scope: {
1690             int r0 = (++it)->u.operand;
1691             int r1 = (++it)->u.operand;
1692             int id0 = (++it)->u.operand;
1693             GetPutInfo getPutInfo = GetPutInfo((++it)->u.operand);
1694             ++it; // Structure
1695             int operand = (++it)->u.operand; // Operand
1696             printLocationAndOp(out, exec, location, it, "get_from_scope");
1697             out.print(registerName(r0), ", ", registerName(r1));
1698             if (static_cast<unsigned>(id0) == UINT_MAX)
1699                 out.print(", anonymous");
1700             else
1701                 out.print(", ", idName(id0, identifier(id0)));
1702             out.print(", ", getPutInfo.operand(), "<", resolveModeName(getPutInfo.resolveMode()), "|", resolveTypeName(getPutInfo.resolveType()), "|", initializationModeName(getPutInfo.initializationMode()), ">, ", operand);
1703             dumpValueProfiling(out, it, hasPrintedProfiling);
1704             break;
1705         }
1706         case op_put_to_scope: {
1707             int r0 = (++it)->u.operand;
1708             int id0 = (++it)->u.operand;
1709             int r1 = (++it)->u.operand;
1710             GetPutInfo getPutInfo = GetPutInfo((++it)->u.operand);
1711             ++it; // Structure
1712             int operand = (++it)->u.operand; // Operand
1713             printLocationAndOp(out, exec, location, it, "put_to_scope");
1714             out.print(registerName(r0));
1715             if (static_cast<unsigned>(id0) == UINT_MAX)
1716                 out.print(", anonymous");
1717             else
1718                 out.print(", ", idName(id0, identifier(id0)));
1719             out.print(", ", registerName(r1), ", ", getPutInfo.operand(), "<", resolveModeName(getPutInfo.resolveMode()), "|", resolveTypeName(getPutInfo.resolveType()), "|", initializationModeName(getPutInfo.initializationMode()), ">, <structure>, ", operand);
1720             break;
1721         }
1722         case op_get_from_arguments: {
1723             int r0 = (++it)->u.operand;
1724             int r1 = (++it)->u.operand;
1725             int offset = (++it)->u.operand;
1726             printLocationAndOp(out, exec, location, it, "get_from_arguments");
1727             out.printf("%s, %s, %d", registerName(r0).data(), registerName(r1).data(), offset);
1728             dumpValueProfiling(out, it, hasPrintedProfiling);
1729             break;
1730         }
1731         case op_put_to_arguments: {
1732             int r0 = (++it)->u.operand;
1733             int offset = (++it)->u.operand;
1734             int r1 = (++it)->u.operand;
1735             printLocationAndOp(out, exec, location, it, "put_to_arguments");
1736             out.printf("%s, %d, %s", registerName(r0).data(), offset, registerName(r1).data());
1737             break;
1738         }
1739         default:
1740             RELEASE_ASSERT_NOT_REACHED();
1741     }
1742
1743     dumpRareCaseProfile(out, "rare case: ", rareCaseProfileForBytecodeOffset(location), hasPrintedProfiling);
1744     dumpResultProfile(out, resultProfileForBytecodeOffset(location), hasPrintedProfiling);
1745     
1746 #if ENABLE(DFG_JIT)
1747     Vector<DFG::FrequentExitSite> exitSites = exitProfile().exitSitesFor(location);
1748     if (!exitSites.isEmpty()) {
1749         out.print(" !! frequent exits: ");
1750         CommaPrinter comma;
1751         for (unsigned i = 0; i < exitSites.size(); ++i)
1752             out.print(comma, exitSites[i].kind(), " ", exitSites[i].jitType());
1753     }
1754 #else // ENABLE(DFG_JIT)
1755     UNUSED_PARAM(location);
1756 #endif // ENABLE(DFG_JIT)
1757     out.print("\n");
1758 }
1759
1760 void CodeBlock::dumpBytecode(
1761     PrintStream& out, unsigned bytecodeOffset,
1762     const StubInfoMap& stubInfos, const CallLinkInfoMap& callLinkInfos)
1763 {
1764     ExecState* exec = m_globalObject->globalExec();
1765     const Instruction* it = instructions().begin() + bytecodeOffset;
1766     dumpBytecode(out, exec, instructions().begin(), it, stubInfos, callLinkInfos);
1767 }
1768
1769 #define FOR_EACH_MEMBER_VECTOR(macro) \
1770     macro(instructions) \
1771     macro(callLinkInfos) \
1772     macro(linkedCallerList) \
1773     macro(identifiers) \
1774     macro(functionExpressions) \
1775     macro(constantRegisters)
1776
1777 #define FOR_EACH_MEMBER_VECTOR_RARE_DATA(macro) \
1778     macro(regexps) \
1779     macro(functions) \
1780     macro(exceptionHandlers) \
1781     macro(switchJumpTables) \
1782     macro(stringSwitchJumpTables) \
1783     macro(evalCodeCache) \
1784     macro(expressionInfo) \
1785     macro(lineInfo) \
1786     macro(callReturnIndexVector)
1787
1788 template<typename T>
1789 static size_t sizeInBytes(const Vector<T>& vector)
1790 {
1791     return vector.capacity() * sizeof(T);
1792 }
1793
1794 namespace {
1795
1796 class PutToScopeFireDetail : public FireDetail {
1797 public:
1798     PutToScopeFireDetail(CodeBlock* codeBlock, const Identifier& ident)
1799         : m_codeBlock(codeBlock)
1800         , m_ident(ident)
1801     {
1802     }
1803     
1804     void dump(PrintStream& out) const override
1805     {
1806         out.print("Linking put_to_scope in ", FunctionExecutableDump(jsCast<FunctionExecutable*>(m_codeBlock->ownerExecutable())), " for ", m_ident);
1807     }
1808     
1809 private:
1810     CodeBlock* m_codeBlock;
1811     const Identifier& m_ident;
1812 };
1813
1814 } // anonymous namespace
1815
1816 CodeBlock::CodeBlock(VM* vm, Structure* structure, CopyParsedBlockTag, CodeBlock& other)
1817     : JSCell(*vm, structure)
1818     , m_globalObject(other.m_globalObject)
1819     , m_numCalleeLocals(other.m_numCalleeLocals)
1820     , m_numVars(other.m_numVars)
1821     , m_shouldAlwaysBeInlined(true)
1822 #if ENABLE(JIT)
1823     , m_capabilityLevelState(DFG::CapabilityLevelNotSet)
1824 #endif
1825     , m_didFailFTLCompilation(false)
1826     , m_hasBeenCompiledWithFTL(false)
1827     , m_isConstructor(other.m_isConstructor)
1828     , m_isStrictMode(other.m_isStrictMode)
1829     , m_codeType(other.m_codeType)
1830     , m_unlinkedCode(*other.m_vm, this, other.m_unlinkedCode.get())
1831     , m_hasDebuggerStatement(false)
1832     , m_steppingMode(SteppingModeDisabled)
1833     , m_numBreakpoints(0)
1834     , m_ownerExecutable(*other.m_vm, this, other.m_ownerExecutable.get())
1835     , m_vm(other.m_vm)
1836     , m_instructions(other.m_instructions)
1837     , m_thisRegister(other.m_thisRegister)
1838     , m_scopeRegister(other.m_scopeRegister)
1839     , m_hash(other.m_hash)
1840     , m_source(other.m_source)
1841     , m_sourceOffset(other.m_sourceOffset)
1842     , m_firstLineColumnOffset(other.m_firstLineColumnOffset)
1843     , m_constantRegisters(other.m_constantRegisters)
1844     , m_constantsSourceCodeRepresentation(other.m_constantsSourceCodeRepresentation)
1845     , m_functionDecls(other.m_functionDecls)
1846     , m_functionExprs(other.m_functionExprs)
1847     , m_osrExitCounter(0)
1848     , m_optimizationDelayCounter(0)
1849     , m_reoptimizationRetryCounter(0)
1850     , m_creationTime(std::chrono::steady_clock::now())
1851 {
1852     m_visitWeaklyHasBeenCalled.store(false, std::memory_order_relaxed);
1853
1854     ASSERT(heap()->isDeferred());
1855     ASSERT(m_scopeRegister.isLocal());
1856
1857     setNumParameters(other.numParameters());
1858 }
1859
1860 struct AbstractResolveKey {
1861     AbstractResolveKey()
1862         : m_impl(nullptr)
1863     { }
1864     AbstractResolveKey(size_t depth, const Identifier& ident, GetOrPut getOrPut, ResolveType resolveType, InitializationMode initializationMode)
1865         : m_depth(depth)
1866         , m_impl(ident.impl())
1867         , m_getOrPut(getOrPut)
1868         , m_resolveType(resolveType)
1869         , m_initializationMode(initializationMode)
1870     { }
1871
1872
1873     bool operator==(const AbstractResolveKey& other) const
1874     { 
1875         return m_impl == other.m_impl
1876             && m_depth == other.m_depth
1877             && m_getOrPut == other.m_getOrPut
1878             && m_resolveType == other.m_resolveType
1879             && m_initializationMode == other.m_initializationMode;
1880     }
1881
1882     bool isNull() const { return !m_impl; }
1883
1884     size_t m_depth;
1885     UniquedStringImpl* m_impl;
1886     GetOrPut m_getOrPut;
1887     ResolveType m_resolveType;
1888     InitializationMode m_initializationMode;
1889 };
1890
1891 void CodeBlock::finishCreation(VM& vm, CopyParsedBlockTag, CodeBlock& other)
1892 {
1893     Base::finishCreation(vm);
1894
1895     optimizeAfterWarmUp();
1896     jitAfterWarmUp();
1897
1898     if (other.m_rareData) {
1899         createRareDataIfNecessary();
1900         
1901         m_rareData->m_exceptionHandlers = other.m_rareData->m_exceptionHandlers;
1902         m_rareData->m_constantBuffers = other.m_rareData->m_constantBuffers;
1903         m_rareData->m_switchJumpTables = other.m_rareData->m_switchJumpTables;
1904         m_rareData->m_stringSwitchJumpTables = other.m_rareData->m_stringSwitchJumpTables;
1905         m_rareData->m_liveCalleeLocalsAtYield = other.m_rareData->m_liveCalleeLocalsAtYield;
1906     }
1907     
1908     heap()->m_codeBlocks.add(this);
1909 }
1910
1911 CodeBlock::CodeBlock(VM* vm, Structure* structure, ScriptExecutable* ownerExecutable, UnlinkedCodeBlock* unlinkedCodeBlock,
1912     JSScope* scope, PassRefPtr<SourceProvider> sourceProvider, unsigned sourceOffset, unsigned firstLineColumnOffset)
1913     : JSCell(*vm, structure)
1914     , m_globalObject(scope->globalObject()->vm(), this, scope->globalObject())
1915     , m_numCalleeLocals(unlinkedCodeBlock->m_numCalleeLocals)
1916     , m_numVars(unlinkedCodeBlock->m_numVars)
1917     , m_shouldAlwaysBeInlined(true)
1918 #if ENABLE(JIT)
1919     , m_capabilityLevelState(DFG::CapabilityLevelNotSet)
1920 #endif
1921     , m_didFailFTLCompilation(false)
1922     , m_hasBeenCompiledWithFTL(false)
1923     , m_isConstructor(unlinkedCodeBlock->isConstructor())
1924     , m_isStrictMode(unlinkedCodeBlock->isStrictMode())
1925     , m_codeType(unlinkedCodeBlock->codeType())
1926     , m_unlinkedCode(m_globalObject->vm(), this, unlinkedCodeBlock)
1927     , m_hasDebuggerStatement(false)
1928     , m_steppingMode(SteppingModeDisabled)
1929     , m_numBreakpoints(0)
1930     , m_ownerExecutable(m_globalObject->vm(), this, ownerExecutable)
1931     , m_vm(unlinkedCodeBlock->vm())
1932     , m_thisRegister(unlinkedCodeBlock->thisRegister())
1933     , m_scopeRegister(unlinkedCodeBlock->scopeRegister())
1934     , m_source(sourceProvider)
1935     , m_sourceOffset(sourceOffset)
1936     , m_firstLineColumnOffset(firstLineColumnOffset)
1937     , m_osrExitCounter(0)
1938     , m_optimizationDelayCounter(0)
1939     , m_reoptimizationRetryCounter(0)
1940     , m_creationTime(std::chrono::steady_clock::now())
1941 {
1942     m_visitWeaklyHasBeenCalled.store(false, std::memory_order_relaxed);
1943
1944     ASSERT(heap()->isDeferred());
1945     ASSERT(m_scopeRegister.isLocal());
1946
1947     ASSERT(m_source);
1948     setNumParameters(unlinkedCodeBlock->numParameters());
1949 }
1950
1951 void CodeBlock::finishCreation(VM& vm, ScriptExecutable* ownerExecutable, UnlinkedCodeBlock* unlinkedCodeBlock,
1952     JSScope* scope)
1953 {
1954     Base::finishCreation(vm);
1955
1956     if (vm.typeProfiler() || vm.controlFlowProfiler())
1957         vm.functionHasExecutedCache()->removeUnexecutedRange(ownerExecutable->sourceID(), ownerExecutable->typeProfilingStartOffset(), ownerExecutable->typeProfilingEndOffset());
1958
1959     setConstantRegisters(unlinkedCodeBlock->constantRegisters(), unlinkedCodeBlock->constantsSourceCodeRepresentation());
1960     if (unlinkedCodeBlock->usesGlobalObject())
1961         m_constantRegisters[unlinkedCodeBlock->globalObjectRegister().toConstantIndex()].set(*m_vm, this, m_globalObject.get());
1962
1963     for (unsigned i = 0; i < LinkTimeConstantCount; i++) {
1964         LinkTimeConstant type = static_cast<LinkTimeConstant>(i);
1965         if (unsigned registerIndex = unlinkedCodeBlock->registerIndexForLinkTimeConstant(type))
1966             m_constantRegisters[registerIndex].set(*m_vm, this, m_globalObject->jsCellForLinkTimeConstant(type));
1967     }
1968
1969     // We already have the cloned symbol table for the module environment since we need to instantiate
1970     // the module environments before linking the code block. We replace the stored symbol table with the already cloned one.
1971     if (UnlinkedModuleProgramCodeBlock* unlinkedModuleProgramCodeBlock = jsDynamicCast<UnlinkedModuleProgramCodeBlock*>(unlinkedCodeBlock)) {
1972         SymbolTable* clonedSymbolTable = jsCast<ModuleProgramExecutable*>(ownerExecutable)->moduleEnvironmentSymbolTable();
1973         if (m_vm->typeProfiler()) {
1974             ConcurrentJITLocker locker(clonedSymbolTable->m_lock);
1975             clonedSymbolTable->prepareForTypeProfiling(locker);
1976         }
1977         replaceConstant(unlinkedModuleProgramCodeBlock->moduleEnvironmentSymbolTableConstantRegisterOffset(), clonedSymbolTable);
1978     }
1979
1980     bool shouldUpdateFunctionHasExecutedCache = vm.typeProfiler() || vm.controlFlowProfiler();
1981     m_functionDecls = RefCountedArray<WriteBarrier<FunctionExecutable>>(unlinkedCodeBlock->numberOfFunctionDecls());
1982     for (size_t count = unlinkedCodeBlock->numberOfFunctionDecls(), i = 0; i < count; ++i) {
1983         UnlinkedFunctionExecutable* unlinkedExecutable = unlinkedCodeBlock->functionDecl(i);
1984         if (shouldUpdateFunctionHasExecutedCache)
1985             vm.functionHasExecutedCache()->insertUnexecutedRange(ownerExecutable->sourceID(), unlinkedExecutable->typeProfilingStartOffset(), unlinkedExecutable->typeProfilingEndOffset());
1986         m_functionDecls[i].set(*m_vm, this, unlinkedExecutable->link(*m_vm, ownerExecutable->source()));
1987     }
1988
1989     m_functionExprs = RefCountedArray<WriteBarrier<FunctionExecutable>>(unlinkedCodeBlock->numberOfFunctionExprs());
1990     for (size_t count = unlinkedCodeBlock->numberOfFunctionExprs(), i = 0; i < count; ++i) {
1991         UnlinkedFunctionExecutable* unlinkedExecutable = unlinkedCodeBlock->functionExpr(i);
1992         if (shouldUpdateFunctionHasExecutedCache)
1993             vm.functionHasExecutedCache()->insertUnexecutedRange(ownerExecutable->sourceID(), unlinkedExecutable->typeProfilingStartOffset(), unlinkedExecutable->typeProfilingEndOffset());
1994         m_functionExprs[i].set(*m_vm, this, unlinkedExecutable->link(*m_vm, ownerExecutable->source()));
1995     }
1996
1997     if (unlinkedCodeBlock->hasRareData()) {
1998         createRareDataIfNecessary();
1999         if (size_t count = unlinkedCodeBlock->constantBufferCount()) {
2000             m_rareData->m_constantBuffers.grow(count);
2001             for (size_t i = 0; i < count; i++) {
2002                 const UnlinkedCodeBlock::ConstantBuffer& buffer = unlinkedCodeBlock->constantBuffer(i);
2003                 m_rareData->m_constantBuffers[i] = buffer;
2004             }
2005         }
2006         if (size_t count = unlinkedCodeBlock->numberOfExceptionHandlers()) {
2007             m_rareData->m_exceptionHandlers.resizeToFit(count);
2008             for (size_t i = 0; i < count; i++) {
2009                 const UnlinkedHandlerInfo& unlinkedHandler = unlinkedCodeBlock->exceptionHandler(i);
2010                 HandlerInfo& handler = m_rareData->m_exceptionHandlers[i];
2011 #if ENABLE(JIT)
2012                 handler.initialize(unlinkedHandler, CodeLocationLabel(MacroAssemblerCodePtr::createFromExecutableAddress(LLInt::getCodePtr(op_catch))));
2013 #else
2014                 handler.initialize(unlinkedHandler);
2015 #endif
2016             }
2017         }
2018
2019         if (size_t count = unlinkedCodeBlock->numberOfStringSwitchJumpTables()) {
2020             m_rareData->m_stringSwitchJumpTables.grow(count);
2021             for (size_t i = 0; i < count; i++) {
2022                 UnlinkedStringJumpTable::StringOffsetTable::iterator ptr = unlinkedCodeBlock->stringSwitchJumpTable(i).offsetTable.begin();
2023                 UnlinkedStringJumpTable::StringOffsetTable::iterator end = unlinkedCodeBlock->stringSwitchJumpTable(i).offsetTable.end();
2024                 for (; ptr != end; ++ptr) {
2025                     OffsetLocation offset;
2026                     offset.branchOffset = ptr->value;
2027                     m_rareData->m_stringSwitchJumpTables[i].offsetTable.add(ptr->key, offset);
2028                 }
2029             }
2030         }
2031
2032         if (size_t count = unlinkedCodeBlock->numberOfSwitchJumpTables()) {
2033             m_rareData->m_switchJumpTables.grow(count);
2034             for (size_t i = 0; i < count; i++) {
2035                 UnlinkedSimpleJumpTable& sourceTable = unlinkedCodeBlock->switchJumpTable(i);
2036                 SimpleJumpTable& destTable = m_rareData->m_switchJumpTables[i];
2037                 destTable.branchOffsets = sourceTable.branchOffsets;
2038                 destTable.min = sourceTable.min;
2039             }
2040         }
2041     }
2042
2043     // Allocate metadata buffers for the bytecode
2044     if (size_t size = unlinkedCodeBlock->numberOfLLintCallLinkInfos())
2045         m_llintCallLinkInfos = RefCountedArray<LLIntCallLinkInfo>(size);
2046     if (size_t size = unlinkedCodeBlock->numberOfArrayProfiles())
2047         m_arrayProfiles.grow(size);
2048     if (size_t size = unlinkedCodeBlock->numberOfArrayAllocationProfiles())
2049         m_arrayAllocationProfiles = RefCountedArray<ArrayAllocationProfile>(size);
2050     if (size_t size = unlinkedCodeBlock->numberOfValueProfiles())
2051         m_valueProfiles = RefCountedArray<ValueProfile>(size);
2052     if (size_t size = unlinkedCodeBlock->numberOfObjectAllocationProfiles())
2053         m_objectAllocationProfiles = RefCountedArray<ObjectAllocationProfile>(size);
2054
2055 #if ENABLE(JIT)
2056     setCalleeSaveRegisters(RegisterSet::llintBaselineCalleeSaveRegisters());
2057 #endif
2058
2059     AbstractResolveKey lastResolveKey;
2060     ResolveOp lastCachedOp;
2061     auto cachedAbstractResolve = [&] (size_t localScopeDepth, const Identifier& ident, GetOrPut getOrPut, ResolveType resolveType, InitializationMode initializationMode) -> const ResolveOp& {
2062         AbstractResolveKey key(localScopeDepth, ident, getOrPut, resolveType, initializationMode);
2063         if (key == lastResolveKey) {
2064             ASSERT(!lastResolveKey.isNull());
2065             return lastCachedOp;
2066         }
2067         lastCachedOp = JSScope::abstractResolve(m_globalObject->globalExec(), localScopeDepth, scope, ident, getOrPut, resolveType, initializationMode);
2068         lastResolveKey = key;
2069         return lastCachedOp;
2070     };
2071
2072     // Copy and translate the UnlinkedInstructions
2073     unsigned instructionCount = unlinkedCodeBlock->instructions().count();
2074     UnlinkedInstructionStream::Reader instructionReader(unlinkedCodeBlock->instructions());
2075
2076     // Bookkeep the strongly referenced module environments.
2077     HashSet<JSModuleEnvironment*> stronglyReferencedModuleEnvironments;
2078
2079     // Bookkeep the merge point bytecode offsets.
2080     Vector<size_t> mergePointBytecodeOffsets;
2081
2082     RefCountedArray<Instruction> instructions(instructionCount);
2083
2084     for (unsigned i = 0; !instructionReader.atEnd(); ) {
2085         const UnlinkedInstruction* pc = instructionReader.next();
2086
2087         unsigned opLength = opcodeLength(pc[0].u.opcode);
2088
2089         instructions[i] = vm.interpreter->getOpcode(pc[0].u.opcode);
2090         for (size_t j = 1; j < opLength; ++j) {
2091             if (sizeof(int32_t) != sizeof(intptr_t))
2092                 instructions[i + j].u.pointer = 0;
2093             instructions[i + j].u.operand = pc[j].u.operand;
2094         }
2095         switch (pc[0].u.opcode) {
2096         case op_has_indexed_property: {
2097             int arrayProfileIndex = pc[opLength - 1].u.operand;
2098             m_arrayProfiles[arrayProfileIndex] = ArrayProfile(i);
2099
2100             instructions[i + opLength - 1] = &m_arrayProfiles[arrayProfileIndex];
2101             break;
2102         }
2103         case op_call_varargs:
2104         case op_tail_call_varargs:
2105         case op_construct_varargs:
2106         case op_get_by_val: {
2107             int arrayProfileIndex = pc[opLength - 2].u.operand;
2108             m_arrayProfiles[arrayProfileIndex] = ArrayProfile(i);
2109
2110             instructions[i + opLength - 2] = &m_arrayProfiles[arrayProfileIndex];
2111             FALLTHROUGH;
2112         }
2113         case op_get_direct_pname:
2114         case op_get_by_id:
2115         case op_get_from_arguments: {
2116             ValueProfile* profile = &m_valueProfiles[pc[opLength - 1].u.operand];
2117             ASSERT(profile->m_bytecodeOffset == -1);
2118             profile->m_bytecodeOffset = i;
2119             instructions[i + opLength - 1] = profile;
2120             break;
2121         }
2122         case op_put_by_val: {
2123             int arrayProfileIndex = pc[opLength - 1].u.operand;
2124             m_arrayProfiles[arrayProfileIndex] = ArrayProfile(i);
2125             instructions[i + opLength - 1] = &m_arrayProfiles[arrayProfileIndex];
2126             break;
2127         }
2128         case op_put_by_val_direct: {
2129             int arrayProfileIndex = pc[opLength - 1].u.operand;
2130             m_arrayProfiles[arrayProfileIndex] = ArrayProfile(i);
2131             instructions[i + opLength - 1] = &m_arrayProfiles[arrayProfileIndex];
2132             break;
2133         }
2134
2135         case op_new_array:
2136         case op_new_array_buffer:
2137         case op_new_array_with_size: {
2138             int arrayAllocationProfileIndex = pc[opLength - 1].u.operand;
2139             instructions[i + opLength - 1] = &m_arrayAllocationProfiles[arrayAllocationProfileIndex];
2140             break;
2141         }
2142         case op_new_object: {
2143             int objectAllocationProfileIndex = pc[opLength - 1].u.operand;
2144             ObjectAllocationProfile* objectAllocationProfile = &m_objectAllocationProfiles[objectAllocationProfileIndex];
2145             int inferredInlineCapacity = pc[opLength - 2].u.operand;
2146
2147             instructions[i + opLength - 1] = objectAllocationProfile;
2148             objectAllocationProfile->initialize(vm,
2149                 this, m_globalObject->objectPrototype(), inferredInlineCapacity);
2150             break;
2151         }
2152
2153         case op_call:
2154         case op_tail_call:
2155         case op_call_eval: {
2156             ValueProfile* profile = &m_valueProfiles[pc[opLength - 1].u.operand];
2157             ASSERT(profile->m_bytecodeOffset == -1);
2158             profile->m_bytecodeOffset = i;
2159             instructions[i + opLength - 1] = profile;
2160             int arrayProfileIndex = pc[opLength - 2].u.operand;
2161             m_arrayProfiles[arrayProfileIndex] = ArrayProfile(i);
2162             instructions[i + opLength - 2] = &m_arrayProfiles[arrayProfileIndex];
2163             instructions[i + 5] = &m_llintCallLinkInfos[pc[5].u.operand];
2164             break;
2165         }
2166         case op_construct: {
2167             instructions[i + 5] = &m_llintCallLinkInfos[pc[5].u.operand];
2168             ValueProfile* profile = &m_valueProfiles[pc[opLength - 1].u.operand];
2169             ASSERT(profile->m_bytecodeOffset == -1);
2170             profile->m_bytecodeOffset = i;
2171             instructions[i + opLength - 1] = profile;
2172             break;
2173         }
2174         case op_get_array_length:
2175             CRASH();
2176
2177         case op_resolve_scope: {
2178             const Identifier& ident = identifier(pc[3].u.operand);
2179             ResolveType type = static_cast<ResolveType>(pc[4].u.operand);
2180             RELEASE_ASSERT(type != LocalClosureVar);
2181             int localScopeDepth = pc[5].u.operand;
2182
2183             const ResolveOp& op = cachedAbstractResolve(localScopeDepth, ident, Get, type, InitializationMode::NotInitialization);
2184             instructions[i + 4].u.operand = op.type;
2185             instructions[i + 5].u.operand = op.depth;
2186             if (op.lexicalEnvironment) {
2187                 if (op.type == ModuleVar) {
2188                     // Keep the linked module environment strongly referenced.
2189                     if (stronglyReferencedModuleEnvironments.add(jsCast<JSModuleEnvironment*>(op.lexicalEnvironment)).isNewEntry)
2190                         addConstant(op.lexicalEnvironment);
2191                     instructions[i + 6].u.jsCell.set(vm, this, op.lexicalEnvironment);
2192                 } else
2193                     instructions[i + 6].u.symbolTable.set(vm, this, op.lexicalEnvironment->symbolTable());
2194             } else if (JSScope* constantScope = JSScope::constantScopeForCodeBlock(op.type, this))
2195                 instructions[i + 6].u.jsCell.set(vm, this, constantScope);
2196             else
2197                 instructions[i + 6].u.pointer = nullptr;
2198             break;
2199         }
2200
2201         case op_get_from_scope: {
2202             ValueProfile* profile = &m_valueProfiles[pc[opLength - 1].u.operand];
2203             ASSERT(profile->m_bytecodeOffset == -1);
2204             profile->m_bytecodeOffset = i;
2205             instructions[i + opLength - 1] = profile;
2206
2207             // get_from_scope dst, scope, id, GetPutInfo, Structure, Operand
2208
2209             int localScopeDepth = pc[5].u.operand;
2210             instructions[i + 5].u.pointer = nullptr;
2211
2212             GetPutInfo getPutInfo = GetPutInfo(pc[4].u.operand);
2213             ASSERT(!isInitialization(getPutInfo.initializationMode()));
2214             if (getPutInfo.resolveType() == LocalClosureVar) {
2215                 instructions[i + 4] = GetPutInfo(getPutInfo.resolveMode(), ClosureVar, getPutInfo.initializationMode()).operand();
2216                 break;
2217             }
2218
2219             const Identifier& ident = identifier(pc[3].u.operand);
2220             const ResolveOp& op = cachedAbstractResolve(localScopeDepth, ident, Get, getPutInfo.resolveType(), InitializationMode::NotInitialization);
2221
2222             instructions[i + 4].u.operand = GetPutInfo(getPutInfo.resolveMode(), op.type, getPutInfo.initializationMode()).operand();
2223             if (op.type == ModuleVar)
2224                 instructions[i + 4].u.operand = GetPutInfo(getPutInfo.resolveMode(), ClosureVar, getPutInfo.initializationMode()).operand();
2225             if (op.type == GlobalVar || op.type == GlobalVarWithVarInjectionChecks || op.type == GlobalLexicalVar || op.type == GlobalLexicalVarWithVarInjectionChecks)
2226                 instructions[i + 5].u.watchpointSet = op.watchpointSet;
2227             else if (op.structure)
2228                 instructions[i + 5].u.structure.set(vm, this, op.structure);
2229             instructions[i + 6].u.pointer = reinterpret_cast<void*>(op.operand);
2230             break;
2231         }
2232
2233         case op_put_to_scope: {
2234             // put_to_scope scope, id, value, GetPutInfo, Structure, Operand
2235             GetPutInfo getPutInfo = GetPutInfo(pc[4].u.operand);
2236             if (getPutInfo.resolveType() == LocalClosureVar) {
2237                 // Only do watching if the property we're putting to is not anonymous.
2238                 if (static_cast<unsigned>(pc[2].u.operand) != UINT_MAX) {
2239                     int symbolTableIndex = pc[5].u.operand;
2240                     SymbolTable* symbolTable = jsCast<SymbolTable*>(getConstant(symbolTableIndex));
2241                     const Identifier& ident = identifier(pc[2].u.operand);
2242                     ConcurrentJITLocker locker(symbolTable->m_lock);
2243                     auto iter = symbolTable->find(locker, ident.impl());
2244                     ASSERT(iter != symbolTable->end(locker));
2245                     iter->value.prepareToWatch();
2246                     instructions[i + 5].u.watchpointSet = iter->value.watchpointSet();
2247                 } else
2248                     instructions[i + 5].u.watchpointSet = nullptr;
2249                 break;
2250             }
2251
2252             const Identifier& ident = identifier(pc[2].u.operand);
2253             int localScopeDepth = pc[5].u.operand;
2254             instructions[i + 5].u.pointer = nullptr;
2255             const ResolveOp& op = cachedAbstractResolve(localScopeDepth, ident, Put, getPutInfo.resolveType(), getPutInfo.initializationMode());
2256
2257             instructions[i + 4].u.operand = GetPutInfo(getPutInfo.resolveMode(), op.type, getPutInfo.initializationMode()).operand();
2258             if (op.type == GlobalVar || op.type == GlobalVarWithVarInjectionChecks || op.type == GlobalLexicalVar || op.type == GlobalLexicalVarWithVarInjectionChecks)
2259                 instructions[i + 5].u.watchpointSet = op.watchpointSet;
2260             else if (op.type == ClosureVar || op.type == ClosureVarWithVarInjectionChecks) {
2261                 if (op.watchpointSet)
2262                     op.watchpointSet->invalidate(PutToScopeFireDetail(this, ident));
2263             } else if (op.structure)
2264                 instructions[i + 5].u.structure.set(vm, this, op.structure);
2265             instructions[i + 6].u.pointer = reinterpret_cast<void*>(op.operand);
2266
2267             break;
2268         }
2269
2270         case op_profile_type: {
2271             RELEASE_ASSERT(vm.typeProfiler());
2272             // The format of this instruction is: op_profile_type regToProfile, TypeLocation*, flag, identifier?, resolveType?
2273             size_t instructionOffset = i + opLength - 1;
2274             unsigned divotStart, divotEnd;
2275             GlobalVariableID globalVariableID = 0;
2276             RefPtr<TypeSet> globalTypeSet;
2277             bool shouldAnalyze = m_unlinkedCode->typeProfilerExpressionInfoForBytecodeOffset(instructionOffset, divotStart, divotEnd);
2278             VirtualRegister profileRegister(pc[1].u.operand);
2279             ProfileTypeBytecodeFlag flag = static_cast<ProfileTypeBytecodeFlag>(pc[3].u.operand);
2280             SymbolTable* symbolTable = nullptr;
2281
2282             switch (flag) {
2283             case ProfileTypeBytecodeClosureVar: {
2284                 const Identifier& ident = identifier(pc[4].u.operand);
2285                 int localScopeDepth = pc[2].u.operand;
2286                 ResolveType type = static_cast<ResolveType>(pc[5].u.operand);
2287                 // Even though type profiling may be profiling either a Get or a Put, we can always claim a Get because
2288                 // we're abstractly "read"ing from a JSScope.
2289                 const ResolveOp& op = cachedAbstractResolve(localScopeDepth, ident, Get, type, InitializationMode::NotInitialization);
2290
2291                 if (op.type == ClosureVar || op.type == ModuleVar)
2292                     symbolTable = op.lexicalEnvironment->symbolTable();
2293                 else if (op.type == GlobalVar)
2294                     symbolTable = m_globalObject.get()->symbolTable();
2295
2296                 UniquedStringImpl* impl = (op.type == ModuleVar) ? op.importedName.get() : ident.impl();
2297                 if (symbolTable) {
2298                     ConcurrentJITLocker locker(symbolTable->m_lock);
2299                     // If our parent scope was created while profiling was disabled, it will not have prepared for profiling yet.
2300                     symbolTable->prepareForTypeProfiling(locker);
2301                     globalVariableID = symbolTable->uniqueIDForVariable(locker, impl, vm);
2302                     globalTypeSet = symbolTable->globalTypeSetForVariable(locker, impl, vm);
2303                 } else
2304                     globalVariableID = TypeProfilerNoGlobalIDExists;
2305
2306                 break;
2307             }
2308             case ProfileTypeBytecodeLocallyResolved: {
2309                 int symbolTableIndex = pc[2].u.operand;
2310                 SymbolTable* symbolTable = jsCast<SymbolTable*>(getConstant(symbolTableIndex));
2311                 const Identifier& ident = identifier(pc[4].u.operand);
2312                 ConcurrentJITLocker locker(symbolTable->m_lock);
2313                 // If our parent scope was created while profiling was disabled, it will not have prepared for profiling yet.
2314                 globalVariableID = symbolTable->uniqueIDForVariable(locker, ident.impl(), vm);
2315                 globalTypeSet = symbolTable->globalTypeSetForVariable(locker, ident.impl(), vm);
2316
2317                 break;
2318             }
2319             case ProfileTypeBytecodeDoesNotHaveGlobalID: 
2320             case ProfileTypeBytecodeFunctionArgument: {
2321                 globalVariableID = TypeProfilerNoGlobalIDExists;
2322                 break;
2323             }
2324             case ProfileTypeBytecodeFunctionReturnStatement: {
2325                 RELEASE_ASSERT(ownerExecutable->isFunctionExecutable());
2326                 globalTypeSet = jsCast<FunctionExecutable*>(ownerExecutable)->returnStatementTypeSet();
2327                 globalVariableID = TypeProfilerReturnStatement;
2328                 if (!shouldAnalyze) {
2329                     // Because a return statement can be added implicitly to return undefined at the end of a function,
2330                     // and these nodes don't emit expression ranges because they aren't in the actual source text of
2331                     // the user's program, give the type profiler some range to identify these return statements.
2332                     // Currently, the text offset that is used as identification is "f" in the function keyword
2333                     // and is stored on TypeLocation's m_divotForFunctionOffsetIfReturnStatement member variable.
2334                     divotStart = divotEnd = ownerExecutable->typeProfilingStartOffset();
2335                     shouldAnalyze = true;
2336                 }
2337                 break;
2338             }
2339             }
2340
2341             std::pair<TypeLocation*, bool> locationPair = vm.typeProfiler()->typeLocationCache()->getTypeLocation(globalVariableID,
2342                 ownerExecutable->sourceID(), divotStart, divotEnd, globalTypeSet, &vm);
2343             TypeLocation* location = locationPair.first;
2344             bool isNewLocation = locationPair.second;
2345
2346             if (flag == ProfileTypeBytecodeFunctionReturnStatement)
2347                 location->m_divotForFunctionOffsetIfReturnStatement = ownerExecutable->typeProfilingStartOffset();
2348
2349             if (shouldAnalyze && isNewLocation)
2350                 vm.typeProfiler()->insertNewLocation(location);
2351
2352             instructions[i + 2].u.location = location;
2353             break;
2354         }
2355
2356         case op_debug: {
2357             if (pc[1].u.index == DidReachBreakpoint)
2358                 m_hasDebuggerStatement = true;
2359             break;
2360         }
2361
2362         case op_save: {
2363             unsigned liveCalleeLocalsIndex = pc[2].u.index;
2364             int offset = pc[3].u.operand;
2365             if (liveCalleeLocalsIndex >= mergePointBytecodeOffsets.size())
2366                 mergePointBytecodeOffsets.resize(liveCalleeLocalsIndex + 1);
2367             mergePointBytecodeOffsets[liveCalleeLocalsIndex] = i + offset;
2368             break;
2369         }
2370
2371         default:
2372             break;
2373         }
2374         i += opLength;
2375     }
2376
2377     if (vm.controlFlowProfiler())
2378         insertBasicBlockBoundariesForControlFlowProfiler(instructions);
2379
2380     m_instructions = WTFMove(instructions);
2381
2382     // Perform bytecode liveness analysis to determine which locals are live and should be resumed when executing op_resume.
2383     if (unlinkedCodeBlock->parseMode() == SourceParseMode::GeneratorBodyMode) {
2384         if (size_t count = mergePointBytecodeOffsets.size()) {
2385             createRareDataIfNecessary();
2386             BytecodeLivenessAnalysis liveness(this);
2387             m_rareData->m_liveCalleeLocalsAtYield.grow(count);
2388             size_t liveCalleeLocalsIndex = 0;
2389             for (size_t bytecodeOffset : mergePointBytecodeOffsets) {
2390                 m_rareData->m_liveCalleeLocalsAtYield[liveCalleeLocalsIndex] = liveness.getLivenessInfoAtBytecodeOffset(bytecodeOffset);
2391                 ++liveCalleeLocalsIndex;
2392             }
2393         }
2394     }
2395
2396     // Set optimization thresholds only after m_instructions is initialized, since these
2397     // rely on the instruction count (and are in theory permitted to also inspect the
2398     // instruction stream to more accurate assess the cost of tier-up).
2399     optimizeAfterWarmUp();
2400     jitAfterWarmUp();
2401
2402     // If the concurrent thread will want the code block's hash, then compute it here
2403     // synchronously.
2404     if (Options::alwaysComputeHash())
2405         hash();
2406
2407     if (Options::dumpGeneratedBytecodes())
2408         dumpBytecode();
2409     
2410     heap()->m_codeBlocks.add(this);
2411     heap()->reportExtraMemoryAllocated(m_instructions.size() * sizeof(Instruction));
2412 }
2413
2414 #if ENABLE(WEBASSEMBLY)
2415 CodeBlock::CodeBlock(VM* vm, Structure* structure, WebAssemblyExecutable* ownerExecutable, JSGlobalObject* globalObject)
2416     : JSCell(*vm, structure)
2417     , m_globalObject(globalObject->vm(), this, globalObject)
2418     , m_numCalleeLocals(0)
2419     , m_numVars(0)
2420     , m_shouldAlwaysBeInlined(false)
2421 #if ENABLE(JIT)
2422     , m_capabilityLevelState(DFG::CannotCompile)
2423 #endif
2424     , m_didFailFTLCompilation(false)
2425     , m_hasBeenCompiledWithFTL(false)
2426     , m_isConstructor(false)
2427     , m_isStrictMode(false)
2428     , m_codeType(FunctionCode)
2429     , m_hasDebuggerStatement(false)
2430     , m_steppingMode(SteppingModeDisabled)
2431     , m_numBreakpoints(0)
2432     , m_ownerExecutable(m_globalObject->vm(), this, ownerExecutable)
2433     , m_vm(vm)
2434     , m_osrExitCounter(0)
2435     , m_optimizationDelayCounter(0)
2436     , m_reoptimizationRetryCounter(0)
2437     , m_creationTime(std::chrono::steady_clock::now())
2438 {
2439     ASSERT(heap()->isDeferred());
2440 }
2441
2442 void CodeBlock::finishCreation(VM& vm, WebAssemblyExecutable*, JSGlobalObject*)
2443 {
2444     Base::finishCreation(vm);
2445
2446     heap()->m_codeBlocks.add(this);
2447 }
2448 #endif
2449
2450 CodeBlock::~CodeBlock()
2451 {
2452     if (m_vm->m_perBytecodeProfiler)
2453         m_vm->m_perBytecodeProfiler->notifyDestruction(this);
2454     
2455 #if ENABLE(VERBOSE_VALUE_PROFILE)
2456     dumpValueProfiles();
2457 #endif
2458
2459     // We may be destroyed before any CodeBlocks that refer to us are destroyed.
2460     // Consider that two CodeBlocks become unreachable at the same time. There
2461     // is no guarantee about the order in which the CodeBlocks are destroyed.
2462     // So, if we don't remove incoming calls, and get destroyed before the
2463     // CodeBlock(s) that have calls into us, then the CallLinkInfo vector's
2464     // destructor will try to remove nodes from our (no longer valid) linked list.
2465     unlinkIncomingCalls();
2466     
2467     // Note that our outgoing calls will be removed from other CodeBlocks'
2468     // m_incomingCalls linked lists through the execution of the ~CallLinkInfo
2469     // destructors.
2470
2471 #if ENABLE(JIT)
2472     for (Bag<StructureStubInfo>::iterator iter = m_stubInfos.begin(); !!iter; ++iter) {
2473         StructureStubInfo* stub = *iter;
2474         stub->aboutToDie();
2475         stub->deref();
2476     }
2477 #endif // ENABLE(JIT)
2478 }
2479
2480 void CodeBlock::setConstantRegisters(const Vector<WriteBarrier<Unknown>>& constants, const Vector<SourceCodeRepresentation>& constantsSourceCodeRepresentation)
2481 {
2482     ASSERT(constants.size() == constantsSourceCodeRepresentation.size());
2483     size_t count = constants.size();
2484     m_constantRegisters.resizeToFit(count);
2485     bool hasTypeProfiler = !!m_vm->typeProfiler();
2486     for (size_t i = 0; i < count; i++) {
2487         JSValue constant = constants[i].get();
2488
2489         if (!constant.isEmpty()) {
2490             if (SymbolTable* symbolTable = jsDynamicCast<SymbolTable*>(constant)) {
2491                 if (hasTypeProfiler) {
2492                     ConcurrentJITLocker locker(symbolTable->m_lock);
2493                     symbolTable->prepareForTypeProfiling(locker);
2494                 }
2495                 constant = symbolTable->cloneScopePart(*m_vm);
2496             }
2497         }
2498
2499         m_constantRegisters[i].set(*m_vm, this, constant);
2500     }
2501
2502     m_constantsSourceCodeRepresentation = constantsSourceCodeRepresentation;
2503 }
2504
2505 void CodeBlock::setAlternative(VM& vm, CodeBlock* alternative)
2506 {
2507     m_alternative.set(vm, this, alternative);
2508 }
2509
2510 void CodeBlock::setNumParameters(int newValue)
2511 {
2512     m_numParameters = newValue;
2513
2514     m_argumentValueProfiles = RefCountedArray<ValueProfile>(newValue);
2515 }
2516
2517 void EvalCodeCache::visitAggregate(SlotVisitor& visitor)
2518 {
2519     EvalCacheMap::iterator end = m_cacheMap.end();
2520     for (EvalCacheMap::iterator ptr = m_cacheMap.begin(); ptr != end; ++ptr)
2521         visitor.append(&ptr->value);
2522 }
2523
2524 CodeBlock* CodeBlock::specialOSREntryBlockOrNull()
2525 {
2526 #if ENABLE(FTL_JIT)
2527     if (jitType() != JITCode::DFGJIT)
2528         return 0;
2529     DFG::JITCode* jitCode = m_jitCode->dfg();
2530     return jitCode->osrEntryBlock();
2531 #else // ENABLE(FTL_JIT)
2532     return 0;
2533 #endif // ENABLE(FTL_JIT)
2534 }
2535
2536 void CodeBlock::visitWeakly(SlotVisitor& visitor)
2537 {
2538     bool setByMe = m_visitWeaklyHasBeenCalled.compareExchangeStrong(false, true);
2539     if (!setByMe)
2540         return;
2541
2542     if (Heap::isMarked(this))
2543         return;
2544
2545     if (shouldVisitStrongly()) {
2546         visitor.appendUnbarrieredReadOnlyPointer(this);
2547         return;
2548     }
2549
2550     // There are two things that may use unconditional finalizers: inline cache clearing
2551     // and jettisoning. The probability of us wanting to do at least one of those things
2552     // is probably quite close to 1. So we add one no matter what and when it runs, it
2553     // figures out whether it has any work to do.
2554     visitor.addUnconditionalFinalizer(&m_unconditionalFinalizer);
2555
2556     if (!JITCode::isOptimizingJIT(jitType()))
2557         return;
2558
2559     // If we jettison ourselves we'll install our alternative, so make sure that it
2560     // survives GC even if we don't.
2561     visitor.append(&m_alternative);
2562     
2563     // There are two things that we use weak reference harvesters for: DFG fixpoint for
2564     // jettisoning, and trying to find structures that would be live based on some
2565     // inline cache. So it makes sense to register them regardless.
2566     visitor.addWeakReferenceHarvester(&m_weakReferenceHarvester);
2567
2568 #if ENABLE(DFG_JIT)
2569     // We get here if we're live in the sense that our owner executable is live,
2570     // but we're not yet live for sure in another sense: we may yet decide that this
2571     // code block should be jettisoned based on its outgoing weak references being
2572     // stale. Set a flag to indicate that we're still assuming that we're dead, and
2573     // perform one round of determining if we're live. The GC may determine, based on
2574     // either us marking additional objects, or by other objects being marked for
2575     // other reasons, that this iteration should run again; it will notify us of this
2576     // decision by calling harvestWeakReferences().
2577
2578     m_allTransitionsHaveBeenMarked = false;
2579     propagateTransitions(visitor);
2580
2581     m_jitCode->dfgCommon()->livenessHasBeenProved = false;
2582     determineLiveness(visitor);
2583 #endif // ENABLE(DFG_JIT)
2584 }
2585
2586 size_t CodeBlock::estimatedSize(JSCell* cell)
2587 {
2588     CodeBlock* thisObject = jsCast<CodeBlock*>(cell);
2589     size_t extraMemoryAllocated = thisObject->m_instructions.size() * sizeof(Instruction);
2590     if (thisObject->m_jitCode)
2591         extraMemoryAllocated += thisObject->m_jitCode->size();
2592     return Base::estimatedSize(cell) + extraMemoryAllocated;
2593 }
2594
2595 void CodeBlock::visitChildren(JSCell* cell, SlotVisitor& visitor)
2596 {
2597     CodeBlock* thisObject = jsCast<CodeBlock*>(cell);
2598     ASSERT_GC_OBJECT_INHERITS(thisObject, info());
2599     JSCell::visitChildren(thisObject, visitor);
2600     thisObject->visitChildren(visitor);
2601 }
2602
2603 void CodeBlock::visitChildren(SlotVisitor& visitor)
2604 {
2605     // There are two things that may use unconditional finalizers: inline cache clearing
2606     // and jettisoning. The probability of us wanting to do at least one of those things
2607     // is probably quite close to 1. So we add one no matter what and when it runs, it
2608     // figures out whether it has any work to do.
2609     visitor.addUnconditionalFinalizer(&m_unconditionalFinalizer);
2610
2611     if (CodeBlock* otherBlock = specialOSREntryBlockOrNull())
2612         visitor.appendUnbarrieredReadOnlyPointer(otherBlock);
2613
2614     if (m_jitCode)
2615         visitor.reportExtraMemoryVisited(m_jitCode->size());
2616     if (m_instructions.size())
2617         visitor.reportExtraMemoryVisited(m_instructions.size() * sizeof(Instruction) / m_instructions.refCount());
2618
2619     stronglyVisitStrongReferences(visitor);
2620     stronglyVisitWeakReferences(visitor);
2621
2622     m_allTransitionsHaveBeenMarked = false;
2623     propagateTransitions(visitor);
2624 }
2625
2626 bool CodeBlock::shouldVisitStrongly()
2627 {
2628     if (Options::forceCodeBlockLiveness())
2629         return true;
2630
2631     if (shouldJettisonDueToOldAge())
2632         return false;
2633
2634     // Interpreter and Baseline JIT CodeBlocks don't need to be jettisoned when
2635     // their weak references go stale. So if a basline JIT CodeBlock gets
2636     // scanned, we can assume that this means that it's live.
2637     if (!JITCode::isOptimizingJIT(jitType()))
2638         return true;
2639
2640     return false;
2641 }
2642
2643 bool CodeBlock::shouldJettisonDueToWeakReference()
2644 {
2645     if (!JITCode::isOptimizingJIT(jitType()))
2646         return false;
2647     return !Heap::isMarked(this);
2648 }
2649
2650 bool CodeBlock::shouldJettisonDueToOldAge()
2651 {
2652     return false;
2653 }
2654
2655 #if ENABLE(DFG_JIT)
2656 static bool shouldMarkTransition(DFG::WeakReferenceTransition& transition)
2657 {
2658     if (transition.m_codeOrigin && !Heap::isMarked(transition.m_codeOrigin.get()))
2659         return false;
2660     
2661     if (!Heap::isMarked(transition.m_from.get()))
2662         return false;
2663     
2664     return true;
2665 }
2666 #endif // ENABLE(DFG_JIT)
2667
2668 void CodeBlock::propagateTransitions(SlotVisitor& visitor)
2669 {
2670     UNUSED_PARAM(visitor);
2671
2672     if (m_allTransitionsHaveBeenMarked)
2673         return;
2674
2675     bool allAreMarkedSoFar = true;
2676         
2677     Interpreter* interpreter = m_vm->interpreter;
2678     if (jitType() == JITCode::InterpreterThunk) {
2679         const Vector<unsigned>& propertyAccessInstructions = m_unlinkedCode->propertyAccessInstructions();
2680         for (size_t i = 0; i < propertyAccessInstructions.size(); ++i) {
2681             Instruction* instruction = &instructions()[propertyAccessInstructions[i]];
2682             switch (interpreter->getOpcodeID(instruction[0].u.opcode)) {
2683             case op_put_by_id: {
2684                 StructureID oldStructureID = instruction[4].u.structureID;
2685                 StructureID newStructureID = instruction[6].u.structureID;
2686                 if (!oldStructureID || !newStructureID)
2687                     break;
2688                 Structure* oldStructure =
2689                     m_vm->heap.structureIDTable().get(oldStructureID);
2690                 Structure* newStructure =
2691                     m_vm->heap.structureIDTable().get(newStructureID);
2692                 if (Heap::isMarked(oldStructure))
2693                     visitor.appendUnbarrieredReadOnlyPointer(newStructure);
2694                 else
2695                     allAreMarkedSoFar = false;
2696                 break;
2697             }
2698             default:
2699                 break;
2700             }
2701         }
2702     }
2703
2704 #if ENABLE(JIT)
2705     if (JITCode::isJIT(jitType())) {
2706         for (Bag<StructureStubInfo>::iterator iter = m_stubInfos.begin(); !!iter; ++iter)
2707             allAreMarkedSoFar &= (*iter)->propagateTransitions(visitor);
2708     }
2709 #endif // ENABLE(JIT)
2710     
2711 #if ENABLE(DFG_JIT)
2712     if (JITCode::isOptimizingJIT(jitType())) {
2713         DFG::CommonData* dfgCommon = m_jitCode->dfgCommon();
2714         for (auto& weakReference : dfgCommon->weakStructureReferences)
2715             allAreMarkedSoFar &= weakReference->markIfCheap(visitor);
2716         
2717         for (unsigned i = 0; i < dfgCommon->transitions.size(); ++i) {
2718             if (shouldMarkTransition(dfgCommon->transitions[i])) {
2719                 // If the following three things are live, then the target of the
2720                 // transition is also live:
2721                 //
2722                 // - This code block. We know it's live already because otherwise
2723                 //   we wouldn't be scanning ourselves.
2724                 //
2725                 // - The code origin of the transition. Transitions may arise from
2726                 //   code that was inlined. They are not relevant if the user's
2727                 //   object that is required for the inlinee to run is no longer
2728                 //   live.
2729                 //
2730                 // - The source of the transition. The transition checks if some
2731                 //   heap location holds the source, and if so, stores the target.
2732                 //   Hence the source must be live for the transition to be live.
2733                 //
2734                 // We also short-circuit the liveness if the structure is harmless
2735                 // to mark (i.e. its global object and prototype are both already
2736                 // live).
2737                 
2738                 visitor.append(&dfgCommon->transitions[i].m_to);
2739             } else
2740                 allAreMarkedSoFar = false;
2741         }
2742     }
2743 #endif // ENABLE(DFG_JIT)
2744     
2745     if (allAreMarkedSoFar)
2746         m_allTransitionsHaveBeenMarked = true;
2747 }
2748
2749 void CodeBlock::determineLiveness(SlotVisitor& visitor)
2750 {
2751     UNUSED_PARAM(visitor);
2752     
2753 #if ENABLE(DFG_JIT)
2754     // Check if we have any remaining work to do.
2755     DFG::CommonData* dfgCommon = m_jitCode->dfgCommon();
2756     if (dfgCommon->livenessHasBeenProved)
2757         return;
2758     
2759     // Now check all of our weak references. If all of them are live, then we
2760     // have proved liveness and so we scan our strong references. If at end of
2761     // GC we still have not proved liveness, then this code block is toast.
2762     bool allAreLiveSoFar = true;
2763     for (unsigned i = 0; i < dfgCommon->weakReferences.size(); ++i) {
2764         if (!Heap::isMarked(dfgCommon->weakReferences[i].get())) {
2765             allAreLiveSoFar = false;
2766             break;
2767         }
2768     }
2769     if (allAreLiveSoFar) {
2770         for (unsigned i = 0; i < dfgCommon->weakStructureReferences.size(); ++i) {
2771             if (!Heap::isMarked(dfgCommon->weakStructureReferences[i].get())) {
2772                 allAreLiveSoFar = false;
2773                 break;
2774             }
2775         }
2776     }
2777     
2778     // If some weak references are dead, then this fixpoint iteration was
2779     // unsuccessful.
2780     if (!allAreLiveSoFar)
2781         return;
2782     
2783     // All weak references are live. Record this information so we don't
2784     // come back here again, and scan the strong references.
2785     dfgCommon->livenessHasBeenProved = true;
2786     visitor.appendUnbarrieredReadOnlyPointer(this);
2787 #endif // ENABLE(DFG_JIT)
2788 }
2789
2790 void CodeBlock::WeakReferenceHarvester::visitWeakReferences(SlotVisitor& visitor)
2791 {
2792     CodeBlock* codeBlock =
2793         bitwise_cast<CodeBlock*>(
2794             bitwise_cast<char*>(this) - OBJECT_OFFSETOF(CodeBlock, m_weakReferenceHarvester));
2795
2796     codeBlock->propagateTransitions(visitor);
2797     codeBlock->determineLiveness(visitor);
2798 }
2799
2800 void CodeBlock::finalizeLLIntInlineCaches()
2801 {
2802 #if ENABLE(WEBASSEMBLY)
2803     if (m_ownerExecutable->isWebAssemblyExecutable())
2804         return;
2805 #endif
2806
2807     Interpreter* interpreter = m_vm->interpreter;
2808     const Vector<unsigned>& propertyAccessInstructions = m_unlinkedCode->propertyAccessInstructions();
2809     for (size_t size = propertyAccessInstructions.size(), i = 0; i < size; ++i) {
2810         Instruction* curInstruction = &instructions()[propertyAccessInstructions[i]];
2811         switch (interpreter->getOpcodeID(curInstruction[0].u.opcode)) {
2812         case op_get_by_id:
2813         case op_get_by_id_proto_load:
2814         case op_get_by_id_unset: {
2815             StructureID oldStructureID = curInstruction[4].u.structureID;
2816             if (!oldStructureID || Heap::isMarked(m_vm->heap.structureIDTable().get(oldStructureID)))
2817                 break;
2818             if (Options::verboseOSR())
2819                 dataLogF("Clearing LLInt property access.\n");
2820             clearLLIntGetByIdCache(curInstruction);
2821             break;
2822         }
2823         case op_put_by_id: {
2824             StructureID oldStructureID = curInstruction[4].u.structureID;
2825             StructureID newStructureID = curInstruction[6].u.structureID;
2826             StructureChain* chain = curInstruction[7].u.structureChain.get();
2827             if ((!oldStructureID || Heap::isMarked(m_vm->heap.structureIDTable().get(oldStructureID))) &&
2828                 (!newStructureID || Heap::isMarked(m_vm->heap.structureIDTable().get(newStructureID))) &&
2829                 (!chain || Heap::isMarked(chain)))
2830                 break;
2831             if (Options::verboseOSR())
2832                 dataLogF("Clearing LLInt put transition.\n");
2833             curInstruction[4].u.structureID = 0;
2834             curInstruction[5].u.operand = 0;
2835             curInstruction[6].u.structureID = 0;
2836             curInstruction[7].u.structureChain.clear();
2837             break;
2838         }
2839         case op_get_array_length:
2840             break;
2841         case op_to_this:
2842             if (!curInstruction[2].u.structure || Heap::isMarked(curInstruction[2].u.structure.get()))
2843                 break;
2844             if (Options::verboseOSR())
2845                 dataLogF("Clearing LLInt to_this with structure %p.\n", curInstruction[2].u.structure.get());
2846             curInstruction[2].u.structure.clear();
2847             curInstruction[3].u.toThisStatus = merge(
2848                 curInstruction[3].u.toThisStatus, ToThisClearedByGC);
2849             break;
2850         case op_create_this: {
2851             auto& cacheWriteBarrier = curInstruction[4].u.jsCell;
2852             if (!cacheWriteBarrier || cacheWriteBarrier.unvalidatedGet() == JSCell::seenMultipleCalleeObjects())
2853                 break;
2854             JSCell* cachedFunction = cacheWriteBarrier.get();
2855             if (Heap::isMarked(cachedFunction))
2856                 break;
2857             if (Options::verboseOSR())
2858                 dataLogF("Clearing LLInt create_this with cached callee %p.\n", cachedFunction);
2859             cacheWriteBarrier.clear();
2860             break;
2861         }
2862         case op_resolve_scope: {
2863             // Right now this isn't strictly necessary. Any symbol tables that this will refer to
2864             // are for outer functions, and we refer to those functions strongly, and they refer
2865             // to the symbol table strongly. But it's nice to be on the safe side.
2866             WriteBarrierBase<SymbolTable>& symbolTable = curInstruction[6].u.symbolTable;
2867             if (!symbolTable || Heap::isMarked(symbolTable.get()))
2868                 break;
2869             if (Options::verboseOSR())
2870                 dataLogF("Clearing dead symbolTable %p.\n", symbolTable.get());
2871             symbolTable.clear();
2872             break;
2873         }
2874         case op_get_from_scope:
2875         case op_put_to_scope: {
2876             GetPutInfo getPutInfo = GetPutInfo(curInstruction[4].u.operand);
2877             if (getPutInfo.resolveType() == GlobalVar || getPutInfo.resolveType() == GlobalVarWithVarInjectionChecks 
2878                 || getPutInfo.resolveType() == LocalClosureVar || getPutInfo.resolveType() == GlobalLexicalVar || getPutInfo.resolveType() == GlobalLexicalVarWithVarInjectionChecks)
2879                 continue;
2880             WriteBarrierBase<Structure>& structure = curInstruction[5].u.structure;
2881             if (!structure || Heap::isMarked(structure.get()))
2882                 break;
2883             if (Options::verboseOSR())
2884                 dataLogF("Clearing scope access with structure %p.\n", structure.get());
2885             structure.clear();
2886             break;
2887         }
2888         default:
2889             OpcodeID opcodeID = interpreter->getOpcodeID(curInstruction[0].u.opcode);
2890             ASSERT_WITH_MESSAGE_UNUSED(opcodeID, false, "Unhandled opcode in CodeBlock::finalizeUnconditionally, %s(%d) at bc %u", opcodeNames[opcodeID], opcodeID, propertyAccessInstructions[i]);
2891         }
2892     }
2893
2894     // We can't just remove all the sets when we clear the caches since we might have created a watchpoint set
2895     // then cleared the cache without GCing in between.
2896     m_llintGetByIdWatchpointMap.removeIf([](const StructureWatchpointMap::KeyValuePairType& pair) -> bool {
2897         return !Heap::isMarked(pair.key);
2898     });
2899
2900     for (unsigned i = 0; i < m_llintCallLinkInfos.size(); ++i) {
2901         if (m_llintCallLinkInfos[i].isLinked() && !Heap::isMarked(m_llintCallLinkInfos[i].callee.get())) {
2902             if (Options::verboseOSR())
2903                 dataLog("Clearing LLInt call from ", *this, "\n");
2904             m_llintCallLinkInfos[i].unlink();
2905         }
2906         if (!!m_llintCallLinkInfos[i].lastSeenCallee && !Heap::isMarked(m_llintCallLinkInfos[i].lastSeenCallee.get()))
2907             m_llintCallLinkInfos[i].lastSeenCallee.clear();
2908     }
2909 }
2910
2911 void CodeBlock::finalizeBaselineJITInlineCaches()
2912 {
2913 #if ENABLE(JIT)
2914     for (auto iter = callLinkInfosBegin(); !!iter; ++iter)
2915         (*iter)->visitWeak(*vm());
2916
2917     for (Bag<StructureStubInfo>::iterator iter = m_stubInfos.begin(); !!iter; ++iter) {
2918         StructureStubInfo& stubInfo = **iter;
2919         stubInfo.visitWeakReferences(this);
2920     }
2921 #endif
2922 }
2923
2924 void CodeBlock::UnconditionalFinalizer::finalizeUnconditionally()
2925 {
2926     CodeBlock* codeBlock = bitwise_cast<CodeBlock*>(
2927         bitwise_cast<char*>(this) - OBJECT_OFFSETOF(CodeBlock, m_unconditionalFinalizer));
2928
2929 #if ENABLE(DFG_JIT)
2930     if (codeBlock->shouldJettisonDueToWeakReference()) {
2931         codeBlock->jettison(Profiler::JettisonDueToWeakReference);
2932         return;
2933     }
2934 #endif // ENABLE(DFG_JIT)
2935
2936     if (codeBlock->shouldJettisonDueToOldAge()) {
2937         codeBlock->jettison(Profiler::JettisonDueToOldAge);
2938         return;
2939     }
2940
2941     if (JITCode::couldBeInterpreted(codeBlock->jitType()))
2942         codeBlock->finalizeLLIntInlineCaches();
2943
2944 #if ENABLE(JIT)
2945     if (!!codeBlock->jitCode())
2946         codeBlock->finalizeBaselineJITInlineCaches();
2947 #endif
2948 }
2949
2950 void CodeBlock::getStubInfoMap(const ConcurrentJITLocker&, StubInfoMap& result)
2951 {
2952 #if ENABLE(JIT)
2953     toHashMap(m_stubInfos, getStructureStubInfoCodeOrigin, result);
2954 #else
2955     UNUSED_PARAM(result);
2956 #endif
2957 }
2958
2959 void CodeBlock::getStubInfoMap(StubInfoMap& result)
2960 {
2961     ConcurrentJITLocker locker(m_lock);
2962     getStubInfoMap(locker, result);
2963 }
2964
2965 void CodeBlock::getCallLinkInfoMap(const ConcurrentJITLocker&, CallLinkInfoMap& result)
2966 {
2967 #if ENABLE(JIT)
2968     toHashMap(m_callLinkInfos, getCallLinkInfoCodeOrigin, result);
2969 #else
2970     UNUSED_PARAM(result);
2971 #endif
2972 }
2973
2974 void CodeBlock::getCallLinkInfoMap(CallLinkInfoMap& result)
2975 {
2976     ConcurrentJITLocker locker(m_lock);
2977     getCallLinkInfoMap(locker, result);
2978 }
2979
2980 void CodeBlock::getByValInfoMap(const ConcurrentJITLocker&, ByValInfoMap& result)
2981 {
2982 #if ENABLE(JIT)
2983     for (auto* byValInfo : m_byValInfos)
2984         result.add(CodeOrigin(byValInfo->bytecodeIndex), byValInfo);
2985 #else
2986     UNUSED_PARAM(result);
2987 #endif
2988 }
2989
2990 void CodeBlock::getByValInfoMap(ByValInfoMap& result)
2991 {
2992     ConcurrentJITLocker locker(m_lock);
2993     getByValInfoMap(locker, result);
2994 }
2995
2996 #if ENABLE(JIT)
2997 StructureStubInfo* CodeBlock::addStubInfo(AccessType accessType)
2998 {
2999     ConcurrentJITLocker locker(m_lock);
3000     return m_stubInfos.add(accessType);
3001 }
3002
3003 StructureStubInfo* CodeBlock::findStubInfo(CodeOrigin codeOrigin)
3004 {
3005     for (StructureStubInfo* stubInfo : m_stubInfos) {
3006         if (stubInfo->codeOrigin == codeOrigin)
3007             return stubInfo;
3008     }
3009     return nullptr;
3010 }
3011
3012 ByValInfo* CodeBlock::addByValInfo()
3013 {
3014     ConcurrentJITLocker locker(m_lock);
3015     return m_byValInfos.add();
3016 }
3017
3018 CallLinkInfo* CodeBlock::addCallLinkInfo()
3019 {
3020     ConcurrentJITLocker locker(m_lock);
3021     return m_callLinkInfos.add();
3022 }
3023
3024 CallLinkInfo* CodeBlock::getCallLinkInfoForBytecodeIndex(unsigned index)
3025 {
3026     for (auto iter = m_callLinkInfos.begin(); !!iter; ++iter) {
3027         if ((*iter)->codeOrigin() == CodeOrigin(index))
3028             return *iter;
3029     }
3030     return nullptr;
3031 }
3032 #endif
3033
3034 void CodeBlock::visitOSRExitTargets(SlotVisitor& visitor)
3035 {
3036     // We strongly visit OSR exits targets because we don't want to deal with
3037     // the complexity of generating an exit target CodeBlock on demand and
3038     // guaranteeing that it matches the details of the CodeBlock we compiled
3039     // the OSR exit against.
3040
3041     visitor.append(&m_alternative);
3042
3043 #if ENABLE(DFG_JIT)
3044     DFG::CommonData* dfgCommon = m_jitCode->dfgCommon();
3045     if (dfgCommon->inlineCallFrames) {
3046         for (auto* inlineCallFrame : *dfgCommon->inlineCallFrames) {
3047             ASSERT(inlineCallFrame->baselineCodeBlock);
3048             visitor.append(&inlineCallFrame->baselineCodeBlock);
3049         }
3050     }
3051 #endif
3052 }
3053
3054 void CodeBlock::stronglyVisitStrongReferences(SlotVisitor& visitor)
3055 {
3056     visitor.append(&m_globalObject);
3057     visitor.append(&m_ownerExecutable);
3058     visitor.append(&m_unlinkedCode);
3059     if (m_rareData)
3060         m_rareData->m_evalCodeCache.visitAggregate(visitor);
3061     visitor.appendValues(m_constantRegisters.data(), m_constantRegisters.size());
3062     for (size_t i = 0; i < m_functionExprs.size(); ++i)
3063         visitor.append(&m_functionExprs[i]);
3064     for (size_t i = 0; i < m_functionDecls.size(); ++i)
3065         visitor.append(&m_functionDecls[i]);
3066     for (unsigned i = 0; i < m_objectAllocationProfiles.size(); ++i)
3067         m_objectAllocationProfiles[i].visitAggregate(visitor);
3068
3069 #if ENABLE(DFG_JIT)
3070     if (JITCode::isOptimizingJIT(jitType()))
3071         visitOSRExitTargets(visitor);
3072 #endif
3073
3074     updateAllPredictions();
3075 }
3076
3077 void CodeBlock::stronglyVisitWeakReferences(SlotVisitor& visitor)
3078 {
3079     UNUSED_PARAM(visitor);
3080
3081 #if ENABLE(DFG_JIT)
3082     if (!JITCode::isOptimizingJIT(jitType()))
3083         return;
3084     
3085     DFG::CommonData* dfgCommon = m_jitCode->dfgCommon();
3086
3087     for (unsigned i = 0; i < dfgCommon->transitions.size(); ++i) {
3088         if (!!dfgCommon->transitions[i].m_codeOrigin)
3089             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.
3090         visitor.append(&dfgCommon->transitions[i].m_from);
3091         visitor.append(&dfgCommon->transitions[i].m_to);
3092     }
3093     
3094     for (unsigned i = 0; i < dfgCommon->weakReferences.size(); ++i)
3095         visitor.append(&dfgCommon->weakReferences[i]);
3096
3097     for (unsigned i = 0; i < dfgCommon->weakStructureReferences.size(); ++i)
3098         visitor.append(&dfgCommon->weakStructureReferences[i]);
3099
3100     dfgCommon->livenessHasBeenProved = true;
3101 #endif    
3102 }
3103
3104 CodeBlock* CodeBlock::baselineAlternative()
3105 {
3106 #if ENABLE(JIT)
3107     CodeBlock* result = this;
3108     while (result->alternative())
3109         result = result->alternative();
3110     RELEASE_ASSERT(result);
3111     RELEASE_ASSERT(JITCode::isBaselineCode(result->jitType()) || result->jitType() == JITCode::None);
3112     return result;
3113 #else
3114     return this;
3115 #endif
3116 }
3117
3118 CodeBlock* CodeBlock::baselineVersion()
3119 {
3120 #if ENABLE(JIT)
3121     if (JITCode::isBaselineCode(jitType()))
3122         return this;
3123     CodeBlock* result = replacement();
3124     if (!result) {
3125         // This can happen if we're creating the original CodeBlock for an executable.
3126         // Assume that we're the baseline CodeBlock.
3127         RELEASE_ASSERT(jitType() == JITCode::None);
3128         return this;
3129     }
3130     result = result->baselineAlternative();
3131     return result;
3132 #else
3133     return this;
3134 #endif
3135 }
3136
3137 #if ENABLE(JIT)
3138 bool CodeBlock::hasOptimizedReplacement(JITCode::JITType typeToReplace)
3139 {
3140     return JITCode::isHigherTier(replacement()->jitType(), typeToReplace);
3141 }
3142
3143 bool CodeBlock::hasOptimizedReplacement()
3144 {
3145     return hasOptimizedReplacement(jitType());
3146 }
3147 #endif
3148
3149 HandlerInfo* CodeBlock::handlerForBytecodeOffset(unsigned bytecodeOffset, RequiredHandler requiredHandler)
3150 {
3151     RELEASE_ASSERT(bytecodeOffset < instructions().size());
3152     return handlerForIndex(bytecodeOffset, requiredHandler);
3153 }
3154
3155 HandlerInfo* CodeBlock::handlerForIndex(unsigned index, RequiredHandler requiredHandler)
3156 {
3157     if (!m_rareData)
3158         return 0;
3159     
3160     Vector<HandlerInfo>& exceptionHandlers = m_rareData->m_exceptionHandlers;
3161     for (size_t i = 0; i < exceptionHandlers.size(); ++i) {
3162         HandlerInfo& handler = exceptionHandlers[i];
3163         if ((requiredHandler == RequiredHandler::CatchHandler) && !handler.isCatchHandler())
3164             continue;
3165
3166         // Handlers are ordered innermost first, so the first handler we encounter
3167         // that contains the source address is the correct handler to use.
3168         // This index used is either the BytecodeOffset or a CallSiteIndex.
3169         if (handler.start <= index && handler.end > index)
3170             return &handler;
3171     }
3172
3173     return 0;
3174 }
3175
3176 CallSiteIndex CodeBlock::newExceptionHandlingCallSiteIndex(CallSiteIndex originalCallSite)
3177 {
3178 #if ENABLE(DFG_JIT)
3179     RELEASE_ASSERT(JITCode::isOptimizingJIT(jitType()));
3180     RELEASE_ASSERT(canGetCodeOrigin(originalCallSite));
3181     ASSERT(!!handlerForIndex(originalCallSite.bits()));
3182     CodeOrigin originalOrigin = codeOrigin(originalCallSite);
3183     return m_jitCode->dfgCommon()->addUniqueCallSiteIndex(originalOrigin);
3184 #else
3185     // We never create new on-the-fly exception handling
3186     // call sites outside the DFG/FTL inline caches.
3187     UNUSED_PARAM(originalCallSite);
3188     RELEASE_ASSERT_NOT_REACHED();
3189     return CallSiteIndex(0u);
3190 #endif
3191 }
3192
3193 void CodeBlock::removeExceptionHandlerForCallSite(CallSiteIndex callSiteIndex)
3194 {
3195     RELEASE_ASSERT(m_rareData);
3196     Vector<HandlerInfo>& exceptionHandlers = m_rareData->m_exceptionHandlers;
3197     unsigned index = callSiteIndex.bits();
3198     for (size_t i = 0; i < exceptionHandlers.size(); ++i) {
3199         HandlerInfo& handler = exceptionHandlers[i];
3200         if (handler.start <= index && handler.end > index) {
3201             exceptionHandlers.remove(i);
3202             return;
3203         }
3204     }
3205
3206     RELEASE_ASSERT_NOT_REACHED();
3207 }
3208
3209 unsigned CodeBlock::lineNumberForBytecodeOffset(unsigned bytecodeOffset)
3210 {
3211     RELEASE_ASSERT(bytecodeOffset < instructions().size());
3212     return ownerScriptExecutable()->firstLine() + m_unlinkedCode->lineNumberForBytecodeOffset(bytecodeOffset);
3213 }
3214
3215 unsigned CodeBlock::columnNumberForBytecodeOffset(unsigned bytecodeOffset)
3216 {
3217     int divot;
3218     int startOffset;
3219     int endOffset;
3220     unsigned line;
3221     unsigned column;
3222     expressionRangeForBytecodeOffset(bytecodeOffset, divot, startOffset, endOffset, line, column);
3223     return column;
3224 }
3225
3226 void CodeBlock::expressionRangeForBytecodeOffset(unsigned bytecodeOffset, int& divot, int& startOffset, int& endOffset, unsigned& line, unsigned& column)
3227 {
3228     m_unlinkedCode->expressionRangeForBytecodeOffset(bytecodeOffset, divot, startOffset, endOffset, line, column);
3229     divot += m_sourceOffset;
3230     column += line ? 1 : firstLineColumnOffset();
3231     line += ownerScriptExecutable()->firstLine();
3232 }
3233
3234 bool CodeBlock::hasOpDebugForLineAndColumn(unsigned line, unsigned column)
3235 {
3236     Interpreter* interpreter = vm()->interpreter;
3237     const Instruction* begin = instructions().begin();
3238     const Instruction* end = instructions().end();
3239     for (const Instruction* it = begin; it != end;) {
3240         OpcodeID opcodeID = interpreter->getOpcodeID(it->u.opcode);
3241         if (opcodeID == op_debug) {
3242             unsigned bytecodeOffset = it - begin;
3243             int unused;
3244             unsigned opDebugLine;
3245             unsigned opDebugColumn;
3246             expressionRangeForBytecodeOffset(bytecodeOffset, unused, unused, unused, opDebugLine, opDebugColumn);
3247             if (line == opDebugLine && (column == Breakpoint::unspecifiedColumn || column == opDebugColumn))
3248                 return true;
3249         }
3250         it += opcodeLengths[opcodeID];
3251     }
3252     return false;
3253 }
3254
3255 void CodeBlock::shrinkToFit(ShrinkMode shrinkMode)
3256 {
3257     m_rareCaseProfiles.shrinkToFit();
3258     m_resultProfiles.shrinkToFit();
3259     
3260     if (shrinkMode == EarlyShrink) {
3261         m_constantRegisters.shrinkToFit();
3262         m_constantsSourceCodeRepresentation.shrinkToFit();
3263         
3264         if (m_rareData) {
3265             m_rareData->m_switchJumpTables.shrinkToFit();
3266             m_rareData->m_stringSwitchJumpTables.shrinkToFit();
3267             m_rareData->m_liveCalleeLocalsAtYield.shrinkToFit();
3268         }
3269     } // else don't shrink these, because we would have already pointed pointers into these tables.
3270 }
3271
3272 #if ENABLE(JIT)
3273 void CodeBlock::linkIncomingCall(ExecState* callerFrame, CallLinkInfo* incoming)
3274 {
3275     noticeIncomingCall(callerFrame);
3276     m_incomingCalls.push(incoming);
3277 }
3278
3279 void CodeBlock::linkIncomingPolymorphicCall(ExecState* callerFrame, PolymorphicCallNode* incoming)
3280 {
3281     noticeIncomingCall(callerFrame);
3282     m_incomingPolymorphicCalls.push(incoming);
3283 }
3284 #endif // ENABLE(JIT)
3285
3286 void CodeBlock::unlinkIncomingCalls()
3287 {
3288     while (m_incomingLLIntCalls.begin() != m_incomingLLIntCalls.end())
3289         m_incomingLLIntCalls.begin()->unlink();
3290 #if ENABLE(JIT)
3291     while (m_incomingCalls.begin() != m_incomingCalls.end())
3292         m_incomingCalls.begin()->unlink(*vm());
3293     while (m_incomingPolymorphicCalls.begin() != m_incomingPolymorphicCalls.end())
3294         m_incomingPolymorphicCalls.begin()->unlink(*vm());
3295 #endif // ENABLE(JIT)
3296 }
3297
3298 void CodeBlock::linkIncomingCall(ExecState* callerFrame, LLIntCallLinkInfo* incoming)
3299 {
3300     noticeIncomingCall(callerFrame);
3301     m_incomingLLIntCalls.push(incoming);
3302 }
3303
3304 CodeBlock* CodeBlock::newReplacement()
3305 {
3306     return ownerScriptExecutable()->newReplacementCodeBlockFor(specializationKind());
3307 }
3308
3309 #if ENABLE(JIT)
3310 CodeBlock* CodeBlock::replacement()
3311 {
3312     const ClassInfo* classInfo = this->classInfo();
3313
3314     if (classInfo == FunctionCodeBlock::info())
3315         return jsCast<FunctionExecutable*>(ownerExecutable())->codeBlockFor(m_isConstructor ? CodeForConstruct : CodeForCall);
3316
3317     if (classInfo == EvalCodeBlock::info())
3318         return jsCast<EvalExecutable*>(ownerExecutable())->codeBlock();
3319
3320     if (classInfo == ProgramCodeBlock::info())
3321         return jsCast<ProgramExecutable*>(ownerExecutable())->codeBlock();
3322
3323     if (classInfo == ModuleProgramCodeBlock::info())
3324         return jsCast<ModuleProgramExecutable*>(ownerExecutable())->codeBlock();
3325
3326 #if ENABLE(WEBASSEMBLY)
3327     if (classInfo == WebAssemblyCodeBlock::info())
3328         return nullptr;
3329 #endif
3330
3331     RELEASE_ASSERT_NOT_REACHED();
3332     return nullptr;
3333 }
3334
3335 DFG::CapabilityLevel CodeBlock::computeCapabilityLevel()
3336 {
3337     const ClassInfo* classInfo = this->classInfo();
3338
3339     if (classInfo == FunctionCodeBlock::info()) {
3340         if (m_isConstructor)
3341             return DFG::functionForConstructCapabilityLevel(this);
3342         return DFG::functionForCallCapabilityLevel(this);
3343     }
3344
3345     if (classInfo == EvalCodeBlock::info())
3346         return DFG::evalCapabilityLevel(this);
3347
3348     if (classInfo == ProgramCodeBlock::info())
3349         return DFG::programCapabilityLevel(this);
3350
3351     if (classInfo == ModuleProgramCodeBlock::info())
3352         return DFG::programCapabilityLevel(this);
3353
3354 #if ENABLE(WEBASSEMBLY)
3355     if (classInfo == WebAssemblyCodeBlock::info())
3356         return DFG::CannotCompile;
3357 #endif
3358
3359     RELEASE_ASSERT_NOT_REACHED();
3360     return DFG::CannotCompile;
3361 }
3362
3363 #endif // ENABLE(JIT)
3364
3365 void CodeBlock::jettison(Profiler::JettisonReason reason, ReoptimizationMode mode, const FireDetail* detail)
3366 {
3367 #if !ENABLE(DFG_JIT)
3368     UNUSED_PARAM(mode);
3369     UNUSED_PARAM(detail);
3370 #endif
3371     
3372     CODEBLOCK_LOG_EVENT(this, "jettison", ("due to ", reason, ", counting = ", mode == CountReoptimization, ", detail = ", pointerDump(detail)));
3373
3374     RELEASE_ASSERT(reason != Profiler::NotJettisoned);
3375     
3376 #if ENABLE(DFG_JIT)
3377     if (DFG::shouldDumpDisassembly()) {
3378         dataLog("Jettisoning ", *this);
3379         if (mode == CountReoptimization)
3380             dataLog(" and counting reoptimization");
3381         dataLog(" due to ", reason);
3382         if (detail)
3383             dataLog(", ", *detail);
3384         dataLog(".\n");
3385     }
3386     
3387     if (reason == Profiler::JettisonDueToWeakReference) {
3388         if (DFG::shouldDumpDisassembly()) {
3389             dataLog(*this, " will be jettisoned because of the following dead references:\n");
3390             DFG::CommonData* dfgCommon = m_jitCode->dfgCommon();
3391             for (unsigned i = 0; i < dfgCommon->transitions.size(); ++i) {
3392                 DFG::WeakReferenceTransition& transition = dfgCommon->transitions[i];
3393                 JSCell* origin = transition.m_codeOrigin.get();
3394                 JSCell* from = transition.m_from.get();
3395                 JSCell* to = transition.m_to.get();
3396                 if ((!origin || Heap::isMarked(origin)) && Heap::isMarked(from))
3397                     continue;
3398                 dataLog("    Transition under ", RawPointer(origin), ", ", RawPointer(from), " -> ", RawPointer(to), ".\n");
3399             }
3400             for (unsigned i = 0; i < dfgCommon->weakReferences.size(); ++i) {
3401                 JSCell* weak = dfgCommon->weakReferences[i].get();
3402                 if (Heap::isMarked(weak))
3403                     continue;
3404                 dataLog("    Weak reference ", RawPointer(weak), ".\n");
3405             }
3406         }
3407     }
3408 #endif // ENABLE(DFG_JIT)
3409
3410     DeferGCForAWhile deferGC(*heap());
3411     
3412     // We want to accomplish two things here:
3413     // 1) Make sure that if this CodeBlock is on the stack right now, then if we return to it
3414     //    we should OSR exit at the top of the next bytecode instruction after the return.
3415     // 2) Make sure that if we call the owner executable, then we shouldn't call this CodeBlock.
3416
3417 #if ENABLE(DFG_JIT)
3418     if (reason != Profiler::JettisonDueToOldAge) {
3419         if (Profiler::Compilation* compilation = jitCode()->dfgCommon()->compilation.get())
3420             compilation->setJettisonReason(reason, detail);
3421         
3422         // This accomplishes (1), and does its own book-keeping about whether it has already happened.
3423         if (!jitCode()->dfgCommon()->invalidate()) {
3424             // We've already been invalidated.
3425             RELEASE_ASSERT(this != replacement());
3426             return;
3427         }
3428     }
3429     
3430     if (DFG::shouldDumpDisassembly())
3431         dataLog("    Did invalidate ", *this, "\n");
3432     
3433     // Count the reoptimization if that's what the user wanted.
3434     if (mode == CountReoptimization) {
3435         // FIXME: Maybe this should call alternative().
3436         // https://bugs.webkit.org/show_bug.cgi?id=123677
3437         baselineAlternative()->countReoptimization();
3438         if (DFG::shouldDumpDisassembly())
3439             dataLog("    Did count reoptimization for ", *this, "\n");
3440     }
3441     
3442     if (this != replacement()) {
3443         // This means that we were never the entrypoint. This can happen for OSR entry code
3444         // blocks.
3445         return;
3446     }
3447
3448     if (alternative())
3449         alternative()->optimizeAfterWarmUp();
3450
3451     if (reason != Profiler::JettisonDueToOldAge)
3452         tallyFrequentExitSites();
3453 #endif // ENABLE(DFG_JIT)
3454
3455     // This accomplishes (2).
3456     ownerScriptExecutable()->installCode(
3457         m_globalObject->vm(), alternative(), codeType(), specializationKind());
3458
3459 #if ENABLE(DFG_JIT)
3460     if (DFG::shouldDumpDisassembly())
3461         dataLog("    Did install baseline version of ", *this, "\n");
3462 #endif // ENABLE(DFG_JIT)
3463 }
3464
3465 JSGlobalObject* CodeBlock::globalObjectFor(CodeOrigin codeOrigin)
3466 {
3467     if (!codeOrigin.inlineCallFrame)
3468         return globalObject();
3469     return codeOrigin.inlineCallFrame->baselineCodeBlock->globalObject();
3470 }
3471
3472 class RecursionCheckFunctor {
3473 public:
3474     RecursionCheckFunctor(CallFrame* startCallFrame, CodeBlock* codeBlock, unsigned depthToCheck)
3475         : m_startCallFrame(startCallFrame)
3476         , m_codeBlock(codeBlock)
3477         , m_depthToCheck(depthToCheck)
3478         , m_foundStartCallFrame(false)
3479         , m_didRecurse(false)
3480     { }
3481
3482     StackVisitor::Status operator()(StackVisitor& visitor) const
3483     {
3484         CallFrame* currentCallFrame = visitor->callFrame();
3485
3486         if (currentCallFrame == m_startCallFrame)
3487             m_foundStartCallFrame = true;
3488
3489         if (m_foundStartCallFrame) {
3490             if (visitor->callFrame()->codeBlock() == m_codeBlock) {
3491                 m_didRecurse = true;
3492                 return StackVisitor::Done;
3493             }
3494
3495             if (!m_depthToCheck--)
3496                 return StackVisitor::Done;
3497         }
3498
3499         return StackVisitor::Continue;
3500     }
3501
3502     bool didRecurse() const { return m_didRecurse; }
3503
3504 private:
3505     CallFrame* m_startCallFrame;
3506     CodeBlock* m_codeBlock;
3507     mutable unsigned m_depthToCheck;
3508     mutable bool m_foundStartCallFrame;
3509     mutable bool m_didRecurse;
3510 };
3511
3512 void CodeBlock::noticeIncomingCall(ExecState* callerFrame)
3513 {
3514     CodeBlock* callerCodeBlock = callerFrame->codeBlock();
3515     
3516     if (Options::verboseCallLink())
3517         dataLog("Noticing call link from ", pointerDump(callerCodeBlock), " to ", *this, "\n");
3518     
3519 #if ENABLE(DFG_JIT)
3520     if (!m_shouldAlwaysBeInlined)
3521         return;
3522     
3523     if (!callerCodeBlock) {
3524         m_shouldAlwaysBeInlined = false;
3525         if (Options::verboseCallLink())
3526             dataLog("    Clearing SABI because caller is native.\n");
3527         return;
3528     }
3529
3530     if (!hasBaselineJITProfiling())
3531         return;
3532
3533     if (!DFG::mightInlineFunction(this))
3534         return;
3535
3536     if (!canInline(capabilityLevelState()))
3537         return;
3538     
3539     if (!DFG::isSmallEnoughToInlineCodeInto(callerCodeBlock)) {
3540         m_shouldAlwaysBeInlined = false;
3541         if (Options::verboseCallLink())
3542             dataLog("    Clearing SABI because caller is too large.\n");
3543         return;
3544     }
3545
3546     if (callerCodeBlock->jitType() == JITCode::InterpreterThunk) {
3547         // If the caller is still in the interpreter, then we can't expect inlining to
3548         // happen anytime soon. Assume it's profitable to optimize it separately. This
3549         // ensures that a function is SABI only if it is called no more frequently than
3550         // any of its callers.
3551         m_shouldAlwaysBeInlined = false;
3552         if (Options::verboseCallLink())
3553             dataLog("    Clearing SABI because caller is in LLInt.\n");
3554         return;
3555     }
3556     
3557     if (JITCode::isOptimizingJIT(callerCodeBlock->jitType())) {
3558         m_shouldAlwaysBeInlined = false;
3559         if (Options::verboseCallLink())
3560             dataLog("    Clearing SABI bcause caller was already optimized.\n");
3561         return;
3562     }
3563     
3564     if (callerCodeBlock->codeType() != FunctionCode) {
3565         // If the caller is either eval or global code, assume that that won't be
3566         // optimized anytime soon. For eval code this is particularly true since we
3567         // delay eval optimization by a *lot*.
3568         m_shouldAlwaysBeInlined = false;
3569         if (Options::verboseCallLink())
3570             dataLog("    Clearing SABI because caller is not a function.\n");
3571         return;
3572     }
3573
3574     // Recursive calls won't be inlined.
3575     RecursionCheckFunctor functor(callerFrame, this, Options::maximumInliningDepth());
3576     vm()->topCallFrame->iterate(functor);
3577
3578     if (functor.didRecurse()) {
3579         if (Options::verboseCallLink())
3580             dataLog("    Clearing SABI because recursion was detected.\n");
3581         m_shouldAlwaysBeInlined = false;
3582         return;
3583     }
3584     
3585     if (callerCodeBlock->capabilityLevelState() == DFG::CapabilityLevelNotSet) {
3586         dataLog("In call from ", *callerCodeBlock, " ", callerFrame->codeOrigin(), " to ", *this, ": caller's DFG capability level is not set.\n");
3587         CRASH();
3588     }
3589     
3590     if (canCompile(callerCodeBlock->capabilityLevelState()))
3591         return;
3592     
3593     if (Options::verboseCallLink())
3594         dataLog("    Clearing SABI because the caller is not a DFG candidate.\n");
3595     
3596     m_shouldAlwaysBeInlined = false;
3597 #endif
3598 }
3599
3600 unsigned CodeBlock::reoptimizationRetryCounter() const
3601 {
3602 #if ENABLE(JIT)
3603     ASSERT(m_reoptimizationRetryCounter <= Options::reoptimizationRetryCounterMax());
3604     return m_reoptimizationRetryCounter;
3605 #else
3606     return 0;
3607 #endif // ENABLE(JIT)
3608 }
3609
3610 #if ENABLE(JIT)
3611 void CodeBlock::setCalleeSaveRegisters(RegisterSet calleeSaveRegisters)
3612 {
3613     m_calleeSaveRegisters = std::make_unique<RegisterAtOffsetList>(calleeSaveRegisters);
3614 }
3615
3616 void CodeBlock::setCalleeSaveRegisters(std::unique_ptr<RegisterAtOffsetList> registerAtOffsetList)
3617 {
3618     m_calleeSaveRegisters = WTFMove(registerAtOffsetList);
3619 }
3620     
3621 static size_t roundCalleeSaveSpaceAsVirtualRegisters(size_t calleeSaveRegisters)
3622 {
3623     static const unsigned cpuRegisterSize = sizeof(void*);
3624     return (WTF::roundUpToMultipleOf(sizeof(Register), calleeSaveRegisters * cpuRegisterSize) / sizeof(Register));
3625
3626 }
3627
3628 size_t CodeBlock::llintBaselineCalleeSaveSpaceAsVirtualRegisters()
3629 {
3630     return roundCalleeSaveSpaceAsVirtualRegisters(numberOfLLIntBaselineCalleeSaveRegisters());
3631 }
3632
3633 size_t CodeBlock::calleeSaveSpaceAsVirtualRegisters()
3634 {
3635     return roundCalleeSaveSpaceAsVirtualRegisters(m_calleeSaveRegisters->size());
3636 }
3637
3638 void CodeBlock::countReoptimization()
3639 {
3640     m_reoptimizationRetryCounter++;
3641     if (m_reoptimizationRetryCounter > Options::reoptimizationRetryCounterMax())
3642         m_reoptimizationRetryCounter = Options::reoptimizationRetryCounterMax();
3643 }
3644
3645 unsigned CodeBlock::numberOfDFGCompiles()
3646 {
3647     ASSERT(JITCode::isBaselineCode(jitType()));
3648     if (Options::testTheFTL()) {
3649         if (m_didFailFTLCompilation)
3650             return 1000000;
3651         return (m_hasBeenCompiledWithFTL ? 1 : 0) + m_reoptimizationRetryCounter;
3652     }
3653     return (JITCode::isOptimizingJIT(replacement()->jitType()) ? 1 : 0) + m_reoptimizationRetryCounter;
3654 }
3655
3656 int32_t CodeBlock::codeTypeThresholdMultiplier() const
3657 {
3658     if (codeType() == EvalCode)
3659         return Options::evalThresholdMultiplier();
3660     
3661     return 1;
3662 }
3663
3664 double CodeBlock::optimizationThresholdScalingFactor()
3665 {
3666     // This expression arises from doing a least-squares fit of
3667     //
3668     // F[x_] =: a * Sqrt[x + b] + Abs[c * x] + d
3669     //
3670     // against the data points:
3671     //
3672     //    x       F[x_]
3673     //    10       0.9          (smallest reasonable code block)
3674     //   200       1.0          (typical small-ish code block)
3675     //   320       1.2          (something I saw in 3d-cube that I wanted to optimize)
3676     //  1268       5.0          (something I saw in 3d-cube that I didn't want to optimize)
3677     //  4000       5.5          (random large size, used to cause the function to converge to a shallow curve of some sort)
3678     // 10000       6.0          (similar to above)
3679     //
3680     // I achieve the minimization using the following Mathematica code:
3681     //
3682     // MyFunctionTemplate[x_, a_, b_, c_, d_] := a*Sqrt[x + b] + Abs[c*x] + d
3683     //
3684     // samples = {{10, 0.9}, {200, 1}, {320, 1.2}, {1268, 5}, {4000, 5.5}, {10000, 6}}
3685     //
3686     // solution = 
3687     //     Minimize[Plus @@ ((MyFunctionTemplate[#[[1]], a, b, c, d] - #[[2]])^2 & /@ samples),
3688     //         {a, b, c, d}][[2]]
3689     //
3690     // And the code below (to initialize a, b, c, d) is generated by:
3691     //
3692     // Print["const double " <> ToString[#[[1]]] <> " = " <>
3693     //     If[#[[2]] < 0.00001, "0.0", ToString[#[[2]]]] <> ";"] & /@ solution
3694     //
3695     // We've long known the following to be true:
3696     // - Small code blocks are cheap to optimize and so we should do it sooner rather
3697     //   than later.
3698     // - Large code blocks are expensive to optimize and so we should postpone doing so,
3699     //   and sometimes have a large enough threshold that we never optimize them.
3700     // - The difference in cost is not totally linear because (a) just invoking the
3701     //   DFG incurs some base cost and (b) for large code blocks there is enough slop
3702     //   in the correlation between instruction count and the actual compilation cost
3703     //   that for those large blocks, the instruction count should not have a strong
3704     //   influence on our threshold.
3705     //
3706     // I knew the goals but I didn't know how to achieve them; so I picked an interesting
3707     // example where the heuristics were right (code block in 3d-cube with instruction
3708     // count 320, which got compiled early as it should have been) and one where they were
3709     // totally wrong (code block in 3d-cube with instruction count 1268, which was expensive
3710     // to compile and didn't run often enough to warrant compilation in my opinion), and
3711     // then threw in additional data points that represented my own guess of what our
3712     // heuristics should do for some round-numbered examples.
3713     //
3714     // The expression to which I decided to fit the data arose because I started with an
3715     // affine function, and then did two things: put the linear part in an Abs to ensure
3716     // that the fit didn't end up choosing a negative value of c (which would result in
3717     // the function turning over and going negative for large x) and I threw in a Sqrt
3718     // term because Sqrt represents my intution that the function should be more sensitive
3719     // to small changes in small values of x, but less sensitive when x gets large.
3720     
3721     // Note that the current fit essentially eliminates the linear portion of the
3722     // expression (c == 0.0).
3723     const double a = 0.061504;
3724     const double b = 1.02406;
3725     const double c = 0.0;
3726     const double d = 0.825914;
3727     
3728     double instructionCount = this->instructionCount();
3729     
3730     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.
3731     
3732     double result = d + a * sqrt(instructionCount + b) + c * instructionCount;
3733     
3734     result *= codeTypeThresholdMultiplier();
3735     
3736     if (Options::verboseOSR()) {
3737         dataLog(
3738             *this, ": instruction count is ", instructionCount,
3739             ", scaling execution counter by ", result, " * ", codeTypeThresholdMultiplier(),
3740             "\n");
3741     }
3742     return result;
3743 }
3744
3745 static int32_t clipThreshold(double threshold)
3746 {
3747     if (threshold < 1.0)
3748         return 1;
3749     
3750     if (threshold > static_cast<double>(std::numeric_limits<int32_t>::max()))
3751         return std::numeric_limits<int32_t>::max();
3752     
3753     return static_cast<int32_t>(threshold);
3754 }
3755
3756 int32_t CodeBlock::adjustedCounterValue(int32_t desiredThreshold)
3757 {
3758     return clipThreshold(
3759         static_cast<double>(desiredThreshold) *
3760         optimizationThresholdScalingFactor() *
3761         (1 << reoptimizationRetryCounter()));
3762 }
3763
3764 bool CodeBlock::checkIfOptimizationThresholdReached()
3765 {
3766 #if ENABLE(DFG_JIT)
3767     if (DFG::Worklist* worklist = DFG::existingGlobalDFGWorklistOrNull()) {
3768         if (worklist->compilationState(DFG::CompilationKey(this, DFG::DFGMode))
3769             == DFG::Worklist::Compiled) {
3770             optimizeNextInvocation();
3771             return true;
3772         }
3773     }
3774 #endif
3775     
3776     return m_jitExecuteCounter.checkIfThresholdCrossedAndSet(this);
3777 }
3778
3779 void CodeBlock::optimizeNextInvocation()
3780 {
3781     if (Options::verboseOSR())
3782         dataLog(*this, ": Optimizing next invocation.\n");
3783     m_jitExecuteCounter.setNewThreshold(0, this);
3784 }
3785
3786 void CodeBlock::dontOptimizeAnytimeSoon()
3787 {
3788     if (Options::verboseOSR())
3789         dataLog(*this, ": Not optimizing anytime soon.\n");
3790     m_jitExecuteCounter.deferIndefinitely();
3791 }
3792
3793 void CodeBlock::optimizeAfterWarmUp()
3794 {
3795     if (Options::verboseOSR())
3796         dataLog(*this, ": Optimizing after warm-up.\n");
3797 #if ENABLE(DFG_JIT)
3798     m_jitExecuteCounter.setNewThreshold(
3799         adjustedCounterValue(Options::thresholdForOptimizeAfterWarmUp()), this);
3800 #endif
3801 }
3802
3803 void CodeBlock::optimizeAfterLongWarmUp()
3804 {
3805     if (Options::verboseOSR())
3806         dataLog(*this, ": Optimizing after long warm-up.\n");
3807 #if ENABLE(DFG_JIT)
3808     m_jitExecuteCounter.setNewThreshold(
3809         adjustedCounterValue(Options::thresholdForOptimizeAfterLongWarmUp()), this);
3810 #endif
3811 }
3812
3813 void CodeBlock::optimizeSoon()
3814 {
3815     if (Options::verboseOSR())
3816         dataLog(*this, ": Optimizing soon.\n");
3817 #if ENABLE(DFG_JIT)
3818     m_jitExecuteCounter.setNewThreshold(
3819         adjustedCounterValue(Options::thresholdForOptimizeSoon()), this);
3820 #endif
3821 }
3822
3823 void CodeBlock::forceOptimizationSlowPathConcurrently()
3824 {
3825     if (Options::verboseOSR())
3826         dataLog(*this, ": Forcing slow path concurrently.\n");
3827     m_jitExecuteCounter.forceSlowPathConcurrently();
3828 }
3829
3830 #if ENABLE(DFG_JIT)
3831 void CodeBlock::setOptimizationThresholdBasedOnCompilationResult(CompilationResult result)
3832 {
3833     JITCode::JITType type = jitType();
3834     if (type != JITCode::BaselineJIT) {
3835         dataLog(*this, ": expected to have baseline code but have ", type, "\n");
3836         RELEASE_ASSERT_NOT_REACHED();
3837     }