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