1fb3e143e951773dc615354c9e6fc2aa5fa83fee
[WebKit-https.git] / Source / JavaScriptCore / bytecode / CodeBlock.cpp
1 /*
2  * Copyright (C) 2008-2017 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 "ArithProfile.h"
34 #include "BasicBlockLocation.h"
35 #include "BytecodeDumper.h"
36 #include "BytecodeGenerator.h"
37 #include "BytecodeLivenessAnalysis.h"
38 #include "BytecodeUseDef.h"
39 #include "CallLinkStatus.h"
40 #include "CodeBlockSet.h"
41 #include "DFGCapabilities.h"
42 #include "DFGCommon.h"
43 #include "DFGDriver.h"
44 #include "DFGJITCode.h"
45 #include "DFGWorklist.h"
46 #include "Debugger.h"
47 #include "EvalCodeBlock.h"
48 #include "FullCodeOrigin.h"
49 #include "FunctionCodeBlock.h"
50 #include "FunctionExecutableDump.h"
51 #include "GetPutInfo.h"
52 #include "InlineCallFrame.h"
53 #include "InterpreterInlines.h"
54 #include "JIT.h"
55 #include "JITMathIC.h"
56 #include "JSCInlines.h"
57 #include "JSCJSValue.h"
58 #include "JSFunction.h"
59 #include "JSLexicalEnvironment.h"
60 #include "JSModuleEnvironment.h"
61 #include "JSSet.h"
62 #include "JSString.h"
63 #include "JSTemplateRegistryKey.h"
64 #include "LLIntData.h"
65 #include "LLIntEntrypoint.h"
66 #include "LLIntPrototypeLoadAdaptiveStructureWatchpoint.h"
67 #include "LowLevelInterpreter.h"
68 #include "ModuleProgramCodeBlock.h"
69 #include "ObjectAllocationProfileInlines.h"
70 #include "PCToCodeOriginMap.h"
71 #include "PolymorphicAccess.h"
72 #include "ProfilerDatabase.h"
73 #include "ProgramCodeBlock.h"
74 #include "ReduceWhitespace.h"
75 #include "Repatch.h"
76 #include "SlotVisitorInlines.h"
77 #include "StackVisitor.h"
78 #include "StructureStubInfo.h"
79 #include "TypeLocationCache.h"
80 #include "TypeProfiler.h"
81 #include "UnlinkedInstructionStream.h"
82 #include "VMInlines.h"
83 #include <wtf/BagToHashMap.h>
84 #include <wtf/CommaPrinter.h>
85 #include <wtf/SimpleStats.h>
86 #include <wtf/StringExtras.h>
87 #include <wtf/StringPrintStream.h>
88 #include <wtf/text/UniquedStringImpl.h>
89
90 #if ENABLE(JIT)
91 #include "RegisterAtOffsetList.h"
92 #endif
93
94 #if ENABLE(DFG_JIT)
95 #include "DFGOperations.h"
96 #endif
97
98 #if ENABLE(FTL_JIT)
99 #include "FTLJITCode.h"
100 #endif
101
102 namespace JSC {
103
104 const ClassInfo CodeBlock::s_info = {
105     "CodeBlock", nullptr, nullptr, nullptr,
106     CREATE_METHOD_TABLE(CodeBlock)
107 };
108
109 CString CodeBlock::inferredName() const
110 {
111     switch (codeType()) {
112     case GlobalCode:
113         return "<global>";
114     case EvalCode:
115         return "<eval>";
116     case FunctionCode:
117         return jsCast<FunctionExecutable*>(ownerExecutable())->inferredName().utf8();
118     case ModuleCode:
119         return "<module>";
120     default:
121         CRASH();
122         return CString("", 0);
123     }
124 }
125
126 bool CodeBlock::hasHash() const
127 {
128     return !!m_hash;
129 }
130
131 bool CodeBlock::isSafeToComputeHash() const
132 {
133     return !isCompilationThread();
134 }
135
136 CodeBlockHash CodeBlock::hash() const
137 {
138     if (!m_hash) {
139         RELEASE_ASSERT(isSafeToComputeHash());
140         m_hash = CodeBlockHash(ownerScriptExecutable()->source(), specializationKind());
141     }
142     return m_hash;
143 }
144
145 CString CodeBlock::sourceCodeForTools() const
146 {
147     if (codeType() != FunctionCode)
148         return ownerScriptExecutable()->source().toUTF8();
149     
150     SourceProvider* provider = source();
151     FunctionExecutable* executable = jsCast<FunctionExecutable*>(ownerExecutable());
152     UnlinkedFunctionExecutable* unlinked = executable->unlinkedExecutable();
153     unsigned unlinkedStartOffset = unlinked->startOffset();
154     unsigned linkedStartOffset = executable->source().startOffset();
155     int delta = linkedStartOffset - unlinkedStartOffset;
156     unsigned rangeStart = delta + unlinked->unlinkedFunctionNameStart();
157     unsigned rangeEnd = delta + unlinked->startOffset() + unlinked->sourceLength();
158     return toCString(
159         "function ",
160         provider->source().substring(rangeStart, rangeEnd - rangeStart).utf8());
161 }
162
163 CString CodeBlock::sourceCodeOnOneLine() const
164 {
165     return reduceWhitespace(sourceCodeForTools());
166 }
167
168 CString CodeBlock::hashAsStringIfPossible() const
169 {
170     if (hasHash() || isSafeToComputeHash())
171         return toCString(hash());
172     return "<no-hash>";
173 }
174
175 void CodeBlock::dumpAssumingJITType(PrintStream& out, JITCode::JITType jitType) const
176 {
177     out.print(inferredName(), "#", hashAsStringIfPossible());
178     out.print(":[", RawPointer(this), "->");
179     if (!!m_alternative)
180         out.print(RawPointer(alternative()), "->");
181     out.print(RawPointer(ownerExecutable()), ", ", jitType, codeType());
182
183     if (codeType() == FunctionCode)
184         out.print(specializationKind());
185     out.print(", ", instructionCount());
186     if (this->jitType() == JITCode::BaselineJIT && m_shouldAlwaysBeInlined)
187         out.print(" (ShouldAlwaysBeInlined)");
188     if (ownerScriptExecutable()->neverInline())
189         out.print(" (NeverInline)");
190     if (ownerScriptExecutable()->neverOptimize())
191         out.print(" (NeverOptimize)");
192     else if (ownerScriptExecutable()->neverFTLOptimize())
193         out.print(" (NeverFTLOptimize)");
194     if (ownerScriptExecutable()->didTryToEnterInLoop())
195         out.print(" (DidTryToEnterInLoop)");
196     if (ownerScriptExecutable()->isStrictMode())
197         out.print(" (StrictMode)");
198     if (m_didFailJITCompilation)
199         out.print(" (JITFail)");
200     if (this->jitType() == JITCode::BaselineJIT && m_didFailFTLCompilation)
201         out.print(" (FTLFail)");
202     if (this->jitType() == JITCode::BaselineJIT && m_hasBeenCompiledWithFTL)
203         out.print(" (HadFTLReplacement)");
204     out.print("]");
205 }
206
207 void CodeBlock::dump(PrintStream& out) const
208 {
209     dumpAssumingJITType(out, jitType());
210 }
211
212 void CodeBlock::dumpSource()
213 {
214     dumpSource(WTF::dataFile());
215 }
216
217 void CodeBlock::dumpSource(PrintStream& out)
218 {
219     ScriptExecutable* executable = ownerScriptExecutable();
220     if (executable->isFunctionExecutable()) {
221         FunctionExecutable* functionExecutable = reinterpret_cast<FunctionExecutable*>(executable);
222         StringView source = functionExecutable->source().provider()->getRange(
223             functionExecutable->parametersStartOffset(),
224             functionExecutable->typeProfilingEndOffset() + 1); // Type profiling end offset is the character before the '}'.
225         
226         out.print("function ", inferredName(), source);
227         return;
228     }
229     out.print(executable->source().view());
230 }
231
232 void CodeBlock::dumpBytecode()
233 {
234     dumpBytecode(WTF::dataFile());
235 }
236
237 void CodeBlock::dumpBytecode(PrintStream& out)
238 {
239     StubInfoMap stubInfos;
240     CallLinkInfoMap callLinkInfos;
241     getStubInfoMap(stubInfos);
242     getCallLinkInfoMap(callLinkInfos);
243     BytecodeDumper<CodeBlock>::dumpBlock(this, instructions(), out, stubInfos, callLinkInfos);
244 }
245
246 void CodeBlock::dumpBytecode(PrintStream& out, const Instruction* begin, const Instruction*& it, const StubInfoMap& stubInfos, const CallLinkInfoMap& callLinkInfos)
247 {
248     BytecodeDumper<CodeBlock>::dumpBytecode(this, out, begin, it, stubInfos, callLinkInfos);
249 }
250
251 void CodeBlock::dumpBytecode(
252     PrintStream& out, unsigned bytecodeOffset,
253     const StubInfoMap& stubInfos, const CallLinkInfoMap& callLinkInfos)
254 {
255     const Instruction* it = instructions().begin() + bytecodeOffset;
256     dumpBytecode(out, instructions().begin(), it, stubInfos, callLinkInfos);
257 }
258
259 #define FOR_EACH_MEMBER_VECTOR(macro) \
260     macro(instructions) \
261     macro(callLinkInfos) \
262     macro(linkedCallerList) \
263     macro(identifiers) \
264     macro(functionExpressions) \
265     macro(constantRegisters)
266
267 template<typename T>
268 static size_t sizeInBytes(const Vector<T>& vector)
269 {
270     return vector.capacity() * sizeof(T);
271 }
272
273 namespace {
274
275 class PutToScopeFireDetail : public FireDetail {
276 public:
277     PutToScopeFireDetail(CodeBlock* codeBlock, const Identifier& ident)
278         : m_codeBlock(codeBlock)
279         , m_ident(ident)
280     {
281     }
282     
283     void dump(PrintStream& out) const override
284     {
285         out.print("Linking put_to_scope in ", FunctionExecutableDump(jsCast<FunctionExecutable*>(m_codeBlock->ownerExecutable())), " for ", m_ident);
286     }
287     
288 private:
289     CodeBlock* m_codeBlock;
290     const Identifier& m_ident;
291 };
292
293 } // anonymous namespace
294
295 CodeBlock::CodeBlock(VM* vm, Structure* structure, CopyParsedBlockTag, CodeBlock& other)
296     : JSCell(*vm, structure)
297     , m_globalObject(other.m_globalObject)
298     , m_numCalleeLocals(other.m_numCalleeLocals)
299     , m_numVars(other.m_numVars)
300     , m_shouldAlwaysBeInlined(true)
301 #if ENABLE(JIT)
302     , m_capabilityLevelState(DFG::CapabilityLevelNotSet)
303 #endif
304     , m_didFailJITCompilation(false)
305     , m_didFailFTLCompilation(false)
306     , m_hasBeenCompiledWithFTL(false)
307     , m_isConstructor(other.m_isConstructor)
308     , m_isStrictMode(other.m_isStrictMode)
309     , m_codeType(other.m_codeType)
310     , m_unlinkedCode(*other.m_vm, this, other.m_unlinkedCode.get())
311     , m_numberOfArgumentsToSkip(other.m_numberOfArgumentsToSkip)
312     , m_hasDebuggerStatement(false)
313     , m_steppingMode(SteppingModeDisabled)
314     , m_numBreakpoints(0)
315     , m_ownerExecutable(*other.m_vm, this, other.m_ownerExecutable.get())
316     , m_vm(other.m_vm)
317     , m_instructions(other.m_instructions)
318     , m_thisRegister(other.m_thisRegister)
319     , m_scopeRegister(other.m_scopeRegister)
320     , m_hash(other.m_hash)
321     , m_source(other.m_source)
322     , m_sourceOffset(other.m_sourceOffset)
323     , m_firstLineColumnOffset(other.m_firstLineColumnOffset)
324     , m_constantRegisters(other.m_constantRegisters)
325     , m_constantsSourceCodeRepresentation(other.m_constantsSourceCodeRepresentation)
326     , m_functionDecls(other.m_functionDecls)
327     , m_functionExprs(other.m_functionExprs)
328     , m_osrExitCounter(0)
329     , m_optimizationDelayCounter(0)
330     , m_reoptimizationRetryCounter(0)
331     , m_creationTime(std::chrono::steady_clock::now())
332 {
333     m_visitWeaklyHasBeenCalled = false;
334
335     ASSERT(heap()->isDeferred());
336     ASSERT(m_scopeRegister.isLocal());
337
338     setNumParameters(other.numParameters());
339 }
340
341 void CodeBlock::finishCreation(VM& vm, CopyParsedBlockTag, CodeBlock& other)
342 {
343     Base::finishCreation(vm);
344
345     optimizeAfterWarmUp();
346     jitAfterWarmUp();
347
348     if (other.m_rareData) {
349         createRareDataIfNecessary();
350         
351         m_rareData->m_exceptionHandlers = other.m_rareData->m_exceptionHandlers;
352         m_rareData->m_switchJumpTables = other.m_rareData->m_switchJumpTables;
353         m_rareData->m_stringSwitchJumpTables = other.m_rareData->m_stringSwitchJumpTables;
354     }
355     
356     heap()->m_codeBlocks->add(this);
357 }
358
359 CodeBlock::CodeBlock(VM* vm, Structure* structure, ScriptExecutable* ownerExecutable, UnlinkedCodeBlock* unlinkedCodeBlock,
360     JSScope* scope, RefPtr<SourceProvider>&& sourceProvider, unsigned sourceOffset, unsigned firstLineColumnOffset)
361     : JSCell(*vm, structure)
362     , m_globalObject(*vm, this, scope->globalObject())
363     , m_numCalleeLocals(unlinkedCodeBlock->m_numCalleeLocals)
364     , m_numVars(unlinkedCodeBlock->m_numVars)
365     , m_shouldAlwaysBeInlined(true)
366 #if ENABLE(JIT)
367     , m_capabilityLevelState(DFG::CapabilityLevelNotSet)
368 #endif
369     , m_didFailJITCompilation(false)
370     , m_didFailFTLCompilation(false)
371     , m_hasBeenCompiledWithFTL(false)
372     , m_isConstructor(unlinkedCodeBlock->isConstructor())
373     , m_isStrictMode(unlinkedCodeBlock->isStrictMode())
374     , m_codeType(unlinkedCodeBlock->codeType())
375     , m_unlinkedCode(*vm, this, unlinkedCodeBlock)
376     , m_hasDebuggerStatement(false)
377     , m_steppingMode(SteppingModeDisabled)
378     , m_numBreakpoints(0)
379     , m_ownerExecutable(*vm, this, ownerExecutable)
380     , m_vm(vm)
381     , m_thisRegister(unlinkedCodeBlock->thisRegister())
382     , m_scopeRegister(unlinkedCodeBlock->scopeRegister())
383     , m_source(WTFMove(sourceProvider))
384     , m_sourceOffset(sourceOffset)
385     , m_firstLineColumnOffset(firstLineColumnOffset)
386     , m_osrExitCounter(0)
387     , m_optimizationDelayCounter(0)
388     , m_reoptimizationRetryCounter(0)
389     , m_creationTime(std::chrono::steady_clock::now())
390 {
391     m_visitWeaklyHasBeenCalled = false;
392
393     ASSERT(heap()->isDeferred());
394     ASSERT(m_scopeRegister.isLocal());
395
396     ASSERT(m_source);
397     setNumParameters(unlinkedCodeBlock->numParameters());
398 }
399
400 // The main purpose of this function is to generate linked bytecode from unlinked bytecode. The process
401 // of linking is taking an abstract representation of bytecode and tying it to a GlobalObject and scope
402 // chain. For example, this process allows us to cache the depth of lexical environment reads that reach
403 // outside of this CodeBlock's compilation unit. It also allows us to generate particular constants that
404 // we can't generate during unlinked bytecode generation. This process is not allowed to generate control
405 // flow or introduce new locals. The reason for this is we rely on liveness analysis to be the same for
406 // all the CodeBlocks of an UnlinkedCodeBlock. We rely on this fact by caching the liveness analysis
407 // inside UnlinkedCodeBlock.
408 bool CodeBlock::finishCreation(VM& vm, ScriptExecutable* ownerExecutable, UnlinkedCodeBlock* unlinkedCodeBlock,
409     JSScope* scope)
410 {
411     Base::finishCreation(vm);
412
413     auto throwScope = DECLARE_THROW_SCOPE(vm);
414
415     if (vm.typeProfiler() || vm.controlFlowProfiler())
416         vm.functionHasExecutedCache()->removeUnexecutedRange(ownerExecutable->sourceID(), ownerExecutable->typeProfilingStartOffset(), ownerExecutable->typeProfilingEndOffset());
417
418     setConstantRegisters(unlinkedCodeBlock->constantRegisters(), unlinkedCodeBlock->constantsSourceCodeRepresentation());
419     RETURN_IF_EXCEPTION(throwScope, false);
420
421     setConstantIdentifierSetRegisters(vm, unlinkedCodeBlock->constantIdentifierSets());
422     RETURN_IF_EXCEPTION(throwScope, false);
423
424     if (unlinkedCodeBlock->usesGlobalObject())
425         m_constantRegisters[unlinkedCodeBlock->globalObjectRegister().toConstantIndex()].set(*m_vm, this, m_globalObject.get());
426
427     for (unsigned i = 0; i < LinkTimeConstantCount; i++) {
428         LinkTimeConstant type = static_cast<LinkTimeConstant>(i);
429         if (unsigned registerIndex = unlinkedCodeBlock->registerIndexForLinkTimeConstant(type))
430             m_constantRegisters[registerIndex].set(*m_vm, this, m_globalObject->jsCellForLinkTimeConstant(type));
431     }
432
433     // We already have the cloned symbol table for the module environment since we need to instantiate
434     // the module environments before linking the code block. We replace the stored symbol table with the already cloned one.
435     if (UnlinkedModuleProgramCodeBlock* unlinkedModuleProgramCodeBlock = jsDynamicCast<UnlinkedModuleProgramCodeBlock*>(vm, unlinkedCodeBlock)) {
436         SymbolTable* clonedSymbolTable = jsCast<ModuleProgramExecutable*>(ownerExecutable)->moduleEnvironmentSymbolTable();
437         if (m_vm->typeProfiler()) {
438             ConcurrentJSLocker locker(clonedSymbolTable->m_lock);
439             clonedSymbolTable->prepareForTypeProfiling(locker);
440         }
441         replaceConstant(unlinkedModuleProgramCodeBlock->moduleEnvironmentSymbolTableConstantRegisterOffset(), clonedSymbolTable);
442     }
443
444     bool shouldUpdateFunctionHasExecutedCache = vm.typeProfiler() || vm.controlFlowProfiler();
445     m_functionDecls = RefCountedArray<WriteBarrier<FunctionExecutable>>(unlinkedCodeBlock->numberOfFunctionDecls());
446     for (size_t count = unlinkedCodeBlock->numberOfFunctionDecls(), i = 0; i < count; ++i) {
447         UnlinkedFunctionExecutable* unlinkedExecutable = unlinkedCodeBlock->functionDecl(i);
448         if (shouldUpdateFunctionHasExecutedCache)
449             vm.functionHasExecutedCache()->insertUnexecutedRange(ownerExecutable->sourceID(), unlinkedExecutable->typeProfilingStartOffset(), unlinkedExecutable->typeProfilingEndOffset());
450         m_functionDecls[i].set(*m_vm, this, unlinkedExecutable->link(*m_vm, ownerExecutable->source()));
451     }
452
453     m_functionExprs = RefCountedArray<WriteBarrier<FunctionExecutable>>(unlinkedCodeBlock->numberOfFunctionExprs());
454     for (size_t count = unlinkedCodeBlock->numberOfFunctionExprs(), i = 0; i < count; ++i) {
455         UnlinkedFunctionExecutable* unlinkedExecutable = unlinkedCodeBlock->functionExpr(i);
456         if (shouldUpdateFunctionHasExecutedCache)
457             vm.functionHasExecutedCache()->insertUnexecutedRange(ownerExecutable->sourceID(), unlinkedExecutable->typeProfilingStartOffset(), unlinkedExecutable->typeProfilingEndOffset());
458         m_functionExprs[i].set(*m_vm, this, unlinkedExecutable->link(*m_vm, ownerExecutable->source()));
459     }
460
461     if (unlinkedCodeBlock->hasRareData()) {
462         createRareDataIfNecessary();
463         if (size_t count = unlinkedCodeBlock->numberOfExceptionHandlers()) {
464             m_rareData->m_exceptionHandlers.resizeToFit(count);
465             for (size_t i = 0; i < count; i++) {
466                 const UnlinkedHandlerInfo& unlinkedHandler = unlinkedCodeBlock->exceptionHandler(i);
467                 HandlerInfo& handler = m_rareData->m_exceptionHandlers[i];
468 #if ENABLE(JIT)
469                 handler.initialize(unlinkedHandler, CodeLocationLabel(MacroAssemblerCodePtr::createFromExecutableAddress(LLInt::getCodePtr(op_catch))));
470 #else
471                 handler.initialize(unlinkedHandler);
472 #endif
473             }
474         }
475
476         if (size_t count = unlinkedCodeBlock->numberOfStringSwitchJumpTables()) {
477             m_rareData->m_stringSwitchJumpTables.grow(count);
478             for (size_t i = 0; i < count; i++) {
479                 UnlinkedStringJumpTable::StringOffsetTable::iterator ptr = unlinkedCodeBlock->stringSwitchJumpTable(i).offsetTable.begin();
480                 UnlinkedStringJumpTable::StringOffsetTable::iterator end = unlinkedCodeBlock->stringSwitchJumpTable(i).offsetTable.end();
481                 for (; ptr != end; ++ptr) {
482                     OffsetLocation offset;
483                     offset.branchOffset = ptr->value.branchOffset;
484                     m_rareData->m_stringSwitchJumpTables[i].offsetTable.add(ptr->key, offset);
485                 }
486             }
487         }
488
489         if (size_t count = unlinkedCodeBlock->numberOfSwitchJumpTables()) {
490             m_rareData->m_switchJumpTables.grow(count);
491             for (size_t i = 0; i < count; i++) {
492                 UnlinkedSimpleJumpTable& sourceTable = unlinkedCodeBlock->switchJumpTable(i);
493                 SimpleJumpTable& destTable = m_rareData->m_switchJumpTables[i];
494                 destTable.branchOffsets = sourceTable.branchOffsets;
495                 destTable.min = sourceTable.min;
496             }
497         }
498     }
499
500     // Allocate metadata buffers for the bytecode
501     if (size_t size = unlinkedCodeBlock->numberOfLLintCallLinkInfos())
502         m_llintCallLinkInfos = RefCountedArray<LLIntCallLinkInfo>(size);
503     if (size_t size = unlinkedCodeBlock->numberOfArrayProfiles())
504         m_arrayProfiles.grow(size);
505     if (size_t size = unlinkedCodeBlock->numberOfArrayAllocationProfiles())
506         m_arrayAllocationProfiles = RefCountedArray<ArrayAllocationProfile>(size);
507     if (size_t size = unlinkedCodeBlock->numberOfValueProfiles())
508         m_valueProfiles = RefCountedArray<ValueProfile>(size);
509     if (size_t size = unlinkedCodeBlock->numberOfObjectAllocationProfiles())
510         m_objectAllocationProfiles = RefCountedArray<ObjectAllocationProfile>(size);
511
512 #if ENABLE(JIT)
513     setCalleeSaveRegisters(RegisterSet::llintBaselineCalleeSaveRegisters());
514 #endif
515
516     // Copy and translate the UnlinkedInstructions
517     unsigned instructionCount = unlinkedCodeBlock->instructions().count();
518     UnlinkedInstructionStream::Reader instructionReader(unlinkedCodeBlock->instructions());
519
520     // Bookkeep the strongly referenced module environments.
521     HashSet<JSModuleEnvironment*> stronglyReferencedModuleEnvironments;
522
523     RefCountedArray<Instruction> instructions(instructionCount);
524
525     unsigned valueProfileCount = 0;
526     auto linkValueProfile = [&](unsigned bytecodeOffset, unsigned opLength) {
527         unsigned valueProfileIndex = valueProfileCount++;
528         ValueProfile* profile = &m_valueProfiles[valueProfileIndex];
529         ASSERT(profile->m_bytecodeOffset == -1);
530         profile->m_bytecodeOffset = bytecodeOffset;
531         instructions[bytecodeOffset + opLength - 1] = profile;
532     };
533
534     for (unsigned i = 0; !instructionReader.atEnd(); ) {
535         const UnlinkedInstruction* pc = instructionReader.next();
536
537         unsigned opLength = opcodeLength(pc[0].u.opcode);
538
539         instructions[i] = Interpreter::getOpcode(pc[0].u.opcode);
540         for (size_t j = 1; j < opLength; ++j) {
541             if (sizeof(int32_t) != sizeof(intptr_t))
542                 instructions[i + j].u.pointer = 0;
543             instructions[i + j].u.operand = pc[j].u.operand;
544         }
545         switch (pc[0].u.opcode) {
546         case op_has_indexed_property: {
547             int arrayProfileIndex = pc[opLength - 1].u.operand;
548             m_arrayProfiles[arrayProfileIndex] = ArrayProfile(i);
549
550             instructions[i + opLength - 1] = &m_arrayProfiles[arrayProfileIndex];
551             break;
552         }
553         case op_call_varargs:
554         case op_tail_call_varargs:
555         case op_tail_call_forward_arguments:
556         case op_construct_varargs:
557         case op_get_by_val: {
558             int arrayProfileIndex = pc[opLength - 2].u.operand;
559             m_arrayProfiles[arrayProfileIndex] = ArrayProfile(i);
560
561             instructions[i + opLength - 2] = &m_arrayProfiles[arrayProfileIndex];
562             FALLTHROUGH;
563         }
564         case op_get_direct_pname:
565         case op_get_by_id:
566         case op_get_by_id_with_this:
567         case op_try_get_by_id:
568         case op_get_by_val_with_this:
569         case op_get_from_arguments:
570         case op_to_number:
571         case op_to_object:
572         case op_get_argument: {
573             linkValueProfile(i, opLength);
574             break;
575         }
576
577         case op_in:
578         case op_put_by_val:
579         case op_put_by_val_direct: {
580             int arrayProfileIndex = pc[opLength - 1].u.operand;
581             m_arrayProfiles[arrayProfileIndex] = ArrayProfile(i);
582             instructions[i + opLength - 1] = &m_arrayProfiles[arrayProfileIndex];
583             break;
584         }
585
586         case op_new_array:
587         case op_new_array_buffer:
588         case op_new_array_with_size: {
589             int arrayAllocationProfileIndex = pc[opLength - 1].u.operand;
590             instructions[i + opLength - 1] = &m_arrayAllocationProfiles[arrayAllocationProfileIndex];
591             break;
592         }
593         case op_new_object: {
594             int objectAllocationProfileIndex = pc[opLength - 1].u.operand;
595             ObjectAllocationProfile* objectAllocationProfile = &m_objectAllocationProfiles[objectAllocationProfileIndex];
596             int inferredInlineCapacity = pc[opLength - 2].u.operand;
597
598             instructions[i + opLength - 1] = objectAllocationProfile;
599             objectAllocationProfile->initializeProfile(vm,
600                 m_globalObject.get(), this, m_globalObject->objectPrototype(), inferredInlineCapacity);
601             break;
602         }
603
604         case op_call:
605         case op_tail_call:
606         case op_call_eval: {
607             linkValueProfile(i, opLength);
608             int arrayProfileIndex = pc[opLength - 2].u.operand;
609             m_arrayProfiles[arrayProfileIndex] = ArrayProfile(i);
610             instructions[i + opLength - 2] = &m_arrayProfiles[arrayProfileIndex];
611             instructions[i + 5] = &m_llintCallLinkInfos[pc[5].u.operand];
612             break;
613         }
614         case op_construct: {
615             instructions[i + 5] = &m_llintCallLinkInfos[pc[5].u.operand];
616             linkValueProfile(i, opLength);
617             break;
618         }
619         case op_get_array_length:
620             CRASH();
621
622         case op_resolve_scope: {
623             const Identifier& ident = identifier(pc[3].u.operand);
624             ResolveType type = static_cast<ResolveType>(pc[4].u.operand);
625             RELEASE_ASSERT(type != LocalClosureVar);
626             int localScopeDepth = pc[5].u.operand;
627
628             ResolveOp op = JSScope::abstractResolve(m_globalObject->globalExec(), localScopeDepth, scope, ident, Get, type, InitializationMode::NotInitialization);
629             RETURN_IF_EXCEPTION(throwScope, false);
630
631             instructions[i + 4].u.operand = op.type;
632             instructions[i + 5].u.operand = op.depth;
633             if (op.lexicalEnvironment) {
634                 if (op.type == ModuleVar) {
635                     // Keep the linked module environment strongly referenced.
636                     if (stronglyReferencedModuleEnvironments.add(jsCast<JSModuleEnvironment*>(op.lexicalEnvironment)).isNewEntry)
637                         addConstant(op.lexicalEnvironment);
638                     instructions[i + 6].u.jsCell.set(vm, this, op.lexicalEnvironment);
639                 } else
640                     instructions[i + 6].u.symbolTable.set(vm, this, op.lexicalEnvironment->symbolTable());
641             } else if (JSScope* constantScope = JSScope::constantScopeForCodeBlock(op.type, this))
642                 instructions[i + 6].u.jsCell.set(vm, this, constantScope);
643             else
644                 instructions[i + 6].u.pointer = nullptr;
645             break;
646         }
647
648         case op_get_from_scope: {
649             linkValueProfile(i, opLength);
650
651             // get_from_scope dst, scope, id, GetPutInfo, Structure, Operand
652
653             int localScopeDepth = pc[5].u.operand;
654             instructions[i + 5].u.pointer = nullptr;
655
656             GetPutInfo getPutInfo = GetPutInfo(pc[4].u.operand);
657             ASSERT(!isInitialization(getPutInfo.initializationMode()));
658             if (getPutInfo.resolveType() == LocalClosureVar) {
659                 instructions[i + 4] = GetPutInfo(getPutInfo.resolveMode(), ClosureVar, getPutInfo.initializationMode()).operand();
660                 break;
661             }
662
663             const Identifier& ident = identifier(pc[3].u.operand);
664             ResolveOp op = JSScope::abstractResolve(m_globalObject->globalExec(), localScopeDepth, scope, ident, Get, getPutInfo.resolveType(), InitializationMode::NotInitialization);
665             RETURN_IF_EXCEPTION(throwScope, false);
666
667             instructions[i + 4].u.operand = GetPutInfo(getPutInfo.resolveMode(), op.type, getPutInfo.initializationMode()).operand();
668             if (op.type == ModuleVar)
669                 instructions[i + 4].u.operand = GetPutInfo(getPutInfo.resolveMode(), ClosureVar, getPutInfo.initializationMode()).operand();
670             if (op.type == GlobalVar || op.type == GlobalVarWithVarInjectionChecks || op.type == GlobalLexicalVar || op.type == GlobalLexicalVarWithVarInjectionChecks)
671                 instructions[i + 5].u.watchpointSet = op.watchpointSet;
672             else if (op.structure)
673                 instructions[i + 5].u.structure.set(vm, this, op.structure);
674             instructions[i + 6].u.pointer = reinterpret_cast<void*>(op.operand);
675             break;
676         }
677
678         case op_put_to_scope: {
679             // put_to_scope scope, id, value, GetPutInfo, Structure, Operand
680             GetPutInfo getPutInfo = GetPutInfo(pc[4].u.operand);
681             if (getPutInfo.resolveType() == LocalClosureVar) {
682                 // Only do watching if the property we're putting to is not anonymous.
683                 if (static_cast<unsigned>(pc[2].u.operand) != UINT_MAX) {
684                     int symbolTableIndex = pc[5].u.operand;
685                     SymbolTable* symbolTable = jsCast<SymbolTable*>(getConstant(symbolTableIndex));
686                     const Identifier& ident = identifier(pc[2].u.operand);
687                     ConcurrentJSLocker locker(symbolTable->m_lock);
688                     auto iter = symbolTable->find(locker, ident.impl());
689                     ASSERT(iter != symbolTable->end(locker));
690                     iter->value.prepareToWatch();
691                     instructions[i + 5].u.watchpointSet = iter->value.watchpointSet();
692                 } else
693                     instructions[i + 5].u.watchpointSet = nullptr;
694                 break;
695             }
696
697             const Identifier& ident = identifier(pc[2].u.operand);
698             int localScopeDepth = pc[5].u.operand;
699             instructions[i + 5].u.pointer = nullptr;
700             ResolveOp op = JSScope::abstractResolve(m_globalObject->globalExec(), localScopeDepth, scope, ident, Put, getPutInfo.resolveType(), getPutInfo.initializationMode());
701             RETURN_IF_EXCEPTION(throwScope, false);
702
703             instructions[i + 4].u.operand = GetPutInfo(getPutInfo.resolveMode(), op.type, getPutInfo.initializationMode()).operand();
704             if (op.type == GlobalVar || op.type == GlobalVarWithVarInjectionChecks || op.type == GlobalLexicalVar || op.type == GlobalLexicalVarWithVarInjectionChecks)
705                 instructions[i + 5].u.watchpointSet = op.watchpointSet;
706             else if (op.type == ClosureVar || op.type == ClosureVarWithVarInjectionChecks) {
707                 if (op.watchpointSet)
708                     op.watchpointSet->invalidate(vm, PutToScopeFireDetail(this, ident));
709             } else if (op.structure)
710                 instructions[i + 5].u.structure.set(vm, this, op.structure);
711             instructions[i + 6].u.pointer = reinterpret_cast<void*>(op.operand);
712
713             break;
714         }
715
716         case op_profile_type: {
717             RELEASE_ASSERT(vm.typeProfiler());
718             // The format of this instruction is: op_profile_type regToProfile, TypeLocation*, flag, identifier?, resolveType?
719             size_t instructionOffset = i + opLength - 1;
720             unsigned divotStart, divotEnd;
721             GlobalVariableID globalVariableID = 0;
722             RefPtr<TypeSet> globalTypeSet;
723             bool shouldAnalyze = m_unlinkedCode->typeProfilerExpressionInfoForBytecodeOffset(instructionOffset, divotStart, divotEnd);
724             VirtualRegister profileRegister(pc[1].u.operand);
725             ProfileTypeBytecodeFlag flag = static_cast<ProfileTypeBytecodeFlag>(pc[3].u.operand);
726             SymbolTable* symbolTable = nullptr;
727
728             switch (flag) {
729             case ProfileTypeBytecodeClosureVar: {
730                 const Identifier& ident = identifier(pc[4].u.operand);
731                 int localScopeDepth = pc[2].u.operand;
732                 ResolveType type = static_cast<ResolveType>(pc[5].u.operand);
733                 // Even though type profiling may be profiling either a Get or a Put, we can always claim a Get because
734                 // we're abstractly "read"ing from a JSScope.
735                 ResolveOp op = JSScope::abstractResolve(m_globalObject->globalExec(), localScopeDepth, scope, ident, Get, type, InitializationMode::NotInitialization);
736                 RETURN_IF_EXCEPTION(throwScope, false);
737
738                 if (op.type == ClosureVar || op.type == ModuleVar)
739                     symbolTable = op.lexicalEnvironment->symbolTable();
740                 else if (op.type == GlobalVar)
741                     symbolTable = m_globalObject.get()->symbolTable();
742
743                 UniquedStringImpl* impl = (op.type == ModuleVar) ? op.importedName.get() : ident.impl();
744                 if (symbolTable) {
745                     ConcurrentJSLocker locker(symbolTable->m_lock);
746                     // If our parent scope was created while profiling was disabled, it will not have prepared for profiling yet.
747                     symbolTable->prepareForTypeProfiling(locker);
748                     globalVariableID = symbolTable->uniqueIDForVariable(locker, impl, vm);
749                     globalTypeSet = symbolTable->globalTypeSetForVariable(locker, impl, vm);
750                 } else
751                     globalVariableID = TypeProfilerNoGlobalIDExists;
752
753                 break;
754             }
755             case ProfileTypeBytecodeLocallyResolved: {
756                 int symbolTableIndex = pc[2].u.operand;
757                 SymbolTable* symbolTable = jsCast<SymbolTable*>(getConstant(symbolTableIndex));
758                 const Identifier& ident = identifier(pc[4].u.operand);
759                 ConcurrentJSLocker locker(symbolTable->m_lock);
760                 // If our parent scope was created while profiling was disabled, it will not have prepared for profiling yet.
761                 globalVariableID = symbolTable->uniqueIDForVariable(locker, ident.impl(), vm);
762                 globalTypeSet = symbolTable->globalTypeSetForVariable(locker, ident.impl(), vm);
763
764                 break;
765             }
766             case ProfileTypeBytecodeDoesNotHaveGlobalID: 
767             case ProfileTypeBytecodeFunctionArgument: {
768                 globalVariableID = TypeProfilerNoGlobalIDExists;
769                 break;
770             }
771             case ProfileTypeBytecodeFunctionReturnStatement: {
772                 RELEASE_ASSERT(ownerExecutable->isFunctionExecutable());
773                 globalTypeSet = jsCast<FunctionExecutable*>(ownerExecutable)->returnStatementTypeSet();
774                 globalVariableID = TypeProfilerReturnStatement;
775                 if (!shouldAnalyze) {
776                     // Because a return statement can be added implicitly to return undefined at the end of a function,
777                     // and these nodes don't emit expression ranges because they aren't in the actual source text of
778                     // the user's program, give the type profiler some range to identify these return statements.
779                     // Currently, the text offset that is used as identification is "f" in the function keyword
780                     // and is stored on TypeLocation's m_divotForFunctionOffsetIfReturnStatement member variable.
781                     divotStart = divotEnd = ownerExecutable->typeProfilingStartOffset();
782                     shouldAnalyze = true;
783                 }
784                 break;
785             }
786             }
787
788             std::pair<TypeLocation*, bool> locationPair = vm.typeProfiler()->typeLocationCache()->getTypeLocation(globalVariableID,
789                 ownerExecutable->sourceID(), divotStart, divotEnd, WTFMove(globalTypeSet), &vm);
790             TypeLocation* location = locationPair.first;
791             bool isNewLocation = locationPair.second;
792
793             if (flag == ProfileTypeBytecodeFunctionReturnStatement)
794                 location->m_divotForFunctionOffsetIfReturnStatement = ownerExecutable->typeProfilingStartOffset();
795
796             if (shouldAnalyze && isNewLocation)
797                 vm.typeProfiler()->insertNewLocation(location);
798
799             instructions[i + 2].u.location = location;
800             break;
801         }
802
803         case op_debug: {
804             if (pc[1].u.unsignedValue == DidReachBreakpoint)
805                 m_hasDebuggerStatement = true;
806             break;
807         }
808
809         case op_create_rest: {
810             int numberOfArgumentsToSkip = instructions[i + 3].u.operand;
811             ASSERT_UNUSED(numberOfArgumentsToSkip, numberOfArgumentsToSkip >= 0);
812             // This is used when rematerializing the rest parameter during OSR exit in the FTL JIT.");
813             m_numberOfArgumentsToSkip = numberOfArgumentsToSkip;
814             break;
815         }
816         
817         default:
818             break;
819         }
820
821         i += opLength;
822     }
823
824     if (vm.controlFlowProfiler())
825         insertBasicBlockBoundariesForControlFlowProfiler(instructions);
826
827     m_instructions = WTFMove(instructions);
828
829     // Set optimization thresholds only after m_instructions is initialized, since these
830     // rely on the instruction count (and are in theory permitted to also inspect the
831     // instruction stream to more accurate assess the cost of tier-up).
832     optimizeAfterWarmUp();
833     jitAfterWarmUp();
834
835     // If the concurrent thread will want the code block's hash, then compute it here
836     // synchronously.
837     if (Options::alwaysComputeHash())
838         hash();
839
840     if (Options::dumpGeneratedBytecodes())
841         dumpBytecode();
842
843     heap()->m_codeBlocks->add(this);
844     heap()->reportExtraMemoryAllocated(m_instructions.size() * sizeof(Instruction));
845
846     return true;
847 }
848
849 CodeBlock::~CodeBlock()
850 {
851     if (UNLIKELY(m_vm->m_perBytecodeProfiler))
852         m_vm->m_perBytecodeProfiler->notifyDestruction(this);
853
854     if (unlinkedCodeBlock()->didOptimize() == MixedTriState)
855         unlinkedCodeBlock()->setDidOptimize(FalseTriState);
856
857 #if ENABLE(VERBOSE_VALUE_PROFILE)
858     dumpValueProfiles();
859 #endif
860
861     // We may be destroyed before any CodeBlocks that refer to us are destroyed.
862     // Consider that two CodeBlocks become unreachable at the same time. There
863     // is no guarantee about the order in which the CodeBlocks are destroyed.
864     // So, if we don't remove incoming calls, and get destroyed before the
865     // CodeBlock(s) that have calls into us, then the CallLinkInfo vector's
866     // destructor will try to remove nodes from our (no longer valid) linked list.
867     unlinkIncomingCalls();
868     
869     // Note that our outgoing calls will be removed from other CodeBlocks'
870     // m_incomingCalls linked lists through the execution of the ~CallLinkInfo
871     // destructors.
872
873 #if ENABLE(JIT)
874     for (Bag<StructureStubInfo>::iterator iter = m_stubInfos.begin(); !!iter; ++iter) {
875         StructureStubInfo* stub = *iter;
876         stub->aboutToDie();
877         stub->deref();
878     }
879 #endif // ENABLE(JIT)
880 }
881
882 void CodeBlock::setConstantIdentifierSetRegisters(VM& vm, const Vector<ConstantIndentifierSetEntry>& constants)
883 {
884     auto scope = DECLARE_THROW_SCOPE(vm);
885     JSGlobalObject* globalObject = m_globalObject.get();
886     ExecState* exec = globalObject->globalExec();
887
888     for (const auto& entry : constants) {
889         const IdentifierSet& set = entry.first;
890
891         Structure* setStructure = globalObject->setStructure();
892         RETURN_IF_EXCEPTION(scope, void());
893         JSSet* jsSet = JSSet::create(exec, vm, setStructure, set.size());
894         RETURN_IF_EXCEPTION(scope, void());
895
896         for (auto setEntry : set) {
897             JSString* jsString = jsOwnedString(&vm, setEntry.get()); 
898             jsSet->add(exec, jsString);
899             RETURN_IF_EXCEPTION(scope, void());
900         }
901         m_constantRegisters[entry.second].set(vm, this, jsSet);
902     }
903 }
904
905 void CodeBlock::setConstantRegisters(const Vector<WriteBarrier<Unknown>>& constants, const Vector<SourceCodeRepresentation>& constantsSourceCodeRepresentation)
906 {
907     auto scope = DECLARE_THROW_SCOPE(*m_vm);
908     JSGlobalObject* globalObject = m_globalObject.get();
909     ExecState* exec = globalObject->globalExec();
910
911     ASSERT(constants.size() == constantsSourceCodeRepresentation.size());
912     size_t count = constants.size();
913     m_constantRegisters.resizeToFit(count);
914     bool hasTypeProfiler = !!m_vm->typeProfiler();
915     for (size_t i = 0; i < count; i++) {
916         JSValue constant = constants[i].get();
917
918         if (!constant.isEmpty()) {
919             if (SymbolTable* symbolTable = jsDynamicCast<SymbolTable*>(*m_vm, constant)) {
920                 if (hasTypeProfiler) {
921                     ConcurrentJSLocker locker(symbolTable->m_lock);
922                     symbolTable->prepareForTypeProfiling(locker);
923                 }
924
925                 SymbolTable* clone = symbolTable->cloneScopePart(*m_vm);
926                 if (wasCompiledWithDebuggingOpcodes())
927                     clone->setRareDataCodeBlock(this);
928
929                 constant = clone;
930             } else if (isTemplateRegistryKey(*m_vm, constant)) {
931                 auto* templateObject = globalObject->templateRegistry().getTemplateObject(exec, jsCast<JSTemplateRegistryKey*>(constant));
932                 RETURN_IF_EXCEPTION(scope, void());
933                 constant = templateObject;
934             }
935         }
936
937         m_constantRegisters[i].set(*m_vm, this, constant);
938     }
939
940     m_constantsSourceCodeRepresentation = constantsSourceCodeRepresentation;
941 }
942
943 void CodeBlock::setAlternative(VM& vm, CodeBlock* alternative)
944 {
945     m_alternative.set(vm, this, alternative);
946 }
947
948 void CodeBlock::setNumParameters(int newValue)
949 {
950     m_numParameters = newValue;
951
952     m_argumentValueProfiles = RefCountedArray<ValueProfile>(newValue);
953 }
954
955 CodeBlock* CodeBlock::specialOSREntryBlockOrNull()
956 {
957 #if ENABLE(FTL_JIT)
958     if (jitType() != JITCode::DFGJIT)
959         return 0;
960     DFG::JITCode* jitCode = m_jitCode->dfg();
961     return jitCode->osrEntryBlock();
962 #else // ENABLE(FTL_JIT)
963     return 0;
964 #endif // ENABLE(FTL_JIT)
965 }
966
967 void CodeBlock::visitWeakly(SlotVisitor& visitor)
968 {
969     ConcurrentJSLocker locker(m_lock);
970     if (m_visitWeaklyHasBeenCalled)
971         return;
972     
973     m_visitWeaklyHasBeenCalled = true;
974
975     if (Heap::isMarkedConcurrently(this))
976         return;
977
978     if (shouldVisitStrongly(locker)) {
979         visitor.appendUnbarriered(this);
980         return;
981     }
982     
983     // There are two things that may use unconditional finalizers: inline cache clearing
984     // and jettisoning. The probability of us wanting to do at least one of those things
985     // is probably quite close to 1. So we add one no matter what and when it runs, it
986     // figures out whether it has any work to do.
987     visitor.addUnconditionalFinalizer(&m_unconditionalFinalizer);
988
989     if (!JITCode::isOptimizingJIT(jitType()))
990         return;
991
992     // If we jettison ourselves we'll install our alternative, so make sure that it
993     // survives GC even if we don't.
994     visitor.append(m_alternative);
995     
996     // There are two things that we use weak reference harvesters for: DFG fixpoint for
997     // jettisoning, and trying to find structures that would be live based on some
998     // inline cache. So it makes sense to register them regardless.
999     visitor.addWeakReferenceHarvester(&m_weakReferenceHarvester);
1000
1001 #if ENABLE(DFG_JIT)
1002     // We get here if we're live in the sense that our owner executable is live,
1003     // but we're not yet live for sure in another sense: we may yet decide that this
1004     // code block should be jettisoned based on its outgoing weak references being
1005     // stale. Set a flag to indicate that we're still assuming that we're dead, and
1006     // perform one round of determining if we're live. The GC may determine, based on
1007     // either us marking additional objects, or by other objects being marked for
1008     // other reasons, that this iteration should run again; it will notify us of this
1009     // decision by calling harvestWeakReferences().
1010
1011     m_allTransitionsHaveBeenMarked = false;
1012     propagateTransitions(locker, visitor);
1013
1014     m_jitCode->dfgCommon()->livenessHasBeenProved = false;
1015     determineLiveness(locker, visitor);
1016 #endif // ENABLE(DFG_JIT)
1017 }
1018
1019 size_t CodeBlock::estimatedSize(JSCell* cell)
1020 {
1021     CodeBlock* thisObject = jsCast<CodeBlock*>(cell);
1022     size_t extraMemoryAllocated = thisObject->m_instructions.size() * sizeof(Instruction);
1023     if (thisObject->m_jitCode)
1024         extraMemoryAllocated += thisObject->m_jitCode->size();
1025     return Base::estimatedSize(cell) + extraMemoryAllocated;
1026 }
1027
1028 void CodeBlock::visitChildren(JSCell* cell, SlotVisitor& visitor)
1029 {
1030     CodeBlock* thisObject = jsCast<CodeBlock*>(cell);
1031     ASSERT_GC_OBJECT_INHERITS(thisObject, info());
1032     JSCell::visitChildren(thisObject, visitor);
1033     thisObject->visitChildren(visitor);
1034 }
1035
1036 void CodeBlock::visitChildren(SlotVisitor& visitor)
1037 {
1038     ConcurrentJSLocker locker(m_lock);
1039     // There are two things that may use unconditional finalizers: inline cache clearing
1040     // and jettisoning. The probability of us wanting to do at least one of those things
1041     // is probably quite close to 1. So we add one no matter what and when it runs, it
1042     // figures out whether it has any work to do.
1043     visitor.addUnconditionalFinalizer(&m_unconditionalFinalizer);
1044
1045     if (CodeBlock* otherBlock = specialOSREntryBlockOrNull())
1046         visitor.appendUnbarriered(otherBlock);
1047
1048     if (m_jitCode)
1049         visitor.reportExtraMemoryVisited(m_jitCode->size());
1050     if (m_instructions.size()) {
1051         unsigned refCount = m_instructions.refCount();
1052         if (!refCount) {
1053             dataLog("CodeBlock: ", RawPointer(this), "\n");
1054             dataLog("m_instructions.data(): ", RawPointer(m_instructions.data()), "\n");
1055             dataLog("refCount: ", refCount, "\n");
1056             RELEASE_ASSERT_NOT_REACHED();
1057         }
1058         visitor.reportExtraMemoryVisited(m_instructions.size() * sizeof(Instruction) / refCount);
1059     }
1060
1061     stronglyVisitStrongReferences(locker, visitor);
1062     stronglyVisitWeakReferences(locker, visitor);
1063
1064     m_allTransitionsHaveBeenMarked = false;
1065     propagateTransitions(locker, visitor);
1066 }
1067
1068 bool CodeBlock::shouldVisitStrongly(const ConcurrentJSLocker& locker)
1069 {
1070     if (Options::forceCodeBlockLiveness())
1071         return true;
1072
1073     if (shouldJettisonDueToOldAge(locker))
1074         return false;
1075
1076     // Interpreter and Baseline JIT CodeBlocks don't need to be jettisoned when
1077     // their weak references go stale. So if a basline JIT CodeBlock gets
1078     // scanned, we can assume that this means that it's live.
1079     if (!JITCode::isOptimizingJIT(jitType()))
1080         return true;
1081
1082     return false;
1083 }
1084
1085 bool CodeBlock::shouldJettisonDueToWeakReference()
1086 {
1087     if (!JITCode::isOptimizingJIT(jitType()))
1088         return false;
1089     return !Heap::isMarked(this);
1090 }
1091
1092 static std::chrono::milliseconds timeToLive(JITCode::JITType jitType)
1093 {
1094     if (UNLIKELY(Options::useEagerCodeBlockJettisonTiming())) {
1095         switch (jitType) {
1096         case JITCode::InterpreterThunk:
1097             return std::chrono::milliseconds(10);
1098         case JITCode::BaselineJIT:
1099             return std::chrono::milliseconds(10 + 20);
1100         case JITCode::DFGJIT:
1101             return std::chrono::milliseconds(40);
1102         case JITCode::FTLJIT:
1103             return std::chrono::milliseconds(120);
1104         default:
1105             return std::chrono::milliseconds::max();
1106         }
1107     }
1108
1109     switch (jitType) {
1110     case JITCode::InterpreterThunk:
1111         return std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::seconds(5));
1112     case JITCode::BaselineJIT:
1113         // Effectively 10 additional seconds, since BaselineJIT and
1114         // InterpreterThunk share a CodeBlock.
1115         return std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::seconds(5 + 10));
1116     case JITCode::DFGJIT:
1117         return std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::seconds(20));
1118     case JITCode::FTLJIT:
1119         return std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::seconds(60));
1120     default:
1121         return std::chrono::milliseconds::max();
1122     }
1123 }
1124
1125 bool CodeBlock::shouldJettisonDueToOldAge(const ConcurrentJSLocker&)
1126 {
1127     if (Heap::isMarkedConcurrently(this))
1128         return false;
1129
1130     if (UNLIKELY(Options::forceCodeBlockToJettisonDueToOldAge()))
1131         return true;
1132     
1133     if (timeSinceCreation() < timeToLive(jitType()))
1134         return false;
1135     
1136     return true;
1137 }
1138
1139 #if ENABLE(DFG_JIT)
1140 static bool shouldMarkTransition(DFG::WeakReferenceTransition& transition)
1141 {
1142     if (transition.m_codeOrigin && !Heap::isMarkedConcurrently(transition.m_codeOrigin.get()))
1143         return false;
1144     
1145     if (!Heap::isMarkedConcurrently(transition.m_from.get()))
1146         return false;
1147     
1148     return true;
1149 }
1150 #endif // ENABLE(DFG_JIT)
1151
1152 void CodeBlock::propagateTransitions(const ConcurrentJSLocker&, SlotVisitor& visitor)
1153 {
1154     UNUSED_PARAM(visitor);
1155
1156     if (m_allTransitionsHaveBeenMarked)
1157         return;
1158
1159     bool allAreMarkedSoFar = true;
1160         
1161     if (jitType() == JITCode::InterpreterThunk) {
1162         const Vector<unsigned>& propertyAccessInstructions = m_unlinkedCode->propertyAccessInstructions();
1163         for (size_t i = 0; i < propertyAccessInstructions.size(); ++i) {
1164             Instruction* instruction = &instructions()[propertyAccessInstructions[i]];
1165             switch (Interpreter::getOpcodeID(instruction[0])) {
1166             case op_put_by_id: {
1167                 StructureID oldStructureID = instruction[4].u.structureID;
1168                 StructureID newStructureID = instruction[6].u.structureID;
1169                 if (!oldStructureID || !newStructureID)
1170                     break;
1171                 Structure* oldStructure =
1172                     m_vm->heap.structureIDTable().get(oldStructureID);
1173                 Structure* newStructure =
1174                     m_vm->heap.structureIDTable().get(newStructureID);
1175                 if (Heap::isMarkedConcurrently(oldStructure))
1176                     visitor.appendUnbarriered(newStructure);
1177                 else
1178                     allAreMarkedSoFar = false;
1179                 break;
1180             }
1181             default:
1182                 break;
1183             }
1184         }
1185     }
1186
1187 #if ENABLE(JIT)
1188     if (JITCode::isJIT(jitType())) {
1189         for (Bag<StructureStubInfo>::iterator iter = m_stubInfos.begin(); !!iter; ++iter)
1190             allAreMarkedSoFar &= (*iter)->propagateTransitions(visitor);
1191     }
1192 #endif // ENABLE(JIT)
1193     
1194 #if ENABLE(DFG_JIT)
1195     if (JITCode::isOptimizingJIT(jitType())) {
1196         DFG::CommonData* dfgCommon = m_jitCode->dfgCommon();
1197         for (auto& weakReference : dfgCommon->weakStructureReferences)
1198             allAreMarkedSoFar &= weakReference->markIfCheap(visitor);
1199
1200         for (auto& transition : dfgCommon->transitions) {
1201             if (shouldMarkTransition(transition)) {
1202                 // If the following three things are live, then the target of the
1203                 // transition is also live:
1204                 //
1205                 // - This code block. We know it's live already because otherwise
1206                 //   we wouldn't be scanning ourselves.
1207                 //
1208                 // - The code origin of the transition. Transitions may arise from
1209                 //   code that was inlined. They are not relevant if the user's
1210                 //   object that is required for the inlinee to run is no longer
1211                 //   live.
1212                 //
1213                 // - The source of the transition. The transition checks if some
1214                 //   heap location holds the source, and if so, stores the target.
1215                 //   Hence the source must be live for the transition to be live.
1216                 //
1217                 // We also short-circuit the liveness if the structure is harmless
1218                 // to mark (i.e. its global object and prototype are both already
1219                 // live).
1220
1221                 visitor.append(transition.m_to);
1222             } else
1223                 allAreMarkedSoFar = false;
1224         }
1225     }
1226 #endif // ENABLE(DFG_JIT)
1227     
1228     if (allAreMarkedSoFar)
1229         m_allTransitionsHaveBeenMarked = true;
1230 }
1231
1232 void CodeBlock::determineLiveness(const ConcurrentJSLocker&, SlotVisitor& visitor)
1233 {
1234     UNUSED_PARAM(visitor);
1235     
1236 #if ENABLE(DFG_JIT)
1237     // Check if we have any remaining work to do.
1238     DFG::CommonData* dfgCommon = m_jitCode->dfgCommon();
1239     if (dfgCommon->livenessHasBeenProved)
1240         return;
1241     
1242     // Now check all of our weak references. If all of them are live, then we
1243     // have proved liveness and so we scan our strong references. If at end of
1244     // GC we still have not proved liveness, then this code block is toast.
1245     bool allAreLiveSoFar = true;
1246     for (unsigned i = 0; i < dfgCommon->weakReferences.size(); ++i) {
1247         JSCell* reference = dfgCommon->weakReferences[i].get();
1248         ASSERT(!jsDynamicCast<CodeBlock*>(*reference->vm(), reference));
1249         if (!Heap::isMarkedConcurrently(reference)) {
1250             allAreLiveSoFar = false;
1251             break;
1252         }
1253     }
1254     if (allAreLiveSoFar) {
1255         for (unsigned i = 0; i < dfgCommon->weakStructureReferences.size(); ++i) {
1256             if (!Heap::isMarkedConcurrently(dfgCommon->weakStructureReferences[i].get())) {
1257                 allAreLiveSoFar = false;
1258                 break;
1259             }
1260         }
1261     }
1262     
1263     // If some weak references are dead, then this fixpoint iteration was
1264     // unsuccessful.
1265     if (!allAreLiveSoFar)
1266         return;
1267     
1268     // All weak references are live. Record this information so we don't
1269     // come back here again, and scan the strong references.
1270     dfgCommon->livenessHasBeenProved = true;
1271     visitor.appendUnbarriered(this);
1272 #endif // ENABLE(DFG_JIT)
1273 }
1274
1275 void CodeBlock::WeakReferenceHarvester::visitWeakReferences(SlotVisitor& visitor)
1276 {
1277     CodeBlock* codeBlock =
1278         bitwise_cast<CodeBlock*>(
1279             bitwise_cast<char*>(this) - OBJECT_OFFSETOF(CodeBlock, m_weakReferenceHarvester));
1280     
1281     codeBlock->propagateTransitions(NoLockingNecessary, visitor);
1282     codeBlock->determineLiveness(NoLockingNecessary, visitor);
1283 }
1284
1285 void CodeBlock::clearLLIntGetByIdCache(Instruction* instruction)
1286 {
1287     instruction[0].u.opcode = LLInt::getOpcode(op_get_by_id);
1288     instruction[4].u.pointer = nullptr;
1289     instruction[5].u.pointer = nullptr;
1290     instruction[6].u.pointer = nullptr;
1291 }
1292
1293 void CodeBlock::finalizeLLIntInlineCaches()
1294 {
1295     const Vector<unsigned>& propertyAccessInstructions = m_unlinkedCode->propertyAccessInstructions();
1296     for (size_t size = propertyAccessInstructions.size(), i = 0; i < size; ++i) {
1297         Instruction* curInstruction = &instructions()[propertyAccessInstructions[i]];
1298         switch (Interpreter::getOpcodeID(curInstruction[0])) {
1299         case op_get_by_id:
1300         case op_get_by_id_proto_load:
1301         case op_get_by_id_unset: {
1302             StructureID oldStructureID = curInstruction[4].u.structureID;
1303             if (!oldStructureID || Heap::isMarked(m_vm->heap.structureIDTable().get(oldStructureID)))
1304                 break;
1305             if (Options::verboseOSR())
1306                 dataLogF("Clearing LLInt property access.\n");
1307             clearLLIntGetByIdCache(curInstruction);
1308             break;
1309         }
1310         case op_put_by_id: {
1311             StructureID oldStructureID = curInstruction[4].u.structureID;
1312             StructureID newStructureID = curInstruction[6].u.structureID;
1313             StructureChain* chain = curInstruction[7].u.structureChain.get();
1314             if ((!oldStructureID || Heap::isMarked(m_vm->heap.structureIDTable().get(oldStructureID))) &&
1315                 (!newStructureID || Heap::isMarked(m_vm->heap.structureIDTable().get(newStructureID))) &&
1316                 (!chain || Heap::isMarked(chain)))
1317                 break;
1318             if (Options::verboseOSR())
1319                 dataLogF("Clearing LLInt put transition.\n");
1320             curInstruction[4].u.structureID = 0;
1321             curInstruction[5].u.operand = 0;
1322             curInstruction[6].u.structureID = 0;
1323             curInstruction[7].u.structureChain.clear();
1324             break;
1325         }
1326         // FIXME: https://bugs.webkit.org/show_bug.cgi?id=166418
1327         // We need to add optimizations for op_resolve_scope_for_hoisting_func_decl_in_eval to do link time scope resolution.
1328         case op_resolve_scope_for_hoisting_func_decl_in_eval:
1329             break;
1330         case op_get_array_length:
1331             break;
1332         case op_to_this:
1333             if (!curInstruction[2].u.structure || Heap::isMarked(curInstruction[2].u.structure.get()))
1334                 break;
1335             if (Options::verboseOSR())
1336                 dataLogF("Clearing LLInt to_this with structure %p.\n", curInstruction[2].u.structure.get());
1337             curInstruction[2].u.structure.clear();
1338             curInstruction[3].u.toThisStatus = merge(
1339                 curInstruction[3].u.toThisStatus, ToThisClearedByGC);
1340             break;
1341         case op_create_this: {
1342             auto& cacheWriteBarrier = curInstruction[4].u.jsCell;
1343             if (!cacheWriteBarrier || cacheWriteBarrier.unvalidatedGet() == JSCell::seenMultipleCalleeObjects())
1344                 break;
1345             JSCell* cachedFunction = cacheWriteBarrier.get();
1346             if (Heap::isMarked(cachedFunction))
1347                 break;
1348             if (Options::verboseOSR())
1349                 dataLogF("Clearing LLInt create_this with cached callee %p.\n", cachedFunction);
1350             cacheWriteBarrier.clear();
1351             break;
1352         }
1353         case op_resolve_scope: {
1354             // Right now this isn't strictly necessary. Any symbol tables that this will refer to
1355             // are for outer functions, and we refer to those functions strongly, and they refer
1356             // to the symbol table strongly. But it's nice to be on the safe side.
1357             WriteBarrierBase<SymbolTable>& symbolTable = curInstruction[6].u.symbolTable;
1358             if (!symbolTable || Heap::isMarked(symbolTable.get()))
1359                 break;
1360             if (Options::verboseOSR())
1361                 dataLogF("Clearing dead symbolTable %p.\n", symbolTable.get());
1362             symbolTable.clear();
1363             break;
1364         }
1365         case op_get_from_scope:
1366         case op_put_to_scope: {
1367             GetPutInfo getPutInfo = GetPutInfo(curInstruction[4].u.operand);
1368             if (getPutInfo.resolveType() == GlobalVar || getPutInfo.resolveType() == GlobalVarWithVarInjectionChecks 
1369                 || getPutInfo.resolveType() == LocalClosureVar || getPutInfo.resolveType() == GlobalLexicalVar || getPutInfo.resolveType() == GlobalLexicalVarWithVarInjectionChecks)
1370                 continue;
1371             WriteBarrierBase<Structure>& structure = curInstruction[5].u.structure;
1372             if (!structure || Heap::isMarked(structure.get()))
1373                 break;
1374             if (Options::verboseOSR())
1375                 dataLogF("Clearing scope access with structure %p.\n", structure.get());
1376             structure.clear();
1377             break;
1378         }
1379         default:
1380             OpcodeID opcodeID = Interpreter::getOpcodeID(curInstruction[0]);
1381             ASSERT_WITH_MESSAGE_UNUSED(opcodeID, false, "Unhandled opcode in CodeBlock::finalizeUnconditionally, %s(%d) at bc %u", opcodeNames[opcodeID], opcodeID, propertyAccessInstructions[i]);
1382         }
1383     }
1384
1385     // We can't just remove all the sets when we clear the caches since we might have created a watchpoint set
1386     // then cleared the cache without GCing in between.
1387     m_llintGetByIdWatchpointMap.removeIf([](const StructureWatchpointMap::KeyValuePairType& pair) -> bool {
1388         return !Heap::isMarked(pair.key);
1389     });
1390
1391     for (unsigned i = 0; i < m_llintCallLinkInfos.size(); ++i) {
1392         if (m_llintCallLinkInfos[i].isLinked() && !Heap::isMarked(m_llintCallLinkInfos[i].callee.get())) {
1393             if (Options::verboseOSR())
1394                 dataLog("Clearing LLInt call from ", *this, "\n");
1395             m_llintCallLinkInfos[i].unlink();
1396         }
1397         if (!!m_llintCallLinkInfos[i].lastSeenCallee && !Heap::isMarked(m_llintCallLinkInfos[i].lastSeenCallee.get()))
1398             m_llintCallLinkInfos[i].lastSeenCallee.clear();
1399     }
1400 }
1401
1402 void CodeBlock::finalizeBaselineJITInlineCaches()
1403 {
1404 #if ENABLE(JIT)
1405     for (auto iter = callLinkInfosBegin(); !!iter; ++iter)
1406         (*iter)->visitWeak(*vm());
1407
1408     for (Bag<StructureStubInfo>::iterator iter = m_stubInfos.begin(); !!iter; ++iter) {
1409         StructureStubInfo& stubInfo = **iter;
1410         stubInfo.visitWeakReferences(this);
1411     }
1412 #endif
1413 }
1414
1415 void CodeBlock::UnconditionalFinalizer::finalizeUnconditionally()
1416 {
1417     CodeBlock* codeBlock = bitwise_cast<CodeBlock*>(
1418         bitwise_cast<char*>(this) - OBJECT_OFFSETOF(CodeBlock, m_unconditionalFinalizer));
1419     
1420     codeBlock->updateAllPredictions();
1421     
1422     if (!Heap::isMarked(codeBlock)) {
1423         if (codeBlock->shouldJettisonDueToWeakReference())
1424             codeBlock->jettison(Profiler::JettisonDueToWeakReference);
1425         else
1426             codeBlock->jettison(Profiler::JettisonDueToOldAge);
1427         return;
1428     }
1429
1430     if (JITCode::couldBeInterpreted(codeBlock->jitType()))
1431         codeBlock->finalizeLLIntInlineCaches();
1432
1433 #if ENABLE(JIT)
1434     if (!!codeBlock->jitCode())
1435         codeBlock->finalizeBaselineJITInlineCaches();
1436 #endif
1437 }
1438
1439 void CodeBlock::getStubInfoMap(const ConcurrentJSLocker&, StubInfoMap& result)
1440 {
1441 #if ENABLE(JIT)
1442     if (JITCode::isJIT(jitType()))
1443         toHashMap(m_stubInfos, getStructureStubInfoCodeOrigin, result);
1444 #else
1445     UNUSED_PARAM(result);
1446 #endif
1447 }
1448
1449 void CodeBlock::getStubInfoMap(StubInfoMap& result)
1450 {
1451     ConcurrentJSLocker locker(m_lock);
1452     getStubInfoMap(locker, result);
1453 }
1454
1455 void CodeBlock::getCallLinkInfoMap(const ConcurrentJSLocker&, CallLinkInfoMap& result)
1456 {
1457 #if ENABLE(JIT)
1458     if (JITCode::isJIT(jitType()))
1459         toHashMap(m_callLinkInfos, getCallLinkInfoCodeOrigin, result);
1460 #else
1461     UNUSED_PARAM(result);
1462 #endif
1463 }
1464
1465 void CodeBlock::getCallLinkInfoMap(CallLinkInfoMap& result)
1466 {
1467     ConcurrentJSLocker locker(m_lock);
1468     getCallLinkInfoMap(locker, result);
1469 }
1470
1471 void CodeBlock::getByValInfoMap(const ConcurrentJSLocker&, ByValInfoMap& result)
1472 {
1473 #if ENABLE(JIT)
1474     if (JITCode::isJIT(jitType())) {
1475         for (auto* byValInfo : m_byValInfos)
1476             result.add(CodeOrigin(byValInfo->bytecodeIndex), byValInfo);
1477     }
1478 #else
1479     UNUSED_PARAM(result);
1480 #endif
1481 }
1482
1483 void CodeBlock::getByValInfoMap(ByValInfoMap& result)
1484 {
1485     ConcurrentJSLocker locker(m_lock);
1486     getByValInfoMap(locker, result);
1487 }
1488
1489 #if ENABLE(JIT)
1490 StructureStubInfo* CodeBlock::addStubInfo(AccessType accessType)
1491 {
1492     ConcurrentJSLocker locker(m_lock);
1493     return m_stubInfos.add(accessType);
1494 }
1495
1496 JITAddIC* CodeBlock::addJITAddIC(ArithProfile* arithProfile)
1497 {
1498     return m_addICs.add(arithProfile);
1499 }
1500
1501 JITMulIC* CodeBlock::addJITMulIC(ArithProfile* arithProfile)
1502 {
1503     return m_mulICs.add(arithProfile);
1504 }
1505
1506 JITSubIC* CodeBlock::addJITSubIC(ArithProfile* arithProfile)
1507 {
1508     return m_subICs.add(arithProfile);
1509 }
1510
1511 JITNegIC* CodeBlock::addJITNegIC(ArithProfile* arithProfile)
1512 {
1513     return m_negICs.add(arithProfile);
1514 }
1515
1516 StructureStubInfo* CodeBlock::findStubInfo(CodeOrigin codeOrigin)
1517 {
1518     for (StructureStubInfo* stubInfo : m_stubInfos) {
1519         if (stubInfo->codeOrigin == codeOrigin)
1520             return stubInfo;
1521     }
1522     return nullptr;
1523 }
1524
1525 ByValInfo* CodeBlock::addByValInfo()
1526 {
1527     ConcurrentJSLocker locker(m_lock);
1528     return m_byValInfos.add();
1529 }
1530
1531 CallLinkInfo* CodeBlock::addCallLinkInfo()
1532 {
1533     ConcurrentJSLocker locker(m_lock);
1534     return m_callLinkInfos.add();
1535 }
1536
1537 CallLinkInfo* CodeBlock::getCallLinkInfoForBytecodeIndex(unsigned index)
1538 {
1539     for (auto iter = m_callLinkInfos.begin(); !!iter; ++iter) {
1540         if ((*iter)->codeOrigin() == CodeOrigin(index))
1541             return *iter;
1542     }
1543     return nullptr;
1544 }
1545
1546 void CodeBlock::resetJITData()
1547 {
1548     RELEASE_ASSERT(!JITCode::isJIT(jitType()));
1549     ConcurrentJSLocker locker(m_lock);
1550     
1551     // We can clear these because no other thread will have references to any stub infos, call
1552     // link infos, or by val infos if we don't have JIT code. Attempts to query these data
1553     // structures using the concurrent API (getStubInfoMap and friends) will return nothing if we
1554     // don't have JIT code.
1555     m_stubInfos.clear();
1556     m_callLinkInfos.clear();
1557     m_byValInfos.clear();
1558     
1559     // We can clear this because the DFG's queries to these data structures are guarded by whether
1560     // there is JIT code.
1561     m_rareCaseProfiles.clear();
1562 }
1563 #endif
1564
1565 void CodeBlock::visitOSRExitTargets(const ConcurrentJSLocker&, SlotVisitor& visitor)
1566 {
1567     // We strongly visit OSR exits targets because we don't want to deal with
1568     // the complexity of generating an exit target CodeBlock on demand and
1569     // guaranteeing that it matches the details of the CodeBlock we compiled
1570     // the OSR exit against.
1571
1572     visitor.append(m_alternative);
1573
1574 #if ENABLE(DFG_JIT)
1575     DFG::CommonData* dfgCommon = m_jitCode->dfgCommon();
1576     if (dfgCommon->inlineCallFrames) {
1577         for (auto* inlineCallFrame : *dfgCommon->inlineCallFrames) {
1578             ASSERT(inlineCallFrame->baselineCodeBlock);
1579             visitor.append(inlineCallFrame->baselineCodeBlock);
1580         }
1581     }
1582 #endif
1583 }
1584
1585 void CodeBlock::stronglyVisitStrongReferences(const ConcurrentJSLocker& locker, SlotVisitor& visitor)
1586 {
1587     UNUSED_PARAM(locker);
1588     
1589     visitor.append(m_globalObject);
1590     visitor.append(m_ownerExecutable);
1591     visitor.append(m_unlinkedCode);
1592     if (m_rareData)
1593         m_rareData->m_directEvalCodeCache.visitAggregate(visitor);
1594     visitor.appendValues(m_constantRegisters.data(), m_constantRegisters.size());
1595     for (auto& functionExpr : m_functionExprs)
1596         visitor.append(functionExpr);
1597     for (auto& functionDecl : m_functionDecls)
1598         visitor.append(functionDecl);
1599     for (auto& objectAllocationProfile : m_objectAllocationProfiles)
1600         objectAllocationProfile.visitAggregate(visitor);
1601
1602 #if ENABLE(JIT)
1603     for (ByValInfo* byValInfo : m_byValInfos)
1604         visitor.append(byValInfo->cachedSymbol);
1605 #endif
1606
1607 #if ENABLE(DFG_JIT)
1608     if (JITCode::isOptimizingJIT(jitType()))
1609         visitOSRExitTargets(locker, visitor);
1610 #endif
1611 }
1612
1613 void CodeBlock::stronglyVisitWeakReferences(const ConcurrentJSLocker&, SlotVisitor& visitor)
1614 {
1615     UNUSED_PARAM(visitor);
1616
1617 #if ENABLE(DFG_JIT)
1618     if (!JITCode::isOptimizingJIT(jitType()))
1619         return;
1620     
1621     DFG::CommonData* dfgCommon = m_jitCode->dfgCommon();
1622
1623     for (auto& transition : dfgCommon->transitions) {
1624         if (!!transition.m_codeOrigin)
1625             visitor.append(transition.m_codeOrigin); // Almost certainly not necessary, since the code origin should also be a weak reference. Better to be safe, though.
1626         visitor.append(transition.m_from);
1627         visitor.append(transition.m_to);
1628     }
1629
1630     for (auto& weakReference : dfgCommon->weakReferences)
1631         visitor.append(weakReference);
1632
1633     for (auto& weakStructureReference : dfgCommon->weakStructureReferences)
1634         visitor.append(weakStructureReference);
1635
1636     dfgCommon->livenessHasBeenProved = true;
1637 #endif    
1638 }
1639
1640 CodeBlock* CodeBlock::baselineAlternative()
1641 {
1642 #if ENABLE(JIT)
1643     CodeBlock* result = this;
1644     while (result->alternative())
1645         result = result->alternative();
1646     RELEASE_ASSERT(result);
1647     RELEASE_ASSERT(JITCode::isBaselineCode(result->jitType()) || result->jitType() == JITCode::None);
1648     return result;
1649 #else
1650     return this;
1651 #endif
1652 }
1653
1654 CodeBlock* CodeBlock::baselineVersion()
1655 {
1656 #if ENABLE(JIT)
1657     if (JITCode::isBaselineCode(jitType()))
1658         return this;
1659     CodeBlock* result = replacement();
1660     if (!result) {
1661         // This can happen if we're creating the original CodeBlock for an executable.
1662         // Assume that we're the baseline CodeBlock.
1663         RELEASE_ASSERT(jitType() == JITCode::None);
1664         return this;
1665     }
1666     result = result->baselineAlternative();
1667     return result;
1668 #else
1669     return this;
1670 #endif
1671 }
1672
1673 #if ENABLE(JIT)
1674 bool CodeBlock::hasOptimizedReplacement(JITCode::JITType typeToReplace)
1675 {
1676     return JITCode::isHigherTier(replacement()->jitType(), typeToReplace);
1677 }
1678
1679 bool CodeBlock::hasOptimizedReplacement()
1680 {
1681     return hasOptimizedReplacement(jitType());
1682 }
1683 #endif
1684
1685 HandlerInfo* CodeBlock::handlerForBytecodeOffset(unsigned bytecodeOffset, RequiredHandler requiredHandler)
1686 {
1687     RELEASE_ASSERT(bytecodeOffset < instructions().size());
1688     return handlerForIndex(bytecodeOffset, requiredHandler);
1689 }
1690
1691 HandlerInfo* CodeBlock::handlerForIndex(unsigned index, RequiredHandler requiredHandler)
1692 {
1693     if (!m_rareData)
1694         return 0;
1695     return HandlerInfo::handlerForIndex(m_rareData->m_exceptionHandlers, index, requiredHandler);
1696 }
1697
1698 CallSiteIndex CodeBlock::newExceptionHandlingCallSiteIndex(CallSiteIndex originalCallSite)
1699 {
1700 #if ENABLE(DFG_JIT)
1701     RELEASE_ASSERT(JITCode::isOptimizingJIT(jitType()));
1702     RELEASE_ASSERT(canGetCodeOrigin(originalCallSite));
1703     ASSERT(!!handlerForIndex(originalCallSite.bits()));
1704     CodeOrigin originalOrigin = codeOrigin(originalCallSite);
1705     return m_jitCode->dfgCommon()->addUniqueCallSiteIndex(originalOrigin);
1706 #else
1707     // We never create new on-the-fly exception handling
1708     // call sites outside the DFG/FTL inline caches.
1709     UNUSED_PARAM(originalCallSite);
1710     RELEASE_ASSERT_NOT_REACHED();
1711     return CallSiteIndex(0u);
1712 #endif
1713 }
1714
1715 void CodeBlock::ensureCatchLivenessIsComputedForBytecodeOffsetSlow(unsigned bytecodeOffset)
1716 {
1717     ASSERT(Interpreter::getOpcodeID(m_instructions[bytecodeOffset]) == op_catch);
1718     BytecodeLivenessAnalysis& bytecodeLiveness = livenessAnalysis();
1719
1720     // We get the live-out set of variables at op_catch, not the live-in. This
1721     // is because the variables that the op_catch defines might be dead, and
1722     // we can avoid profiling them and extracting them when doing OSR entry
1723     // into the DFG.
1724     FastBitVector liveLocals = bytecodeLiveness.getLivenessInfoAtBytecodeOffset(this, bytecodeOffset + OPCODE_LENGTH(op_catch));
1725     Vector<VirtualRegister> liveOperands;
1726     liveOperands.reserveInitialCapacity(liveLocals.bitCount());
1727     liveLocals.forEachSetBit([&] (unsigned liveLocal) {
1728         liveOperands.append(virtualRegisterForLocal(liveLocal));
1729     });
1730
1731     for (int i = 0; i < numParameters(); ++i)
1732         liveOperands.append(virtualRegisterForArgument(i));
1733
1734     auto profiles = std::make_unique<ValueProfileAndOperandBuffer>(liveOperands.size());
1735     RELEASE_ASSERT(profiles->m_size == liveOperands.size());
1736     for (unsigned i = 0; i < profiles->m_size; ++i)
1737         profiles->m_buffer.get()[i].m_operand = liveOperands[i].offset();
1738
1739     // The compiler thread will read this pointer value and then proceed to dereference it
1740     // if it is not null. We need to make sure all above stores happen before this store so
1741     // the compiler thread reads fully initialized data.
1742     WTF::storeStoreFence(); 
1743
1744     m_instructions[bytecodeOffset + 3].u.pointer = profiles.get();
1745
1746     {
1747         ConcurrentJSLocker locker(m_lock);
1748         m_catchProfiles.append(WTFMove(profiles));
1749     }
1750 }
1751
1752 void CodeBlock::removeExceptionHandlerForCallSite(CallSiteIndex callSiteIndex)
1753 {
1754     RELEASE_ASSERT(m_rareData);
1755     Vector<HandlerInfo>& exceptionHandlers = m_rareData->m_exceptionHandlers;
1756     unsigned index = callSiteIndex.bits();
1757     for (size_t i = 0; i < exceptionHandlers.size(); ++i) {
1758         HandlerInfo& handler = exceptionHandlers[i];
1759         if (handler.start <= index && handler.end > index) {
1760             exceptionHandlers.remove(i);
1761             return;
1762         }
1763     }
1764
1765     RELEASE_ASSERT_NOT_REACHED();
1766 }
1767
1768 unsigned CodeBlock::lineNumberForBytecodeOffset(unsigned bytecodeOffset)
1769 {
1770     RELEASE_ASSERT(bytecodeOffset < instructions().size());
1771     return ownerScriptExecutable()->firstLine() + m_unlinkedCode->lineNumberForBytecodeOffset(bytecodeOffset);
1772 }
1773
1774 unsigned CodeBlock::columnNumberForBytecodeOffset(unsigned bytecodeOffset)
1775 {
1776     int divot;
1777     int startOffset;
1778     int endOffset;
1779     unsigned line;
1780     unsigned column;
1781     expressionRangeForBytecodeOffset(bytecodeOffset, divot, startOffset, endOffset, line, column);
1782     return column;
1783 }
1784
1785 void CodeBlock::expressionRangeForBytecodeOffset(unsigned bytecodeOffset, int& divot, int& startOffset, int& endOffset, unsigned& line, unsigned& column) const
1786 {
1787     m_unlinkedCode->expressionRangeForBytecodeOffset(bytecodeOffset, divot, startOffset, endOffset, line, column);
1788     divot += m_sourceOffset;
1789     column += line ? 1 : firstLineColumnOffset();
1790     line += ownerScriptExecutable()->firstLine();
1791 }
1792
1793 bool CodeBlock::hasOpDebugForLineAndColumn(unsigned line, unsigned column)
1794 {
1795     const Instruction* begin = instructions().begin();
1796     const Instruction* end = instructions().end();
1797     for (const Instruction* it = begin; it != end;) {
1798         OpcodeID opcodeID = Interpreter::getOpcodeID(*it);
1799         if (opcodeID == op_debug) {
1800             unsigned bytecodeOffset = it - begin;
1801             int unused;
1802             unsigned opDebugLine;
1803             unsigned opDebugColumn;
1804             expressionRangeForBytecodeOffset(bytecodeOffset, unused, unused, unused, opDebugLine, opDebugColumn);
1805             if (line == opDebugLine && (column == Breakpoint::unspecifiedColumn || column == opDebugColumn))
1806                 return true;
1807         }
1808         it += opcodeLengths[opcodeID];
1809     }
1810     return false;
1811 }
1812
1813 void CodeBlock::shrinkToFit(ShrinkMode shrinkMode)
1814 {
1815     ConcurrentJSLocker locker(m_lock);
1816
1817     m_rareCaseProfiles.shrinkToFit();
1818     
1819     if (shrinkMode == EarlyShrink) {
1820         m_constantRegisters.shrinkToFit();
1821         m_constantsSourceCodeRepresentation.shrinkToFit();
1822         
1823         if (m_rareData) {
1824             m_rareData->m_switchJumpTables.shrinkToFit();
1825             m_rareData->m_stringSwitchJumpTables.shrinkToFit();
1826         }
1827     } // else don't shrink these, because we would have already pointed pointers into these tables.
1828 }
1829
1830 #if ENABLE(JIT)
1831 void CodeBlock::linkIncomingCall(ExecState* callerFrame, CallLinkInfo* incoming)
1832 {
1833     noticeIncomingCall(callerFrame);
1834     m_incomingCalls.push(incoming);
1835 }
1836
1837 void CodeBlock::linkIncomingPolymorphicCall(ExecState* callerFrame, PolymorphicCallNode* incoming)
1838 {
1839     noticeIncomingCall(callerFrame);
1840     m_incomingPolymorphicCalls.push(incoming);
1841 }
1842 #endif // ENABLE(JIT)
1843
1844 void CodeBlock::unlinkIncomingCalls()
1845 {
1846     while (m_incomingLLIntCalls.begin() != m_incomingLLIntCalls.end())
1847         m_incomingLLIntCalls.begin()->unlink();
1848 #if ENABLE(JIT)
1849     while (m_incomingCalls.begin() != m_incomingCalls.end())
1850         m_incomingCalls.begin()->unlink(*vm());
1851     while (m_incomingPolymorphicCalls.begin() != m_incomingPolymorphicCalls.end())
1852         m_incomingPolymorphicCalls.begin()->unlink(*vm());
1853 #endif // ENABLE(JIT)
1854 }
1855
1856 void CodeBlock::linkIncomingCall(ExecState* callerFrame, LLIntCallLinkInfo* incoming)
1857 {
1858     noticeIncomingCall(callerFrame);
1859     m_incomingLLIntCalls.push(incoming);
1860 }
1861
1862 CodeBlock* CodeBlock::newReplacement()
1863 {
1864     return ownerScriptExecutable()->newReplacementCodeBlockFor(specializationKind());
1865 }
1866
1867 #if ENABLE(JIT)
1868 CodeBlock* CodeBlock::replacement()
1869 {
1870     const ClassInfo* classInfo = this->classInfo(*vm());
1871
1872     if (classInfo == FunctionCodeBlock::info())
1873         return jsCast<FunctionExecutable*>(ownerExecutable())->codeBlockFor(m_isConstructor ? CodeForConstruct : CodeForCall);
1874
1875     if (classInfo == EvalCodeBlock::info())
1876         return jsCast<EvalExecutable*>(ownerExecutable())->codeBlock();
1877
1878     if (classInfo == ProgramCodeBlock::info())
1879         return jsCast<ProgramExecutable*>(ownerExecutable())->codeBlock();
1880
1881     if (classInfo == ModuleProgramCodeBlock::info())
1882         return jsCast<ModuleProgramExecutable*>(ownerExecutable())->codeBlock();
1883
1884     RELEASE_ASSERT_NOT_REACHED();
1885     return nullptr;
1886 }
1887
1888 DFG::CapabilityLevel CodeBlock::computeCapabilityLevel()
1889 {
1890     const ClassInfo* classInfo = this->classInfo(*vm());
1891
1892     if (classInfo == FunctionCodeBlock::info()) {
1893         if (m_isConstructor)
1894             return DFG::functionForConstructCapabilityLevel(this);
1895         return DFG::functionForCallCapabilityLevel(this);
1896     }
1897
1898     if (classInfo == EvalCodeBlock::info())
1899         return DFG::evalCapabilityLevel(this);
1900
1901     if (classInfo == ProgramCodeBlock::info())
1902         return DFG::programCapabilityLevel(this);
1903
1904     if (classInfo == ModuleProgramCodeBlock::info())
1905         return DFG::programCapabilityLevel(this);
1906
1907     RELEASE_ASSERT_NOT_REACHED();
1908     return DFG::CannotCompile;
1909 }
1910
1911 #endif // ENABLE(JIT)
1912
1913 void CodeBlock::jettison(Profiler::JettisonReason reason, ReoptimizationMode mode, const FireDetail* detail)
1914 {
1915 #if !ENABLE(DFG_JIT)
1916     UNUSED_PARAM(mode);
1917     UNUSED_PARAM(detail);
1918 #endif
1919     
1920     CODEBLOCK_LOG_EVENT(this, "jettison", ("due to ", reason, ", counting = ", mode == CountReoptimization, ", detail = ", pointerDump(detail)));
1921
1922     RELEASE_ASSERT(reason != Profiler::NotJettisoned);
1923     
1924 #if ENABLE(DFG_JIT)
1925     if (DFG::shouldDumpDisassembly()) {
1926         dataLog("Jettisoning ", *this);
1927         if (mode == CountReoptimization)
1928             dataLog(" and counting reoptimization");
1929         dataLog(" due to ", reason);
1930         if (detail)
1931             dataLog(", ", *detail);
1932         dataLog(".\n");
1933     }
1934     
1935     if (reason == Profiler::JettisonDueToWeakReference) {
1936         if (DFG::shouldDumpDisassembly()) {
1937             dataLog(*this, " will be jettisoned because of the following dead references:\n");
1938             DFG::CommonData* dfgCommon = m_jitCode->dfgCommon();
1939             for (auto& transition : dfgCommon->transitions) {
1940                 JSCell* origin = transition.m_codeOrigin.get();
1941                 JSCell* from = transition.m_from.get();
1942                 JSCell* to = transition.m_to.get();
1943                 if ((!origin || Heap::isMarked(origin)) && Heap::isMarked(from))
1944                     continue;
1945                 dataLog("    Transition under ", RawPointer(origin), ", ", RawPointer(from), " -> ", RawPointer(to), ".\n");
1946             }
1947             for (unsigned i = 0; i < dfgCommon->weakReferences.size(); ++i) {
1948                 JSCell* weak = dfgCommon->weakReferences[i].get();
1949                 if (Heap::isMarked(weak))
1950                     continue;
1951                 dataLog("    Weak reference ", RawPointer(weak), ".\n");
1952             }
1953         }
1954     }
1955 #endif // ENABLE(DFG_JIT)
1956
1957     DeferGCForAWhile deferGC(*heap());
1958     
1959     // We want to accomplish two things here:
1960     // 1) Make sure that if this CodeBlock is on the stack right now, then if we return to it
1961     //    we should OSR exit at the top of the next bytecode instruction after the return.
1962     // 2) Make sure that if we call the owner executable, then we shouldn't call this CodeBlock.
1963
1964 #if ENABLE(DFG_JIT)
1965     if (reason != Profiler::JettisonDueToOldAge) {
1966         Profiler::Compilation* compilation = jitCode()->dfgCommon()->compilation.get();
1967         if (UNLIKELY(compilation))
1968             compilation->setJettisonReason(reason, detail);
1969         
1970         // This accomplishes (1), and does its own book-keeping about whether it has already happened.
1971         if (!jitCode()->dfgCommon()->invalidate()) {
1972             // We've already been invalidated.
1973             RELEASE_ASSERT(this != replacement() || (m_vm->heap.isCurrentThreadBusy() && !Heap::isMarked(ownerScriptExecutable())));
1974             return;
1975         }
1976     }
1977     
1978     if (DFG::shouldDumpDisassembly())
1979         dataLog("    Did invalidate ", *this, "\n");
1980     
1981     // Count the reoptimization if that's what the user wanted.
1982     if (mode == CountReoptimization) {
1983         // FIXME: Maybe this should call alternative().
1984         // https://bugs.webkit.org/show_bug.cgi?id=123677
1985         baselineAlternative()->countReoptimization();
1986         if (DFG::shouldDumpDisassembly())
1987             dataLog("    Did count reoptimization for ", *this, "\n");
1988     }
1989     
1990     if (this != replacement()) {
1991         // This means that we were never the entrypoint. This can happen for OSR entry code
1992         // blocks.
1993         return;
1994     }
1995
1996     if (alternative())
1997         alternative()->optimizeAfterWarmUp();
1998
1999     if (reason != Profiler::JettisonDueToOldAge && reason != Profiler::JettisonDueToVMTraps)
2000         tallyFrequentExitSites();
2001 #endif // ENABLE(DFG_JIT)
2002
2003     // Jettison can happen during GC. We don't want to install code to a dead executable
2004     // because that would add a dead object to the remembered set.
2005     if (m_vm->heap.isCurrentThreadBusy() && !Heap::isMarked(ownerScriptExecutable()))
2006         return;
2007
2008     // This accomplishes (2).
2009     ownerScriptExecutable()->installCode(
2010         *m_vm, alternative(), codeType(), specializationKind());
2011
2012 #if ENABLE(DFG_JIT)
2013     if (DFG::shouldDumpDisassembly())
2014         dataLog("    Did install baseline version of ", *this, "\n");
2015 #endif // ENABLE(DFG_JIT)
2016 }
2017
2018 JSGlobalObject* CodeBlock::globalObjectFor(CodeOrigin codeOrigin)
2019 {
2020     if (!codeOrigin.inlineCallFrame)
2021         return globalObject();
2022     return codeOrigin.inlineCallFrame->baselineCodeBlock->globalObject();
2023 }
2024
2025 class RecursionCheckFunctor {
2026 public:
2027     RecursionCheckFunctor(CallFrame* startCallFrame, CodeBlock* codeBlock, unsigned depthToCheck)
2028         : m_startCallFrame(startCallFrame)
2029         , m_codeBlock(codeBlock)
2030         , m_depthToCheck(depthToCheck)
2031         , m_foundStartCallFrame(false)
2032         , m_didRecurse(false)
2033     { }
2034
2035     StackVisitor::Status operator()(StackVisitor& visitor) const
2036     {
2037         CallFrame* currentCallFrame = visitor->callFrame();
2038
2039         if (currentCallFrame == m_startCallFrame)
2040             m_foundStartCallFrame = true;
2041
2042         if (m_foundStartCallFrame) {
2043             if (visitor->callFrame()->codeBlock() == m_codeBlock) {
2044                 m_didRecurse = true;
2045                 return StackVisitor::Done;
2046             }
2047
2048             if (!m_depthToCheck--)
2049                 return StackVisitor::Done;
2050         }
2051
2052         return StackVisitor::Continue;
2053     }
2054
2055     bool didRecurse() const { return m_didRecurse; }
2056
2057 private:
2058     CallFrame* m_startCallFrame;
2059     CodeBlock* m_codeBlock;
2060     mutable unsigned m_depthToCheck;
2061     mutable bool m_foundStartCallFrame;
2062     mutable bool m_didRecurse;
2063 };
2064
2065 void CodeBlock::noticeIncomingCall(ExecState* callerFrame)
2066 {
2067     CodeBlock* callerCodeBlock = callerFrame->codeBlock();
2068     
2069     if (Options::verboseCallLink())
2070         dataLog("Noticing call link from ", pointerDump(callerCodeBlock), " to ", *this, "\n");
2071     
2072 #if ENABLE(DFG_JIT)
2073     if (!m_shouldAlwaysBeInlined)
2074         return;
2075     
2076     if (!callerCodeBlock) {
2077         m_shouldAlwaysBeInlined = false;
2078         if (Options::verboseCallLink())
2079             dataLog("    Clearing SABI because caller is native.\n");
2080         return;
2081     }
2082
2083     if (!hasBaselineJITProfiling())
2084         return;
2085
2086     if (!DFG::mightInlineFunction(this))
2087         return;
2088
2089     if (!canInline(capabilityLevelState()))
2090         return;
2091     
2092     if (!DFG::isSmallEnoughToInlineCodeInto(callerCodeBlock)) {
2093         m_shouldAlwaysBeInlined = false;
2094         if (Options::verboseCallLink())
2095             dataLog("    Clearing SABI because caller is too large.\n");
2096         return;
2097     }
2098
2099     if (callerCodeBlock->jitType() == JITCode::InterpreterThunk) {
2100         // If the caller is still in the interpreter, then we can't expect inlining to
2101         // happen anytime soon. Assume it's profitable to optimize it separately. This
2102         // ensures that a function is SABI only if it is called no more frequently than
2103         // any of its callers.
2104         m_shouldAlwaysBeInlined = false;
2105         if (Options::verboseCallLink())
2106             dataLog("    Clearing SABI because caller is in LLInt.\n");
2107         return;
2108     }
2109     
2110     if (JITCode::isOptimizingJIT(callerCodeBlock->jitType())) {
2111         m_shouldAlwaysBeInlined = false;
2112         if (Options::verboseCallLink())
2113             dataLog("    Clearing SABI bcause caller was already optimized.\n");
2114         return;
2115     }
2116     
2117     if (callerCodeBlock->codeType() != FunctionCode) {
2118         // If the caller is either eval or global code, assume that that won't be
2119         // optimized anytime soon. For eval code this is particularly true since we
2120         // delay eval optimization by a *lot*.
2121         m_shouldAlwaysBeInlined = false;
2122         if (Options::verboseCallLink())
2123             dataLog("    Clearing SABI because caller is not a function.\n");
2124         return;
2125     }
2126
2127     // Recursive calls won't be inlined.
2128     RecursionCheckFunctor functor(callerFrame, this, Options::maximumInliningDepth());
2129     vm()->topCallFrame->iterate(functor);
2130
2131     if (functor.didRecurse()) {
2132         if (Options::verboseCallLink())
2133             dataLog("    Clearing SABI because recursion was detected.\n");
2134         m_shouldAlwaysBeInlined = false;
2135         return;
2136     }
2137     
2138     if (callerCodeBlock->capabilityLevelState() == DFG::CapabilityLevelNotSet) {
2139         dataLog("In call from ", FullCodeOrigin(callerCodeBlock, callerFrame->codeOrigin()), " to ", *this, ": caller's DFG capability level is not set.\n");
2140         CRASH();
2141     }
2142     
2143     if (canCompile(callerCodeBlock->capabilityLevelState()))
2144         return;
2145     
2146     if (Options::verboseCallLink())
2147         dataLog("    Clearing SABI because the caller is not a DFG candidate.\n");
2148     
2149     m_shouldAlwaysBeInlined = false;
2150 #endif
2151 }
2152
2153 unsigned CodeBlock::reoptimizationRetryCounter() const
2154 {
2155 #if ENABLE(JIT)
2156     ASSERT(m_reoptimizationRetryCounter <= Options::reoptimizationRetryCounterMax());
2157     return m_reoptimizationRetryCounter;
2158 #else
2159     return 0;
2160 #endif // ENABLE(JIT)
2161 }
2162
2163 #if ENABLE(JIT)
2164 void CodeBlock::setCalleeSaveRegisters(RegisterSet calleeSaveRegisters)
2165 {
2166     m_calleeSaveRegisters = std::make_unique<RegisterAtOffsetList>(calleeSaveRegisters);
2167 }
2168
2169 void CodeBlock::setCalleeSaveRegisters(std::unique_ptr<RegisterAtOffsetList> registerAtOffsetList)
2170 {
2171     m_calleeSaveRegisters = WTFMove(registerAtOffsetList);
2172 }
2173     
2174 static size_t roundCalleeSaveSpaceAsVirtualRegisters(size_t calleeSaveRegisters)
2175 {
2176     static const unsigned cpuRegisterSize = sizeof(void*);
2177     return (WTF::roundUpToMultipleOf(sizeof(Register), calleeSaveRegisters * cpuRegisterSize) / sizeof(Register));
2178
2179 }
2180
2181 size_t CodeBlock::llintBaselineCalleeSaveSpaceAsVirtualRegisters()
2182 {
2183     return roundCalleeSaveSpaceAsVirtualRegisters(numberOfLLIntBaselineCalleeSaveRegisters());
2184 }
2185
2186 size_t CodeBlock::calleeSaveSpaceAsVirtualRegisters()
2187 {
2188     return roundCalleeSaveSpaceAsVirtualRegisters(m_calleeSaveRegisters->size());
2189 }
2190
2191 void CodeBlock::countReoptimization()
2192 {
2193     m_reoptimizationRetryCounter++;
2194     if (m_reoptimizationRetryCounter > Options::reoptimizationRetryCounterMax())
2195         m_reoptimizationRetryCounter = Options::reoptimizationRetryCounterMax();
2196 }
2197
2198 unsigned CodeBlock::numberOfDFGCompiles()
2199 {
2200     ASSERT(JITCode::isBaselineCode(jitType()));
2201     if (Options::testTheFTL()) {
2202         if (m_didFailFTLCompilation)
2203             return 1000000;
2204         return (m_hasBeenCompiledWithFTL ? 1 : 0) + m_reoptimizationRetryCounter;
2205     }
2206     return (JITCode::isOptimizingJIT(replacement()->jitType()) ? 1 : 0) + m_reoptimizationRetryCounter;
2207 }
2208
2209 int32_t CodeBlock::codeTypeThresholdMultiplier() const
2210 {
2211     if (codeType() == EvalCode)
2212         return Options::evalThresholdMultiplier();
2213     
2214     return 1;
2215 }
2216
2217 double CodeBlock::optimizationThresholdScalingFactor()
2218 {
2219     // This expression arises from doing a least-squares fit of
2220     //
2221     // F[x_] =: a * Sqrt[x + b] + Abs[c * x] + d
2222     //
2223     // against the data points:
2224     //
2225     //    x       F[x_]
2226     //    10       0.9          (smallest reasonable code block)
2227     //   200       1.0          (typical small-ish code block)
2228     //   320       1.2          (something I saw in 3d-cube that I wanted to optimize)
2229     //  1268       5.0          (something I saw in 3d-cube that I didn't want to optimize)
2230     //  4000       5.5          (random large size, used to cause the function to converge to a shallow curve of some sort)
2231     // 10000       6.0          (similar to above)
2232     //
2233     // I achieve the minimization using the following Mathematica code:
2234     //
2235     // MyFunctionTemplate[x_, a_, b_, c_, d_] := a*Sqrt[x + b] + Abs[c*x] + d
2236     //
2237     // samples = {{10, 0.9}, {200, 1}, {320, 1.2}, {1268, 5}, {4000, 5.5}, {10000, 6}}
2238     //
2239     // solution = 
2240     //     Minimize[Plus @@ ((MyFunctionTemplate[#[[1]], a, b, c, d] - #[[2]])^2 & /@ samples),
2241     //         {a, b, c, d}][[2]]
2242     //
2243     // And the code below (to initialize a, b, c, d) is generated by:
2244     //
2245     // Print["const double " <> ToString[#[[1]]] <> " = " <>
2246     //     If[#[[2]] < 0.00001, "0.0", ToString[#[[2]]]] <> ";"] & /@ solution
2247     //
2248     // We've long known the following to be true:
2249     // - Small code blocks are cheap to optimize and so we should do it sooner rather
2250     //   than later.
2251     // - Large code blocks are expensive to optimize and so we should postpone doing so,
2252     //   and sometimes have a large enough threshold that we never optimize them.
2253     // - The difference in cost is not totally linear because (a) just invoking the
2254     //   DFG incurs some base cost and (b) for large code blocks there is enough slop
2255     //   in the correlation between instruction count and the actual compilation cost
2256     //   that for those large blocks, the instruction count should not have a strong
2257     //   influence on our threshold.
2258     //
2259     // I knew the goals but I didn't know how to achieve them; so I picked an interesting
2260     // example where the heuristics were right (code block in 3d-cube with instruction
2261     // count 320, which got compiled early as it should have been) and one where they were
2262     // totally wrong (code block in 3d-cube with instruction count 1268, which was expensive
2263     // to compile and didn't run often enough to warrant compilation in my opinion), and
2264     // then threw in additional data points that represented my own guess of what our
2265     // heuristics should do for some round-numbered examples.
2266     //
2267     // The expression to which I decided to fit the data arose because I started with an
2268     // affine function, and then did two things: put the linear part in an Abs to ensure
2269     // that the fit didn't end up choosing a negative value of c (which would result in
2270     // the function turning over and going negative for large x) and I threw in a Sqrt
2271     // term because Sqrt represents my intution that the function should be more sensitive
2272     // to small changes in small values of x, but less sensitive when x gets large.
2273     
2274     // Note that the current fit essentially eliminates the linear portion of the
2275     // expression (c == 0.0).
2276     const double a = 0.061504;
2277     const double b = 1.02406;
2278     const double c = 0.0;
2279     const double d = 0.825914;
2280     
2281     double instructionCount = this->instructionCount();
2282     
2283     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.
2284     
2285     double result = d + a * sqrt(instructionCount + b) + c * instructionCount;
2286     
2287     result *= codeTypeThresholdMultiplier();
2288     
2289     if (Options::verboseOSR()) {
2290         dataLog(
2291             *this, ": instruction count is ", instructionCount,
2292             ", scaling execution counter by ", result, " * ", codeTypeThresholdMultiplier(),
2293             "\n");
2294     }
2295     return result;
2296 }
2297
2298 static int32_t clipThreshold(double threshold)
2299 {
2300     if (threshold < 1.0)
2301         return 1;
2302     
2303     if (threshold > static_cast<double>(std::numeric_limits<int32_t>::max()))
2304         return std::numeric_limits<int32_t>::max();
2305     
2306     return static_cast<int32_t>(threshold);
2307 }
2308
2309 int32_t CodeBlock::adjustedCounterValue(int32_t desiredThreshold)
2310 {
2311     return clipThreshold(
2312         static_cast<double>(desiredThreshold) *
2313         optimizationThresholdScalingFactor() *
2314         (1 << reoptimizationRetryCounter()));
2315 }
2316
2317 bool CodeBlock::checkIfOptimizationThresholdReached()
2318 {
2319 #if ENABLE(DFG_JIT)
2320     if (DFG::Worklist* worklist = DFG::existingGlobalDFGWorklistOrNull()) {
2321         if (worklist->compilationState(DFG::CompilationKey(this, DFG::DFGMode))
2322             == DFG::Worklist::Compiled) {
2323             optimizeNextInvocation();
2324             return true;
2325         }
2326     }
2327 #endif
2328     
2329     return m_jitExecuteCounter.checkIfThresholdCrossedAndSet(this);
2330 }
2331
2332 #if ENABLE(DFG_JIT)
2333 auto CodeBlock::updateOSRExitCounterAndCheckIfNeedToReoptimize(DFG::OSRExitState& exitState) -> OptimizeAction
2334 {
2335     DFG::OSRExitBase& exit = exitState.exit;
2336     if (!exitKindMayJettison(exit.m_kind)) {
2337         // FIXME: We may want to notice that we're frequently exiting
2338         // at an op_catch that we didn't compile an entrypoint for, and
2339         // then trigger a reoptimization of this CodeBlock:
2340         // https://bugs.webkit.org/show_bug.cgi?id=175842
2341         return OptimizeAction::None;
2342     }
2343
2344     exit.m_count++;
2345     m_osrExitCounter++;
2346
2347     CodeBlock* baselineCodeBlock = exitState.baselineCodeBlock;
2348     ASSERT(baselineCodeBlock == baselineAlternative());
2349     if (UNLIKELY(baselineCodeBlock->jitExecuteCounter().hasCrossedThreshold()))
2350         return OptimizeAction::ReoptimizeNow;
2351
2352     // We want to figure out if there's a possibility that we're in a loop. For the outermost
2353     // code block in the inline stack, we handle this appropriately by having the loop OSR trigger
2354     // check the exit count of the replacement of the CodeBlock from which we are OSRing. The
2355     // problem is the inlined functions, which might also have loops, but whose baseline versions
2356     // don't know where to look for the exit count. Figure out if those loops are severe enough
2357     // that we had tried to OSR enter. If so, then we should use the loop reoptimization trigger.
2358     // Otherwise, we should use the normal reoptimization trigger.
2359
2360     bool didTryToEnterInLoop = false;
2361     for (InlineCallFrame* inlineCallFrame = exit.m_codeOrigin.inlineCallFrame; inlineCallFrame; inlineCallFrame = inlineCallFrame->directCaller.inlineCallFrame) {
2362         if (inlineCallFrame->baselineCodeBlock->ownerScriptExecutable()->didTryToEnterInLoop()) {
2363             didTryToEnterInLoop = true;
2364             break;
2365         }
2366     }
2367
2368     uint32_t exitCountThreshold = didTryToEnterInLoop
2369         ? exitCountThresholdForReoptimizationFromLoop()
2370         : exitCountThresholdForReoptimization();
2371
2372     if (m_osrExitCounter > exitCountThreshold)
2373         return OptimizeAction::ReoptimizeNow;
2374
2375     // Too few fails. Adjust the execution counter such that the target is to only optimize after a while.
2376     baselineCodeBlock->m_jitExecuteCounter.setNewThresholdForOSRExit(exitState.activeThreshold, exitState.memoryUsageAdjustedThreshold);
2377     return OptimizeAction::None;
2378 }
2379 #endif
2380
2381 void CodeBlock::optimizeNextInvocation()
2382 {
2383     if (Options::verboseOSR())
2384         dataLog(*this, ": Optimizing next invocation.\n");
2385     m_jitExecuteCounter.setNewThreshold(0, this);
2386 }
2387
2388 void CodeBlock::dontOptimizeAnytimeSoon()
2389 {
2390     if (Options::verboseOSR())
2391         dataLog(*this, ": Not optimizing anytime soon.\n");
2392     m_jitExecuteCounter.deferIndefinitely();
2393 }
2394
2395 void CodeBlock::optimizeAfterWarmUp()
2396 {
2397     if (Options::verboseOSR())
2398         dataLog(*this, ": Optimizing after warm-up.\n");
2399 #if ENABLE(DFG_JIT)
2400     m_jitExecuteCounter.setNewThreshold(
2401         adjustedCounterValue(Options::thresholdForOptimizeAfterWarmUp()), this);
2402 #endif
2403 }
2404
2405 void CodeBlock::optimizeAfterLongWarmUp()
2406 {
2407     if (Options::verboseOSR())
2408         dataLog(*this, ": Optimizing after long warm-up.\n");
2409 #if ENABLE(DFG_JIT)
2410     m_jitExecuteCounter.setNewThreshold(
2411         adjustedCounterValue(Options::thresholdForOptimizeAfterLongWarmUp()), this);
2412 #endif
2413 }
2414
2415 void CodeBlock::optimizeSoon()
2416 {
2417     if (Options::verboseOSR())
2418         dataLog(*this, ": Optimizing soon.\n");
2419 #if ENABLE(DFG_JIT)
2420     m_jitExecuteCounter.setNewThreshold(
2421         adjustedCounterValue(Options::thresholdForOptimizeSoon()), this);
2422 #endif
2423 }
2424
2425 void CodeBlock::forceOptimizationSlowPathConcurrently()
2426 {
2427     if (Options::verboseOSR())
2428         dataLog(*this, ": Forcing slow path concurrently.\n");
2429     m_jitExecuteCounter.forceSlowPathConcurrently();
2430 }
2431
2432 #if ENABLE(DFG_JIT)
2433 void CodeBlock::setOptimizationThresholdBasedOnCompilationResult(CompilationResult result)
2434 {
2435     JITCode::JITType type = jitType();
2436     if (type != JITCode::BaselineJIT) {
2437         dataLog(*this, ": expected to have baseline code but have ", type, "\n");
2438         RELEASE_ASSERT_NOT_REACHED();
2439     }
2440     
2441     CodeBlock* theReplacement = replacement();
2442     if ((result == CompilationSuccessful) != (theReplacement != this)) {
2443         dataLog(*this, ": we have result = ", result, " but ");
2444         if (theReplacement == this)
2445             dataLog("we are our own replacement.\n");
2446         else
2447             dataLog("our replacement is ", pointerDump(theReplacement), "\n");
2448         RELEASE_ASSERT_NOT_REACHED();
2449     }
2450     
2451     switch (result) {
2452     case CompilationSuccessful:
2453         RELEASE_ASSERT(JITCode::isOptimizingJIT(replacement()->jitType()));
2454         optimizeNextInvocation();
2455         return;
2456     case CompilationFailed:
2457         dontOptimizeAnytimeSoon();
2458         return;
2459     case CompilationDeferred:
2460         // We'd like to do dontOptimizeAnytimeSoon() but we cannot because
2461         // forceOptimizationSlowPathConcurrently() is inherently racy. It won't
2462         // necessarily guarantee anything. So, we make sure that even if that
2463         // function ends up being a no-op, we still eventually retry and realize
2464         // that we have optimized code ready.
2465         optimizeAfterWarmUp();
2466         return;
2467     case CompilationInvalidated:
2468         // Retry with exponential backoff.
2469         countReoptimization();
2470         optimizeAfterWarmUp();
2471         return;
2472     }
2473     
2474     dataLog("Unrecognized result: ", static_cast<int>(result), "\n");
2475     RELEASE_ASSERT_NOT_REACHED();
2476 }
2477
2478 #endif
2479     
2480 uint32_t CodeBlock::adjustedExitCountThreshold(uint32_t desiredThreshold)
2481 {
2482     ASSERT(JITCode::isOptimizingJIT(jitType()));
2483     // Compute this the lame way so we don't saturate. This is called infrequently
2484     // enough that this loop won't hurt us.
2485     unsigned result = desiredThreshold;
2486     for (unsigned n = baselineVersion()->reoptimizationRetryCounter(); n--;) {
2487         unsigned newResult = result << 1;
2488         if (newResult < result)
2489             return std::numeric_limits<uint32_t>::max();
2490         result = newResult;
2491     }
2492     return result;
2493 }
2494
2495 uint32_t CodeBlock::exitCountThresholdForReoptimization()
2496 {
2497     return adjustedExitCountThreshold(Options::osrExitCountForReoptimization() * codeTypeThresholdMultiplier());
2498 }
2499
2500 uint32_t CodeBlock::exitCountThresholdForReoptimizationFromLoop()
2501 {
2502     return adjustedExitCountThreshold(Options::osrExitCountForReoptimizationFromLoop() * codeTypeThresholdMultiplier());
2503 }
2504
2505 bool CodeBlock::shouldReoptimizeNow()
2506 {
2507     return osrExitCounter() >= exitCountThresholdForReoptimization();
2508 }
2509
2510 bool CodeBlock::shouldReoptimizeFromLoopNow()
2511 {
2512     return osrExitCounter() >= exitCountThresholdForReoptimizationFromLoop();
2513 }
2514 #endif
2515
2516 ArrayProfile* CodeBlock::getArrayProfile(const ConcurrentJSLocker&, unsigned bytecodeOffset)
2517 {
2518     for (auto& m_arrayProfile : m_arrayProfiles) {
2519         if (m_arrayProfile.bytecodeOffset() == bytecodeOffset)
2520             return &m_arrayProfile;
2521     }
2522     return 0;
2523 }
2524
2525 ArrayProfile* CodeBlock::getArrayProfile(unsigned bytecodeOffset)
2526 {
2527     ConcurrentJSLocker locker(m_lock);
2528     return getArrayProfile(locker, bytecodeOffset);
2529 }
2530
2531 ArrayProfile* CodeBlock::addArrayProfile(const ConcurrentJSLocker&, unsigned bytecodeOffset)
2532 {
2533     m_arrayProfiles.append(ArrayProfile(bytecodeOffset));
2534     return &m_arrayProfiles.last();
2535 }
2536
2537 ArrayProfile* CodeBlock::addArrayProfile(unsigned bytecodeOffset)
2538 {
2539     ConcurrentJSLocker locker(m_lock);
2540     return addArrayProfile(locker, bytecodeOffset);
2541 }
2542
2543 ArrayProfile* CodeBlock::getOrAddArrayProfile(const ConcurrentJSLocker& locker, unsigned bytecodeOffset)
2544 {
2545     ArrayProfile* result = getArrayProfile(locker, bytecodeOffset);
2546     if (result)
2547         return result;
2548     return addArrayProfile(locker, bytecodeOffset);
2549 }
2550
2551 ArrayProfile* CodeBlock::getOrAddArrayProfile(unsigned bytecodeOffset)
2552 {
2553     ConcurrentJSLocker locker(m_lock);
2554     return getOrAddArrayProfile(locker, bytecodeOffset);
2555 }
2556
2557 #if ENABLE(DFG_JIT)
2558 Vector<CodeOrigin, 0, UnsafeVectorOverflow>& CodeBlock::codeOrigins()
2559 {
2560     return m_jitCode->dfgCommon()->codeOrigins;
2561 }
2562
2563 size_t CodeBlock::numberOfDFGIdentifiers() const
2564 {
2565     if (!JITCode::isOptimizingJIT(jitType()))
2566         return 0;
2567     
2568     return m_jitCode->dfgCommon()->dfgIdentifiers.size();
2569 }
2570
2571 const Identifier& CodeBlock::identifier(int index) const
2572 {
2573     size_t unlinkedIdentifiers = m_unlinkedCode->numberOfIdentifiers();
2574     if (static_cast<unsigned>(index) < unlinkedIdentifiers)
2575         return m_unlinkedCode->identifier(index);
2576     ASSERT(JITCode::isOptimizingJIT(jitType()));
2577     return m_jitCode->dfgCommon()->dfgIdentifiers[index - unlinkedIdentifiers];
2578 }
2579 #endif // ENABLE(DFG_JIT)
2580
2581 void CodeBlock::updateAllPredictionsAndCountLiveness(unsigned& numberOfLiveNonArgumentValueProfiles, unsigned& numberOfSamplesInProfiles)
2582 {
2583     ConcurrentJSLocker locker(m_lock);
2584
2585     numberOfLiveNonArgumentValueProfiles = 0;
2586     numberOfSamplesInProfiles = 0; // If this divided by ValueProfile::numberOfBuckets equals numberOfValueProfiles() then value profiles are full.
2587
2588     for (unsigned i = 0; i < totalNumberOfValueProfiles(); ++i) {
2589         ValueProfile& profile = getFromAllValueProfiles(i);
2590         unsigned numSamples = profile.totalNumberOfSamples();
2591         if (numSamples > ValueProfile::numberOfBuckets)
2592             numSamples = ValueProfile::numberOfBuckets; // We don't want profiles that are extremely hot to be given more weight.
2593         numberOfSamplesInProfiles += numSamples;
2594         if (profile.m_bytecodeOffset < 0) {
2595             profile.computeUpdatedPrediction(locker);
2596             continue;
2597         }
2598         if (profile.numberOfSamples() || profile.m_prediction != SpecNone)
2599             numberOfLiveNonArgumentValueProfiles++;
2600         profile.computeUpdatedPrediction(locker);
2601     }
2602
2603     for (auto& profileBucket : m_catchProfiles) {
2604         profileBucket->forEach([&] (ValueProfileAndOperand& profile) {
2605             profile.m_profile.computeUpdatedPrediction(locker);
2606         });
2607     }
2608     
2609 #if ENABLE(DFG_JIT)
2610     m_lazyOperandValueProfiles.computeUpdatedPredictions(locker);
2611 #endif
2612 }
2613
2614 void CodeBlock::updateAllValueProfilePredictions()
2615 {
2616     unsigned ignoredValue1, ignoredValue2;
2617     updateAllPredictionsAndCountLiveness(ignoredValue1, ignoredValue2);
2618 }
2619
2620 void CodeBlock::updateAllArrayPredictions()
2621 {
2622     ConcurrentJSLocker locker(m_lock);
2623     
2624     for (unsigned i = m_arrayProfiles.size(); i--;)
2625         m_arrayProfiles[i].computeUpdatedPrediction(locker, this);
2626     
2627     // Don't count these either, for similar reasons.
2628     for (unsigned i = m_arrayAllocationProfiles.size(); i--;)
2629         m_arrayAllocationProfiles[i].updateProfile();
2630 }
2631
2632 void CodeBlock::updateAllPredictions()
2633 {
2634     updateAllValueProfilePredictions();
2635     updateAllArrayPredictions();
2636 }
2637
2638 bool CodeBlock::shouldOptimizeNow()
2639 {
2640     if (Options::verboseOSR())
2641         dataLog("Considering optimizing ", *this, "...\n");
2642
2643     if (m_optimizationDelayCounter >= Options::maximumOptimizationDelay())
2644         return true;
2645     
2646     updateAllArrayPredictions();
2647     
2648     unsigned numberOfLiveNonArgumentValueProfiles;
2649     unsigned numberOfSamplesInProfiles;
2650     updateAllPredictionsAndCountLiveness(numberOfLiveNonArgumentValueProfiles, numberOfSamplesInProfiles);
2651
2652     if (Options::verboseOSR()) {
2653         dataLogF(
2654             "Profile hotness: %lf (%u / %u), %lf (%u / %u)\n",
2655             (double)numberOfLiveNonArgumentValueProfiles / numberOfValueProfiles(),
2656             numberOfLiveNonArgumentValueProfiles, numberOfValueProfiles(),
2657             (double)numberOfSamplesInProfiles / ValueProfile::numberOfBuckets / numberOfValueProfiles(),
2658             numberOfSamplesInProfiles, ValueProfile::numberOfBuckets * numberOfValueProfiles());
2659     }
2660
2661     if ((!numberOfValueProfiles() || (double)numberOfLiveNonArgumentValueProfiles / numberOfValueProfiles() >= Options::desiredProfileLivenessRate())
2662         && (!totalNumberOfValueProfiles() || (double)numberOfSamplesInProfiles / ValueProfile::numberOfBuckets / totalNumberOfValueProfiles() >= Options::desiredProfileFullnessRate())
2663         && static_cast<unsigned>(m_optimizationDelayCounter) + 1 >= Options::minimumOptimizationDelay())
2664         return true;
2665     
2666     ASSERT(m_optimizationDelayCounter < std::numeric_limits<uint8_t>::max());
2667     m_optimizationDelayCounter++;
2668     optimizeAfterWarmUp();
2669     return false;
2670 }
2671
2672 #if ENABLE(DFG_JIT)
2673 void CodeBlock::tallyFrequentExitSites()
2674 {
2675     ASSERT(JITCode::isOptimizingJIT(jitType()));
2676     ASSERT(alternative()->jitType() == JITCode::BaselineJIT);
2677     
2678     CodeBlock* profiledBlock = alternative();
2679     
2680     switch (jitType()) {
2681     case JITCode::DFGJIT: {
2682         DFG::JITCode* jitCode = m_jitCode->dfg();
2683         for (auto& exit : jitCode->osrExit)
2684             exit.considerAddingAsFrequentExitSite(profiledBlock);
2685         break;
2686     }
2687
2688 #if ENABLE(FTL_JIT)
2689     case JITCode::FTLJIT: {
2690         // There is no easy way to avoid duplicating this code since the FTL::JITCode::osrExit
2691         // vector contains a totally different type, that just so happens to behave like
2692         // DFG::JITCode::osrExit.
2693         FTL::JITCode* jitCode = m_jitCode->ftl();
2694         for (unsigned i = 0; i < jitCode->osrExit.size(); ++i) {
2695             FTL::OSRExit& exit = jitCode->osrExit[i];
2696             exit.considerAddingAsFrequentExitSite(profiledBlock);
2697         }
2698         break;
2699     }
2700 #endif
2701         
2702     default:
2703         RELEASE_ASSERT_NOT_REACHED();
2704         break;
2705     }
2706 }
2707 #endif // ENABLE(DFG_JIT)
2708
2709 #if ENABLE(VERBOSE_VALUE_PROFILE)
2710 void CodeBlock::dumpValueProfiles()
2711 {
2712     dataLog("ValueProfile for ", *this, ":\n");
2713     for (unsigned i = 0; i < totalNumberOfValueProfiles(); ++i) {
2714         ValueProfile& profile = getFromAllValueProfiles(i);
2715         if (profile.m_bytecodeOffset < 0) {
2716             ASSERT(profile.m_bytecodeOffset == -1);
2717             dataLogF("   arg = %u: ", i);
2718         } else
2719             dataLogF("   bc = %d: ", profile.m_bytecodeOffset);
2720         if (!profile.numberOfSamples() && profile.m_prediction == SpecNone) {
2721             dataLogF("<empty>\n");
2722             continue;
2723         }
2724         profile.dump(WTF::dataFile());
2725         dataLogF("\n");
2726     }
2727     dataLog("RareCaseProfile for ", *this, ":\n");
2728     for (unsigned i = 0; i < numberOfRareCaseProfiles(); ++i) {
2729         RareCaseProfile* profile = rareCaseProfile(i);
2730         dataLogF("   bc = %d: %u\n", profile->m_bytecodeOffset, profile->m_counter);
2731     }
2732 }
2733 #endif // ENABLE(VERBOSE_VALUE_PROFILE)
2734
2735 unsigned CodeBlock::frameRegisterCount()
2736 {
2737     switch (jitType()) {
2738     case JITCode::InterpreterThunk:
2739         return LLInt::frameRegisterCountFor(this);
2740
2741 #if ENABLE(JIT)
2742     case JITCode::BaselineJIT:
2743         return JIT::frameRegisterCountFor(this);
2744 #endif // ENABLE(JIT)
2745
2746 #if ENABLE(DFG_JIT)
2747     case JITCode::DFGJIT:
2748     case JITCode::FTLJIT:
2749         return jitCode()->dfgCommon()->frameRegisterCount;
2750 #endif // ENABLE(DFG_JIT)
2751         
2752     default:
2753         RELEASE_ASSERT_NOT_REACHED();
2754         return 0;
2755     }
2756 }
2757
2758 int CodeBlock::stackPointerOffset()
2759 {
2760     return virtualRegisterForLocal(frameRegisterCount() - 1).offset();
2761 }
2762
2763 size_t CodeBlock::predictedMachineCodeSize()
2764 {
2765     // This will be called from CodeBlock::CodeBlock before either m_vm or the
2766     // instructions have been initialized. It's OK to return 0 because what will really
2767     // matter is the recomputation of this value when the slow path is triggered.
2768     if (!m_vm)
2769         return 0;
2770     
2771     if (!*m_vm->machineCodeBytesPerBytecodeWordForBaselineJIT)
2772         return 0; // It's as good of a prediction as we'll get.
2773     
2774     // Be conservative: return a size that will be an overestimation 84% of the time.
2775     double multiplier = m_vm->machineCodeBytesPerBytecodeWordForBaselineJIT->mean() +
2776         m_vm->machineCodeBytesPerBytecodeWordForBaselineJIT->standardDeviation();
2777     
2778     // Be paranoid: silently reject bogus multipiers. Silently doing the "wrong" thing
2779     // here is OK, since this whole method is just a heuristic.
2780     if (multiplier < 0 || multiplier > 1000)
2781         return 0;
2782     
2783     double doubleResult = multiplier * m_instructions.size();
2784     
2785     // Be even more paranoid: silently reject values that won't fit into a size_t. If
2786     // the function is so huge that we can't even fit it into virtual memory then we
2787     // should probably have some other guards in place to prevent us from even getting
2788     // to this point.
2789     if (doubleResult > std::numeric_limits<size_t>::max())
2790         return 0;
2791     
2792     return static_cast<size_t>(doubleResult);
2793 }
2794
2795 String CodeBlock::nameForRegister(VirtualRegister virtualRegister)
2796 {
2797     for (auto& constantRegister : m_constantRegisters) {
2798         if (constantRegister.get().isEmpty())
2799             continue;
2800         if (SymbolTable* symbolTable = jsDynamicCast<SymbolTable*>(*vm(), constantRegister.get())) {
2801             ConcurrentJSLocker locker(symbolTable->m_lock);
2802             auto end = symbolTable->end(locker);
2803             for (auto ptr = symbolTable->begin(locker); ptr != end; ++ptr) {
2804                 if (ptr->value.varOffset() == VarOffset(virtualRegister)) {
2805                     // FIXME: This won't work from the compilation thread.
2806                     // https://bugs.webkit.org/show_bug.cgi?id=115300
2807                     return ptr->key.get();
2808                 }
2809             }
2810         }
2811     }
2812     if (virtualRegister == thisRegister())
2813         return ASCIILiteral("this");
2814     if (virtualRegister.isArgument())
2815         return String::format("arguments[%3d]", virtualRegister.toArgument());
2816
2817     return "";
2818 }
2819
2820 ValueProfile* CodeBlock::tryGetValueProfileForBytecodeOffset(int bytecodeOffset)
2821 {
2822     return tryBinarySearch<ValueProfile, int>(
2823         m_valueProfiles, m_valueProfiles.size(), bytecodeOffset,
2824         getValueProfileBytecodeOffset<ValueProfile>);
2825 }
2826
2827 ValueProfile& CodeBlock::valueProfileForBytecodeOffset(int bytecodeOffset)
2828 {
2829     OpcodeID opcodeID = Interpreter::getOpcodeID(instructions()[bytecodeOffset]);
2830     unsigned length = opcodeLength(opcodeID);
2831     ASSERT(!!tryGetValueProfileForBytecodeOffset(bytecodeOffset));
2832     return *instructions()[bytecodeOffset + length - 1].u.profile;
2833 }
2834
2835 void CodeBlock::validate()
2836 {
2837     BytecodeLivenessAnalysis liveness(this); // Compute directly from scratch so it doesn't effect CodeBlock footprint.
2838     
2839     FastBitVector liveAtHead = liveness.getLivenessInfoAtBytecodeOffset(this, 0);
2840     
2841     if (liveAtHead.numBits() != static_cast<size_t>(m_numCalleeLocals)) {
2842         beginValidationDidFail();
2843         dataLog("    Wrong number of bits in result!\n");
2844         dataLog("    Result: ", liveAtHead, "\n");
2845         dataLog("    Bit count: ", liveAtHead.numBits(), "\n");
2846         endValidationDidFail();
2847     }
2848     
2849     for (unsigned i = m_numCalleeLocals; i--;) {
2850         VirtualRegister reg = virtualRegisterForLocal(i);
2851         
2852         if (liveAtHead[i]) {
2853             beginValidationDidFail();
2854             dataLog("    Variable ", reg, " is expected to be dead.\n");
2855             dataLog("    Result: ", liveAtHead, "\n");
2856             endValidationDidFail();
2857         }
2858     }
2859
2860     for (unsigned i = 0; i + 1 < numberOfValueProfiles(); ++i) {
2861         if (valueProfile(i).m_bytecodeOffset > valueProfile(i + 1).m_bytecodeOffset) {
2862             beginValidationDidFail();
2863             dataLog("    Value profiles are not sorted.\n");
2864             endValidationDidFail();
2865         }
2866     }
2867      
2868     for (unsigned bytecodeOffset = 0; bytecodeOffset < m_instructions.size(); ) {
2869         OpcodeID opcode = Interpreter::getOpcodeID(m_instructions[bytecodeOffset]);
2870         if (!!baselineAlternative()->handlerForBytecodeOffset(bytecodeOffset)) {
2871             if (opcode == op_catch || opcode == op_enter) {
2872                 // op_catch/op_enter logically represent an entrypoint. Entrypoints are not allowed to be
2873                 // inside of a try block because they are responsible for bootstrapping state. And they
2874                 // are never allowed throw an exception because of this. We rely on this when compiling
2875                 // in the DFG. Because an entrypoint never throws, the bytecode generator will never
2876                 // allow once inside a try block.
2877                 beginValidationDidFail();
2878                 dataLog("    entrypoint not allowed inside a try block.");
2879                 endValidationDidFail();
2880             }
2881         }
2882         bytecodeOffset += opcodeLength(opcode);
2883     }
2884 }
2885
2886 void CodeBlock::beginValidationDidFail()
2887 {
2888     dataLog("Validation failure in ", *this, ":\n");
2889     dataLog("\n");
2890 }
2891
2892 void CodeBlock::endValidationDidFail()
2893 {
2894     dataLog("\n");
2895     dumpBytecode();
2896     dataLog("\n");
2897     dataLog("Validation failure.\n");
2898     RELEASE_ASSERT_NOT_REACHED();
2899 }
2900
2901 void CodeBlock::addBreakpoint(unsigned numBreakpoints)
2902 {
2903     m_numBreakpoints += numBreakpoints;
2904     ASSERT(m_numBreakpoints);
2905     if (JITCode::isOptimizingJIT(jitType()))
2906         jettison(Profiler::JettisonDueToDebuggerBreakpoint);
2907 }
2908
2909 void CodeBlock::setSteppingMode(CodeBlock::SteppingMode mode)
2910 {
2911     m_steppingMode = mode;
2912     if (mode == SteppingModeEnabled && JITCode::isOptimizingJIT(jitType()))
2913         jettison(Profiler::JettisonDueToDebuggerStepping);
2914 }
2915
2916 RareCaseProfile* CodeBlock::addRareCaseProfile(int bytecodeOffset)
2917 {
2918     m_rareCaseProfiles.append(RareCaseProfile(bytecodeOffset));
2919     return &m_rareCaseProfiles.last();
2920 }
2921
2922 RareCaseProfile* CodeBlock::rareCaseProfileForBytecodeOffset(int bytecodeOffset)
2923 {
2924     return tryBinarySearch<RareCaseProfile, int>(
2925         m_rareCaseProfiles, m_rareCaseProfiles.size(), bytecodeOffset,
2926         getRareCaseProfileBytecodeOffset);
2927 }
2928
2929 unsigned CodeBlock::rareCaseProfileCountForBytecodeOffset(int bytecodeOffset)
2930 {
2931     RareCaseProfile* profile = rareCaseProfileForBytecodeOffset(bytecodeOffset);
2932     if (profile)
2933         return profile->m_counter;
2934     return 0;
2935 }
2936
2937 ArithProfile* CodeBlock::arithProfileForBytecodeOffset(int bytecodeOffset)
2938 {
2939     return arithProfileForPC(instructions().begin() + bytecodeOffset);
2940 }
2941
2942 ArithProfile* CodeBlock::arithProfileForPC(Instruction* pc)
2943 {
2944     auto opcodeID = Interpreter::getOpcodeID(pc[0]);
2945     switch (opcodeID) {
2946     case op_negate:
2947         return bitwise_cast<ArithProfile*>(&pc[3].u.operand);
2948     case op_bitor:
2949     case op_bitand:
2950     case op_bitxor:
2951     case op_add:
2952     case op_mul:
2953     case op_sub:
2954     case op_div:
2955         return bitwise_cast<ArithProfile*>(&pc[4].u.operand);
2956     default:
2957         break;
2958     }
2959
2960     return nullptr;
2961 }
2962
2963 bool CodeBlock::couldTakeSpecialFastCase(int bytecodeOffset)
2964 {
2965     if (!hasBaselineJITProfiling())
2966         return false;
2967     ArithProfile* profile = arithProfileForBytecodeOffset(bytecodeOffset);
2968     if (!profile)
2969         return false;
2970     return profile->tookSpecialFastPath();
2971 }
2972
2973 #if ENABLE(JIT)
2974 DFG::CapabilityLevel CodeBlock::capabilityLevel()
2975 {
2976     DFG::CapabilityLevel result = computeCapabilityLevel();
2977     m_capabilityLevelState = result;
2978     return result;
2979 }
2980 #endif
2981
2982 void CodeBlock::insertBasicBlockBoundariesForControlFlowProfiler(RefCountedArray<Instruction>& instructions)
2983 {
2984     if (!unlinkedCodeBlock()->hasOpProfileControlFlowBytecodeOffsets())
2985         return;
2986     const Vector<size_t>& bytecodeOffsets = unlinkedCodeBlock()->opProfileControlFlowBytecodeOffsets();
2987     for (size_t i = 0, offsetsLength = bytecodeOffsets.size(); i < offsetsLength; i++) {
2988         // Because op_profile_control_flow is emitted at the beginning of every basic block, finding 
2989         // the next op_profile_control_flow will give us the text range of a single basic block.
2990         size_t startIdx = bytecodeOffsets[i];
2991         RELEASE_ASSERT(Interpreter::getOpcodeID(instructions[startIdx]) == op_profile_control_flow);
2992         int basicBlockStartOffset = instructions[startIdx + 1].u.operand;
2993         int basicBlockEndOffset;
2994         if (i + 1 < offsetsLength) {
2995             size_t endIdx = bytecodeOffsets[i + 1];
2996             RELEASE_ASSERT(Interpreter::getOpcodeID(instructions[endIdx]) == op_profile_control_flow);
2997             basicBlockEndOffset = instructions[endIdx + 1].u.operand - 1;
2998         } else {
2999             basicBlockEndOffset = m_sourceOffset + ownerScriptExecutable()->source().length() - 1; // Offset before the closing brace.
3000             basicBlockStartOffset = std::min(basicBlockStartOffset, basicBlockEndOffset); // Some start offsets may be at the closing brace, ensure it is the offset before.
3001         }
3002
3003         // The following check allows for the same textual JavaScript basic block to have its bytecode emitted more
3004         // than once and still play nice with the control flow profiler. When basicBlockStartOffset is larger than 
3005         // basicBlockEndOffset, it indicates that the bytecode generator has emitted code for the same AST node 
3006         // more than once (for example: ForInNode, Finally blocks in TryNode, etc). Though these are different 
3007         // basic blocks at the bytecode level, they are generated from the same textual basic block in the JavaScript 
3008         // program. The condition: 
3009         // (basicBlockEndOffset < basicBlockStartOffset) 
3010         // is encountered when op_profile_control_flow lies across the boundary of these duplicated bytecode basic 
3011         // blocks and the textual offset goes from the end of the duplicated block back to the beginning. These 
3012         // ranges are dummy ranges and are ignored. The duplicated bytecode basic blocks point to the same 
3013         // internal data structure, so if any of them execute, it will record the same textual basic block in the 
3014         // JavaScript program as executing.
3015         // At the bytecode level, this situation looks like:
3016         // j: op_profile_control_flow (from j->k, we have basicBlockEndOffset < basicBlockStartOffset)
3017         // ...
3018         // k: op_profile_control_flow (we want to skip over the j->k block and start fresh at offset k as the start of a new basic block k->m).
3019         // ...
3020         // m: op_profile_control_flow
3021         if (basicBlockEndOffset < basicBlockStartOffset) {
3022             RELEASE_ASSERT(i + 1 < offsetsLength); // We should never encounter dummy blocks at the end of a CodeBlock.
3023             instructions[startIdx + 1].u.basicBlockLocation = vm()->controlFlowProfiler()->dummyBasicBlock();
3024             continue;
3025         }
3026
3027         BasicBlockLocation* basicBlockLocation = vm()->controlFlowProfiler()->getBasicBlockLocation(ownerScriptExecutable()->sourceID(), basicBlockStartOffset, basicBlockEndOffset);
3028
3029         // Find all functions that are enclosed within the range: [basicBlockStartOffset, basicBlockEndOffset]
3030         // and insert these functions' start/end offsets as gaps in the current BasicBlockLocation.
3031         // This is necessary because in the original source text of a JavaScript program, 
3032         // function literals form new basic blocks boundaries, but they aren't represented 
3033         // inside the CodeBlock's instruction stream.
3034         auto insertFunctionGaps = [basicBlockLocation, basicBlockStartOffset, basicBlockEndOffset] (const WriteBarrier<FunctionExecutable>& functionExecutable) {
3035             const UnlinkedFunctionExecutable* executable = functionExecutable->unlinkedExecutable();
3036             int functionStart = executable->typeProfilingStartOffset();
3037             int functionEnd = executable->typeProfilingEndOffset();
3038             if (functionStart >= basicBlockStartOffset && functionEnd <= basicBlockEndOffset)
3039                 basicBlockLocation->insertGap(functionStart, functionEnd);
3040         };
3041
3042         for (const WriteBarrier<FunctionExecutable>& executable : m_functionDecls)
3043             insertFunctionGaps(executable);
3044         for (const WriteBarrier<FunctionExecutable>& executable : m_functionExprs)
3045             insertFunctionGaps(executable);
3046
3047         instructions[startIdx + 1].u.basicBlockLocation = basicBlockLocation;
3048     }
3049 }
3050
3051 #if ENABLE(JIT)
3052 void CodeBlock::setPCToCodeOriginMap(std::unique_ptr<PCToCodeOriginMap>&& map) 
3053
3054     m_pcToCodeOriginMap = WTFMove(map);
3055 }
3056
3057 std::optional<CodeOrigin> CodeBlock::findPC(void* pc)
3058 {
3059     if (m_pcToCodeOriginMap) {
3060         if (std::optional<CodeOrigin> codeOrigin = m_pcToCodeOriginMap->findPC(pc))
3061             return codeOrigin;
3062     }
3063
3064     for (Bag<StructureStubInfo>::iterator iter = m_stubInfos.begin(); !!iter; ++iter) {
3065         StructureStubInfo* stub = *iter;
3066         if (stub->containsPC(pc))
3067             return std::optional<CodeOrigin>(stub->codeOrigin);
3068     }
3069
3070     if (std::optional<CodeOrigin> codeOrigin = m_jitCode->findPC(this, pc))
3071         return codeOrigin;
3072
3073     return std::nullopt;
3074 }
3075 #endif // ENABLE(JIT)
3076
3077 std::optional<unsigned> CodeBlock::bytecodeOffsetFromCallSiteIndex(CallSiteIndex callSiteIndex)
3078 {
3079     std::optional<unsigned> bytecodeOffset;
3080     JITCode::JITType jitType = this->jitType();
3081     if (jitType == JITCode::InterpreterThunk || jitType == JITCode::BaselineJIT) {
3082 #if USE(JSVALUE64)
3083         bytecodeOffset = callSiteIndex.bits();
3084 #else
3085         Instruction* instruction = bitwise_cast<Instruction*>(callSiteIndex.bits());
3086         bytecodeOffset = instruction - instructions().begin();
3087 #endif
3088     } else if (jitType == JITCode::DFGJIT || jitType == JITCode::FTLJIT) {
3089 #if ENABLE(DFG_JIT)
3090         RELEASE_ASSERT(canGetCodeOrigin(callSiteIndex));
3091         CodeOrigin origin = codeOrigin(callSiteIndex);
3092         bytecodeOffset = origin.bytecodeIndex;
3093 #else
3094         RELEASE_ASSERT_NOT_REACHED();
3095 #endif
3096     }
3097
3098     return bytecodeOffset;
3099 }
3100
3101 int32_t CodeBlock::thresholdForJIT(int32_t threshold)
3102 {
3103     switch (unlinkedCodeBlock()->didOptimize()) {
3104     case MixedTriState:
3105         return threshold;
3106     case FalseTriState:
3107         return threshold * 4;
3108     case TrueTriState:
3109         return threshold / 2;
3110     }
3111     ASSERT_NOT_REACHED();
3112     return threshold;
3113 }
3114
3115 void CodeBlock::jitAfterWarmUp()
3116 {
3117     m_llintExecuteCounter.setNewThreshold(thresholdForJIT(Options::thresholdForJITAfterWarmUp()), this);
3118 }
3119
3120 void CodeBlock::jitSoon()
3121 {
3122     m_llintExecuteCounter.setNewThreshold(thresholdForJIT(Options::thresholdForJITSoon()), this);
3123 }
3124
3125 bool CodeBlock::hasInstalledVMTrapBreakpoints() const
3126 {
3127 #if ENABLE(SIGNAL_BASED_VM_TRAPS)
3128     
3129     // This function may be called from a signal handler. We need to be
3130     // careful to not call anything that is not signal handler safe, e.g.
3131     // we should not perturb the refCount of m_jitCode.
3132     if (!JITCode::isOptimizingJIT(jitType()))
3133         return false;
3134     return m_jitCode->dfgCommon()->hasInstalledVMTrapsBreakpoints();
3135 #else
3136     return false;
3137 #endif
3138 }
3139
3140 bool CodeBlock::installVMTrapBreakpoints()
3141 {
3142 #if ENABLE(SIGNAL_BASED_VM_TRAPS)
3143     // This function may be called from a signal handler. We need to be
3144     // careful to not call anything that is not signal handler safe, e.g.
3145     // we should not perturb the refCount of m_jitCode.
3146     if (!JITCode::isOptimizingJIT(jitType()))
3147         return false;
3148     m_jitCode->dfgCommon()->installVMTrapBreakpoints(this);
3149     return true;
3150 #else
3151     UNREACHABLE_FOR_PLATFORM();
3152     return false;
3153 #endif
3154 }
3155
3156 void CodeBlock::dumpMathICStats()
3157 {
3158 #if ENABLE(MATH_IC_STATS)
3159     double numAdds = 0.0;
3160     double totalAddSize = 0.0;
3161     double numMuls = 0.0;
3162     double totalMulSize = 0.0;
3163     double numNegs = 0.0;
3164     double totalNegSize = 0.0;
3165     double numSubs = 0.0;
3166     double totalSubSize = 0.0;
3167
3168     auto countICs = [&] (CodeBlock* codeBlock) {
3169         for (JITAddIC* addIC : codeBlock->m_addICs) {
3170             numAdds++;
3171             totalAddSize += addIC->codeSize();
3172         }
3173
3174         for (JITMulIC* mulIC : codeBlock->m_mulICs) {
3175             numMuls++;
3176             totalMulSize += mulIC->codeSize();
3177         }
3178
3179         for (JITNegIC* negIC : codeBlock->m_negICs) {
3180             numNegs++;
3181             totalNegSize += negIC->codeSize();
3182         }
3183
3184         for (JITSubIC* subIC : codeBlock->m_subICs) {
3185             numSubs++;
3186             totalSubSize += subIC->codeSize();
3187         }
3188
3189         return false;
3190     };
3191     heap()->forEachCodeBlock(countICs);
3192
3193     dataLog("Num Adds: ", numAdds, "\n");
3194     dataLog("Total Add size in bytes: ", totalAddSize, "\n");
3195     dataLog("Average Add size: ", totalAddSize / numAdds, "\n");
3196     dataLog("\n");
3197     dataLog("Num Muls: ", numMuls, "\n");
3198     dataLog("Total Mul size in bytes: ", totalMulSize, "\n");
3199     dataLog("Average Mul size: ", totalMulSize / numMuls, "\n");
3200     dataLog("\n");
3201     dataLog("Num Negs: ", numNegs, "\n");
3202     dataLog("Total Neg size in bytes: ", totalNegSize, "\n");
3203     dataLog("Average Neg size: ", totalNegSize / numNegs, "\n");
3204     dataLog("\n");
3205     dataLog("Num Subs: ", numSubs, "\n");
3206     dataLog("Total Sub size in bytes: ", totalSubSize, "\n");
3207     dataLog("Average Sub size: ", totalSubSize / numSubs, "\n");
3208
3209     dataLog("-----------------------\n");
3210 #endif
3211 }
3212
3213 void setPrinter(Printer::PrintRecord& record, CodeBlock* codeBlock)
3214 {
3215     Printer::setPrinter(record, toCString(codeBlock));
3216 }
3217
3218 } // namespace JSC
3219
3220 namespace WTF {
3221     
3222 void printInternal(PrintStream& out, JSC::CodeBlock* codeBlock)
3223 {
3224     if (UNLIKELY(!codeBlock)) {
3225         out.print("<null codeBlock>");
3226         return;
3227     }
3228     out.print(*codeBlock);
3229 }
3230     
3231 } // namespace WTF