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