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