Lets not iterate over the constant pool twice every time we link a code block
[WebKit-https.git] / Source / JavaScriptCore / bytecode / CodeBlock.h
1 /*
2  * Copyright (C) 2008-2016 Apple Inc. All rights reserved.
3  * Copyright (C) 2008 Cameron Zwarich <cwzwarich@uwaterloo.ca>
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  *
9  * 1.  Redistributions of source code must retain the above copyright
10  *     notice, this list of conditions and the following disclaimer.
11  * 2.  Redistributions in binary form must reproduce the above copyright
12  *     notice, this list of conditions and the following disclaimer in the
13  *     documentation and/or other materials provided with the distribution.
14  * 3.  Neither the name of Apple Inc. ("Apple") nor the names of
15  *     its contributors may be used to endorse or promote products derived
16  *     from this software without specific prior written permission.
17  *
18  * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
19  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
20  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
21  * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
22  * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
23  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
24  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
25  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
27  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28  */
29
30 #ifndef CodeBlock_h
31 #define CodeBlock_h
32
33 #include "ArrayProfile.h"
34 #include "ByValInfo.h"
35 #include "BytecodeConventions.h"
36 #include "BytecodeLivenessAnalysis.h"
37 #include "CallLinkInfo.h"
38 #include "CallReturnOffsetToBytecodeOffset.h"
39 #include "CodeBlockHash.h"
40 #include "CodeBlockSet.h"
41 #include "CodeOrigin.h"
42 #include "CodeType.h"
43 #include "CompactJITCodeMap.h"
44 #include "ConcurrentJITLock.h"
45 #include "DFGCommon.h"
46 #include "DFGExitProfile.h"
47 #include "DeferredCompilationCallback.h"
48 #include "EvalCodeCache.h"
49 #include "ExecutionCounter.h"
50 #include "ExpressionRangeInfo.h"
51 #include "HandlerInfo.h"
52 #include "Instruction.h"
53 #include "JITCode.h"
54 #include "JITWriteBarrier.h"
55 #include "JSCell.h"
56 #include "JSGlobalObject.h"
57 #include "JumpTable.h"
58 #include "LLIntCallLinkInfo.h"
59 #include "LazyOperandValueProfile.h"
60 #include "ObjectAllocationProfile.h"
61 #include "Options.h"
62 #include "ProfilerCompilation.h"
63 #include "ProfilerJettisonReason.h"
64 #include "PutPropertySlot.h"
65 #include "RegExpObject.h"
66 #include "UnconditionalFinalizer.h"
67 #include "ValueProfile.h"
68 #include "VirtualRegister.h"
69 #include "Watchpoint.h"
70 #include <wtf/Bag.h>
71 #include <wtf/FastBitVector.h>
72 #include <wtf/FastMalloc.h>
73 #include <wtf/RefCountedArray.h>
74 #include <wtf/RefPtr.h>
75 #include <wtf/SegmentedVector.h>
76 #include <wtf/Vector.h>
77 #include <wtf/text/WTFString.h>
78
79 namespace JSC {
80
81 class ExecState;
82 class JSModuleEnvironment;
83 class LLIntOffsetsExtractor;
84 class PCToCodeOriginMap;
85 class RegisterAtOffsetList;
86 class StructureStubInfo;
87 class TypeLocation;
88
89 enum class AccessType : int8_t;
90
91 typedef HashMap<CodeOrigin, StructureStubInfo*, CodeOriginApproximateHash> StubInfoMap;
92
93 enum ReoptimizationMode { DontCountReoptimization, CountReoptimization };
94
95 class CodeBlock : public JSCell {
96     typedef JSCell Base;
97     friend class BytecodeLivenessAnalysis;
98     friend class JIT;
99     friend class LLIntOffsetsExtractor;
100
101     class UnconditionalFinalizer : public JSC::UnconditionalFinalizer { 
102         void finalizeUnconditionally() override;
103     };
104
105     class WeakReferenceHarvester : public JSC::WeakReferenceHarvester {
106         void visitWeakReferences(SlotVisitor&) override;
107     };
108
109 public:
110     enum CopyParsedBlockTag { CopyParsedBlock };
111
112     static const unsigned StructureFlags = Base::StructureFlags | StructureIsImmortal;
113
114     DECLARE_INFO;
115
116 protected:
117     CodeBlock(VM*, Structure*, CopyParsedBlockTag, CodeBlock& other);
118     CodeBlock(VM*, Structure*, ScriptExecutable* ownerExecutable, UnlinkedCodeBlock*, JSScope*, PassRefPtr<SourceProvider>, unsigned sourceOffset, unsigned firstLineColumnOffset);
119 #if ENABLE(WEBASSEMBLY)
120     CodeBlock(VM*, Structure*, WebAssemblyExecutable* ownerExecutable, JSGlobalObject*);
121 #endif
122
123     void finishCreation(VM&, CopyParsedBlockTag, CodeBlock& other);
124     void finishCreation(VM&, ScriptExecutable* ownerExecutable, UnlinkedCodeBlock*, JSScope*);
125 #if ENABLE(WEBASSEMBLY)
126     void finishCreation(VM&, WebAssemblyExecutable* ownerExecutable, JSGlobalObject*);
127 #endif
128
129     WriteBarrier<JSGlobalObject> m_globalObject;
130
131 public:
132     JS_EXPORT_PRIVATE ~CodeBlock();
133
134     UnlinkedCodeBlock* unlinkedCodeBlock() const { return m_unlinkedCode.get(); }
135
136     CString inferredName() const;
137     CodeBlockHash hash() const;
138     bool hasHash() const;
139     bool isSafeToComputeHash() const;
140     CString hashAsStringIfPossible() const;
141     CString sourceCodeForTools() const; // Not quite the actual source we parsed; this will do things like prefix the source for a function with a reified signature.
142     CString sourceCodeOnOneLine() const; // As sourceCodeForTools(), but replaces all whitespace runs with a single space.
143     void dumpAssumingJITType(PrintStream&, JITCode::JITType) const;
144     void dump(PrintStream&) const;
145
146     int numParameters() const { return m_numParameters; }
147     void setNumParameters(int newValue);
148
149     int numCalleeLocals() const { return m_numCalleeLocals; }
150
151     int* addressOfNumParameters() { return &m_numParameters; }
152     static ptrdiff_t offsetOfNumParameters() { return OBJECT_OFFSETOF(CodeBlock, m_numParameters); }
153
154     CodeBlock* alternative() const { return static_cast<CodeBlock*>(m_alternative.get()); }
155     void setAlternative(VM&, CodeBlock*);
156
157     template <typename Functor> void forEachRelatedCodeBlock(Functor&& functor)
158     {
159         Functor f(std::forward<Functor>(functor));
160         Vector<CodeBlock*, 4> codeBlocks;
161         codeBlocks.append(this);
162
163         while (!codeBlocks.isEmpty()) {
164             CodeBlock* currentCodeBlock = codeBlocks.takeLast();
165             f(currentCodeBlock);
166
167             if (CodeBlock* alternative = currentCodeBlock->alternative())
168                 codeBlocks.append(alternative);
169             if (CodeBlock* osrEntryBlock = currentCodeBlock->specialOSREntryBlockOrNull())
170                 codeBlocks.append(osrEntryBlock);
171         }
172     }
173     
174     CodeSpecializationKind specializationKind() const
175     {
176         return specializationFromIsConstruct(m_isConstructor);
177     }
178
179     CodeBlock* alternativeForJettison();    
180     JS_EXPORT_PRIVATE CodeBlock* baselineAlternative();
181     
182     // FIXME: Get rid of this.
183     // https://bugs.webkit.org/show_bug.cgi?id=123677
184     CodeBlock* baselineVersion();
185
186     static size_t estimatedSize(JSCell*);
187     static void visitChildren(JSCell*, SlotVisitor&);
188     void visitChildren(SlotVisitor&);
189     void visitWeakly(SlotVisitor&);
190     void clearVisitWeaklyHasBeenCalled();
191
192     void dumpSource();
193     void dumpSource(PrintStream&);
194
195     void dumpBytecode();
196     void dumpBytecode(PrintStream&);
197     void dumpBytecode(
198         PrintStream&, unsigned bytecodeOffset,
199         const StubInfoMap& = StubInfoMap(), const CallLinkInfoMap& = CallLinkInfoMap());
200     void dumpExceptionHandlers(PrintStream&);
201     void printStructures(PrintStream&, const Instruction*);
202     void printStructure(PrintStream&, const char* name, const Instruction*, int operand);
203
204     bool isStrictMode() const { return m_isStrictMode; }
205     ECMAMode ecmaMode() const { return isStrictMode() ? StrictMode : NotStrictMode; }
206
207     inline bool isKnownNotImmediate(int index)
208     {
209         if (index == m_thisRegister.offset() && !m_isStrictMode)
210             return true;
211
212         if (isConstantRegisterIndex(index))
213             return getConstant(index).isCell();
214
215         return false;
216     }
217
218     ALWAYS_INLINE bool isTemporaryRegisterIndex(int index)
219     {
220         return index >= m_numVars;
221     }
222
223     enum class RequiredHandler {
224         CatchHandler,
225         AnyHandler
226     };
227     HandlerInfo* handlerForBytecodeOffset(unsigned bytecodeOffset, RequiredHandler = RequiredHandler::AnyHandler);
228     HandlerInfo* handlerForIndex(unsigned, RequiredHandler = RequiredHandler::AnyHandler);
229     void removeExceptionHandlerForCallSite(CallSiteIndex);
230     unsigned lineNumberForBytecodeOffset(unsigned bytecodeOffset);
231     unsigned columnNumberForBytecodeOffset(unsigned bytecodeOffset);
232     void expressionRangeForBytecodeOffset(unsigned bytecodeOffset, int& divot,
233                                           int& startOffset, int& endOffset, unsigned& line, unsigned& column);
234
235     void getStubInfoMap(const ConcurrentJITLocker&, StubInfoMap& result);
236     void getStubInfoMap(StubInfoMap& result);
237     
238     void getCallLinkInfoMap(const ConcurrentJITLocker&, CallLinkInfoMap& result);
239     void getCallLinkInfoMap(CallLinkInfoMap& result);
240
241     void getByValInfoMap(const ConcurrentJITLocker&, ByValInfoMap& result);
242     void getByValInfoMap(ByValInfoMap& result);
243     
244 #if ENABLE(JIT)
245     StructureStubInfo* addStubInfo(AccessType);
246     Bag<StructureStubInfo>::iterator stubInfoBegin() { return m_stubInfos.begin(); }
247     Bag<StructureStubInfo>::iterator stubInfoEnd() { return m_stubInfos.end(); }
248     
249     // O(n) operation. Use getStubInfoMap() unless you really only intend to get one
250     // stub info.
251     StructureStubInfo* findStubInfo(CodeOrigin);
252
253     ByValInfo* addByValInfo();
254
255     CallLinkInfo* addCallLinkInfo();
256     Bag<CallLinkInfo>::iterator callLinkInfosBegin() { return m_callLinkInfos.begin(); }
257     Bag<CallLinkInfo>::iterator callLinkInfosEnd() { return m_callLinkInfos.end(); }
258
259     // This is a slow function call used primarily for compiling OSR exits in the case
260     // that there had been inlining. Chances are if you want to use this, you're really
261     // looking for a CallLinkInfoMap to amortize the cost of calling this.
262     CallLinkInfo* getCallLinkInfoForBytecodeIndex(unsigned bytecodeIndex);
263 #endif // ENABLE(JIT)
264
265     void unlinkIncomingCalls();
266
267 #if ENABLE(JIT)
268     void linkIncomingCall(ExecState* callerFrame, CallLinkInfo*);
269     void linkIncomingPolymorphicCall(ExecState* callerFrame, PolymorphicCallNode*);
270 #endif // ENABLE(JIT)
271
272     void linkIncomingCall(ExecState* callerFrame, LLIntCallLinkInfo*);
273
274     void setJITCodeMap(std::unique_ptr<CompactJITCodeMap> jitCodeMap)
275     {
276         m_jitCodeMap = WTFMove(jitCodeMap);
277     }
278     CompactJITCodeMap* jitCodeMap()
279     {
280         return m_jitCodeMap.get();
281     }
282
283     unsigned bytecodeOffset(Instruction* returnAddress)
284     {
285         RELEASE_ASSERT(returnAddress >= instructions().begin() && returnAddress < instructions().end());
286         return static_cast<Instruction*>(returnAddress) - instructions().begin();
287     }
288
289     unsigned numberOfInstructions() const { return m_instructions.size(); }
290     RefCountedArray<Instruction>& instructions() { return m_instructions; }
291     const RefCountedArray<Instruction>& instructions() const { return m_instructions; }
292
293     size_t predictedMachineCodeSize();
294
295     bool usesOpcode(OpcodeID);
296
297     unsigned instructionCount() const { return m_instructions.size(); }
298
299     // Exactly equivalent to codeBlock->ownerExecutable()->newReplacementCodeBlockFor(codeBlock->specializationKind())
300     CodeBlock* newReplacement();
301     
302     void setJITCode(PassRefPtr<JITCode> code)
303     {
304         ASSERT(heap()->isDeferred());
305         heap()->reportExtraMemoryAllocated(code->size());
306         ConcurrentJITLocker locker(m_lock);
307         WTF::storeStoreFence(); // This is probably not needed because the lock will also do something similar, but it's good to be paranoid.
308         m_jitCode = code;
309     }
310     PassRefPtr<JITCode> jitCode() { return m_jitCode; }
311     static ptrdiff_t jitCodeOffset() { return OBJECT_OFFSETOF(CodeBlock, m_jitCode); }
312     JITCode::JITType jitType() const
313     {
314         JITCode* jitCode = m_jitCode.get();
315         WTF::loadLoadFence();
316         JITCode::JITType result = JITCode::jitTypeFor(jitCode);
317         WTF::loadLoadFence(); // This probably isn't needed. Oh well, paranoia is good.
318         return result;
319     }
320
321     bool hasBaselineJITProfiling() const
322     {
323         return jitType() == JITCode::BaselineJIT;
324     }
325     
326 #if ENABLE(JIT)
327     CodeBlock* replacement();
328
329     DFG::CapabilityLevel computeCapabilityLevel();
330     DFG::CapabilityLevel capabilityLevel();
331     DFG::CapabilityLevel capabilityLevelState() { return static_cast<DFG::CapabilityLevel>(m_capabilityLevelState); }
332
333     bool hasOptimizedReplacement(JITCode::JITType typeToReplace);
334     bool hasOptimizedReplacement(); // the typeToReplace is my JITType
335 #endif
336
337     void jettison(Profiler::JettisonReason, ReoptimizationMode = DontCountReoptimization, const FireDetail* = nullptr);
338     
339     ExecutableBase* ownerExecutable() const { return m_ownerExecutable.get(); }
340     ScriptExecutable* ownerScriptExecutable() const { return jsCast<ScriptExecutable*>(m_ownerExecutable.get()); }
341
342     void setVM(VM* vm) { m_vm = vm; }
343     VM* vm() { return m_vm; }
344
345     void setThisRegister(VirtualRegister thisRegister) { m_thisRegister = thisRegister; }
346     VirtualRegister thisRegister() const { return m_thisRegister; }
347
348     bool usesEval() const { return m_unlinkedCode->usesEval(); }
349
350     void setScopeRegister(VirtualRegister scopeRegister)
351     {
352         ASSERT(scopeRegister.isLocal() || !scopeRegister.isValid());
353         m_scopeRegister = scopeRegister;
354     }
355
356     VirtualRegister scopeRegister() const
357     {
358         return m_scopeRegister;
359     }
360     
361     CodeType codeType() const
362     {
363         return static_cast<CodeType>(m_codeType);
364     }
365
366     PutPropertySlot::Context putByIdContext() const
367     {
368         if (codeType() == EvalCode)
369             return PutPropertySlot::PutByIdEval;
370         return PutPropertySlot::PutById;
371     }
372
373     SourceProvider* source() const { return m_source.get(); }
374     unsigned sourceOffset() const { return m_sourceOffset; }
375     unsigned firstLineColumnOffset() const { return m_firstLineColumnOffset; }
376
377     size_t numberOfJumpTargets() const { return m_unlinkedCode->numberOfJumpTargets(); }
378     unsigned jumpTarget(int index) const { return m_unlinkedCode->jumpTarget(index); }
379
380     String nameForRegister(VirtualRegister);
381
382     unsigned numberOfArgumentValueProfiles()
383     {
384         ASSERT(m_numParameters >= 0);
385         ASSERT(m_argumentValueProfiles.size() == static_cast<unsigned>(m_numParameters));
386         return m_argumentValueProfiles.size();
387     }
388     ValueProfile* valueProfileForArgument(unsigned argumentIndex)
389     {
390         ValueProfile* result = &m_argumentValueProfiles[argumentIndex];
391         ASSERT(result->m_bytecodeOffset == -1);
392         return result;
393     }
394
395     unsigned numberOfValueProfiles() { return m_valueProfiles.size(); }
396     ValueProfile* valueProfile(int index) { return &m_valueProfiles[index]; }
397     ValueProfile* valueProfileForBytecodeOffset(int bytecodeOffset);
398     SpeculatedType valueProfilePredictionForBytecodeOffset(const ConcurrentJITLocker& locker, int bytecodeOffset)
399     {
400         return valueProfileForBytecodeOffset(bytecodeOffset)->computeUpdatedPrediction(locker);
401     }
402
403     unsigned totalNumberOfValueProfiles()
404     {
405         return numberOfArgumentValueProfiles() + numberOfValueProfiles();
406     }
407     ValueProfile* getFromAllValueProfiles(unsigned index)
408     {
409         if (index < numberOfArgumentValueProfiles())
410             return valueProfileForArgument(index);
411         return valueProfile(index - numberOfArgumentValueProfiles());
412     }
413
414     RareCaseProfile* addRareCaseProfile(int bytecodeOffset)
415     {
416         m_rareCaseProfiles.append(RareCaseProfile(bytecodeOffset));
417         return &m_rareCaseProfiles.last();
418     }
419     unsigned numberOfRareCaseProfiles() { return m_rareCaseProfiles.size(); }
420     RareCaseProfile* rareCaseProfileForBytecodeOffset(int bytecodeOffset);
421     unsigned rareCaseProfileCountForBytecodeOffset(int bytecodeOffset);
422
423     bool likelyToTakeSlowCase(int bytecodeOffset)
424     {
425         if (!hasBaselineJITProfiling())
426             return false;
427         unsigned value = rareCaseProfileCountForBytecodeOffset(bytecodeOffset);
428         return value >= Options::likelyToTakeSlowCaseMinimumCount();
429     }
430
431     bool couldTakeSlowCase(int bytecodeOffset)
432     {
433         if (!hasBaselineJITProfiling())
434             return false;
435         unsigned value = rareCaseProfileCountForBytecodeOffset(bytecodeOffset);
436         return value >= Options::couldTakeSlowCaseMinimumCount();
437     }
438
439     ResultProfile* ensureResultProfile(int bytecodeOffset);
440     ResultProfile* ensureResultProfile(const ConcurrentJITLocker&, int bytecodeOffset);
441     unsigned numberOfResultProfiles() { return m_resultProfiles.size(); }
442     ResultProfile* resultProfileForBytecodeOffset(int bytecodeOffset);
443     ResultProfile* resultProfileForBytecodeOffset(const ConcurrentJITLocker&, int bytecodeOffset);
444
445     unsigned specialFastCaseProfileCountForBytecodeOffset(int bytecodeOffset)
446     {
447         ResultProfile* profile = resultProfileForBytecodeOffset(bytecodeOffset);
448         if (!profile)
449             return 0;
450         return profile->specialFastPathCount();
451     }
452
453     bool couldTakeSpecialFastCase(int bytecodeOffset)
454     {
455         if (!hasBaselineJITProfiling())
456             return false;
457         unsigned specialFastCaseCount = specialFastCaseProfileCountForBytecodeOffset(bytecodeOffset);
458         return specialFastCaseCount >= Options::couldTakeSlowCaseMinimumCount();
459     }
460
461     unsigned numberOfArrayProfiles() const { return m_arrayProfiles.size(); }
462     const ArrayProfileVector& arrayProfiles() { return m_arrayProfiles; }
463     ArrayProfile* addArrayProfile(unsigned bytecodeOffset)
464     {
465         m_arrayProfiles.append(ArrayProfile(bytecodeOffset));
466         return &m_arrayProfiles.last();
467     }
468     ArrayProfile* getArrayProfile(unsigned bytecodeOffset);
469     ArrayProfile* getOrAddArrayProfile(unsigned bytecodeOffset);
470
471     // Exception handling support
472
473     size_t numberOfExceptionHandlers() const { return m_rareData ? m_rareData->m_exceptionHandlers.size() : 0; }
474     HandlerInfo& exceptionHandler(int index) { RELEASE_ASSERT(m_rareData); return m_rareData->m_exceptionHandlers[index]; }
475
476     bool hasExpressionInfo() { return m_unlinkedCode->hasExpressionInfo(); }
477
478 #if ENABLE(DFG_JIT)
479     Vector<CodeOrigin, 0, UnsafeVectorOverflow>& codeOrigins();
480     
481     // Having code origins implies that there has been some inlining.
482     bool hasCodeOrigins()
483     {
484         return JITCode::isOptimizingJIT(jitType());
485     }
486         
487     bool canGetCodeOrigin(CallSiteIndex index)
488     {
489         if (!hasCodeOrigins())
490             return false;
491         return index.bits() < codeOrigins().size();
492     }
493
494     CodeOrigin codeOrigin(CallSiteIndex index)
495     {
496         return codeOrigins()[index.bits()];
497     }
498
499     bool addFrequentExitSite(const DFG::FrequentExitSite& site)
500     {
501         ASSERT(JITCode::isBaselineCode(jitType()));
502         ConcurrentJITLocker locker(m_lock);
503         return m_exitProfile.add(locker, site);
504     }
505
506     bool hasExitSite(const ConcurrentJITLocker& locker, const DFG::FrequentExitSite& site) const
507     {
508         return m_exitProfile.hasExitSite(locker, site);
509     }
510     bool hasExitSite(const DFG::FrequentExitSite& site) const
511     {
512         ConcurrentJITLocker locker(m_lock);
513         return hasExitSite(locker, site);
514     }
515
516     DFG::ExitProfile& exitProfile() { return m_exitProfile; }
517
518     CompressedLazyOperandValueProfileHolder& lazyOperandValueProfiles()
519     {
520         return m_lazyOperandValueProfiles;
521     }
522 #endif // ENABLE(DFG_JIT)
523
524     // Constant Pool
525 #if ENABLE(DFG_JIT)
526     size_t numberOfIdentifiers() const { return m_unlinkedCode->numberOfIdentifiers() + numberOfDFGIdentifiers(); }
527     size_t numberOfDFGIdentifiers() const;
528     const Identifier& identifier(int index) const;
529 #else
530     size_t numberOfIdentifiers() const { return m_unlinkedCode->numberOfIdentifiers(); }
531     const Identifier& identifier(int index) const { return m_unlinkedCode->identifier(index); }
532 #endif
533
534     Vector<WriteBarrier<Unknown>>& constants() { return m_constantRegisters; }
535     Vector<SourceCodeRepresentation>& constantsSourceCodeRepresentation() { return m_constantsSourceCodeRepresentation; }
536     unsigned addConstant(JSValue v)
537     {
538         unsigned result = m_constantRegisters.size();
539         m_constantRegisters.append(WriteBarrier<Unknown>());
540         m_constantRegisters.last().set(m_globalObject->vm(), this, v);
541         m_constantsSourceCodeRepresentation.append(SourceCodeRepresentation::Other);
542         return result;
543     }
544
545     unsigned addConstantLazily()
546     {
547         unsigned result = m_constantRegisters.size();
548         m_constantRegisters.append(WriteBarrier<Unknown>());
549         m_constantsSourceCodeRepresentation.append(SourceCodeRepresentation::Other);
550         return result;
551     }
552
553     WriteBarrier<Unknown>& constantRegister(int index) { return m_constantRegisters[index - FirstConstantRegisterIndex]; }
554     ALWAYS_INLINE bool isConstantRegisterIndex(int index) const { return index >= FirstConstantRegisterIndex; }
555     ALWAYS_INLINE JSValue getConstant(int index) const { return m_constantRegisters[index - FirstConstantRegisterIndex].get(); }
556     ALWAYS_INLINE SourceCodeRepresentation constantSourceCodeRepresentation(int index) const { return m_constantsSourceCodeRepresentation[index - FirstConstantRegisterIndex]; }
557
558     FunctionExecutable* functionDecl(int index) { return m_functionDecls[index].get(); }
559     int numberOfFunctionDecls() { return m_functionDecls.size(); }
560     FunctionExecutable* functionExpr(int index) { return m_functionExprs[index].get(); }
561     
562     RegExp* regexp(int index) const { return m_unlinkedCode->regexp(index); }
563
564     unsigned numberOfConstantBuffers() const
565     {
566         if (!m_rareData)
567             return 0;
568         return m_rareData->m_constantBuffers.size();
569     }
570     unsigned addConstantBuffer(const Vector<JSValue>& buffer)
571     {
572         createRareDataIfNecessary();
573         unsigned size = m_rareData->m_constantBuffers.size();
574         m_rareData->m_constantBuffers.append(buffer);
575         return size;
576     }
577
578     Vector<JSValue>& constantBufferAsVector(unsigned index)
579     {
580         ASSERT(m_rareData);
581         return m_rareData->m_constantBuffers[index];
582     }
583     JSValue* constantBuffer(unsigned index)
584     {
585         return constantBufferAsVector(index).data();
586     }
587
588     Heap* heap() const { return &m_vm->heap; }
589     JSGlobalObject* globalObject() { return m_globalObject.get(); }
590
591     JSGlobalObject* globalObjectFor(CodeOrigin);
592
593     BytecodeLivenessAnalysis& livenessAnalysis()
594     {
595         {
596             ConcurrentJITLocker locker(m_lock);
597             if (!!m_livenessAnalysis)
598                 return *m_livenessAnalysis;
599         }
600         std::unique_ptr<BytecodeLivenessAnalysis> analysis =
601             std::make_unique<BytecodeLivenessAnalysis>(this);
602         {
603             ConcurrentJITLocker locker(m_lock);
604             if (!m_livenessAnalysis)
605                 m_livenessAnalysis = WTFMove(analysis);
606             return *m_livenessAnalysis;
607         }
608     }
609     
610     void validate();
611
612     // Jump Tables
613
614     size_t numberOfSwitchJumpTables() const { return m_rareData ? m_rareData->m_switchJumpTables.size() : 0; }
615     SimpleJumpTable& addSwitchJumpTable() { createRareDataIfNecessary(); m_rareData->m_switchJumpTables.append(SimpleJumpTable()); return m_rareData->m_switchJumpTables.last(); }
616     SimpleJumpTable& switchJumpTable(int tableIndex) { RELEASE_ASSERT(m_rareData); return m_rareData->m_switchJumpTables[tableIndex]; }
617     void clearSwitchJumpTables()
618     {
619         if (!m_rareData)
620             return;
621         m_rareData->m_switchJumpTables.clear();
622     }
623
624     size_t numberOfStringSwitchJumpTables() const { return m_rareData ? m_rareData->m_stringSwitchJumpTables.size() : 0; }
625     StringJumpTable& addStringSwitchJumpTable() { createRareDataIfNecessary(); m_rareData->m_stringSwitchJumpTables.append(StringJumpTable()); return m_rareData->m_stringSwitchJumpTables.last(); }
626     StringJumpTable& stringSwitchJumpTable(int tableIndex) { RELEASE_ASSERT(m_rareData); return m_rareData->m_stringSwitchJumpTables[tableIndex]; }
627
628     // Live callee registers at yield points.
629     const FastBitVector& liveCalleeLocalsAtYield(unsigned index) const
630     {
631         RELEASE_ASSERT(m_rareData);
632         return m_rareData->m_liveCalleeLocalsAtYield[index];
633     }
634     FastBitVector& liveCalleeLocalsAtYield(unsigned index)
635     {
636         RELEASE_ASSERT(m_rareData);
637         return m_rareData->m_liveCalleeLocalsAtYield[index];
638     }
639
640     EvalCodeCache& evalCodeCache() { createRareDataIfNecessary(); return m_rareData->m_evalCodeCache; }
641
642     enum ShrinkMode {
643         // Shrink prior to generating machine code that may point directly into vectors.
644         EarlyShrink,
645
646         // Shrink after generating machine code, and after possibly creating new vectors
647         // and appending to others. At this time it is not safe to shrink certain vectors
648         // because we would have generated machine code that references them directly.
649         LateShrink
650     };
651     void shrinkToFit(ShrinkMode);
652
653     // Functions for controlling when JITting kicks in, in a mixed mode
654     // execution world.
655
656     bool checkIfJITThresholdReached()
657     {
658         return m_llintExecuteCounter.checkIfThresholdCrossedAndSet(this);
659     }
660
661     void dontJITAnytimeSoon()
662     {
663         m_llintExecuteCounter.deferIndefinitely();
664     }
665
666     void jitAfterWarmUp()
667     {
668         m_llintExecuteCounter.setNewThreshold(Options::thresholdForJITAfterWarmUp(), this);
669     }
670
671     void jitSoon()
672     {
673         m_llintExecuteCounter.setNewThreshold(Options::thresholdForJITSoon(), this);
674     }
675
676     const BaselineExecutionCounter& llintExecuteCounter() const
677     {
678         return m_llintExecuteCounter;
679     }
680
681     // Functions for controlling when tiered compilation kicks in. This
682     // controls both when the optimizing compiler is invoked and when OSR
683     // entry happens. Two triggers exist: the loop trigger and the return
684     // trigger. In either case, when an addition to m_jitExecuteCounter
685     // causes it to become non-negative, the optimizing compiler is
686     // invoked. This includes a fast check to see if this CodeBlock has
687     // already been optimized (i.e. replacement() returns a CodeBlock
688     // that was optimized with a higher tier JIT than this one). In the
689     // case of the loop trigger, if the optimized compilation succeeds
690     // (or has already succeeded in the past) then OSR is attempted to
691     // redirect program flow into the optimized code.
692
693     // These functions are called from within the optimization triggers,
694     // and are used as a single point at which we define the heuristics
695     // for how much warm-up is mandated before the next optimization
696     // trigger files. All CodeBlocks start out with optimizeAfterWarmUp(),
697     // as this is called from the CodeBlock constructor.
698
699     // When we observe a lot of speculation failures, we trigger a
700     // reoptimization. But each time, we increase the optimization trigger
701     // to avoid thrashing.
702     JS_EXPORT_PRIVATE unsigned reoptimizationRetryCounter() const;
703     void countReoptimization();
704 #if ENABLE(JIT)
705     static unsigned numberOfLLIntBaselineCalleeSaveRegisters() { return RegisterSet::llintBaselineCalleeSaveRegisters().numberOfSetRegisters(); }
706     static size_t llintBaselineCalleeSaveSpaceAsVirtualRegisters();
707     size_t calleeSaveSpaceAsVirtualRegisters();
708
709     unsigned numberOfDFGCompiles();
710
711     int32_t codeTypeThresholdMultiplier() const;
712
713     int32_t adjustedCounterValue(int32_t desiredThreshold);
714
715     int32_t* addressOfJITExecuteCounter()
716     {
717         return &m_jitExecuteCounter.m_counter;
718     }
719
720     static ptrdiff_t offsetOfJITExecuteCounter() { return OBJECT_OFFSETOF(CodeBlock, m_jitExecuteCounter) + OBJECT_OFFSETOF(BaselineExecutionCounter, m_counter); }
721     static ptrdiff_t offsetOfJITExecutionActiveThreshold() { return OBJECT_OFFSETOF(CodeBlock, m_jitExecuteCounter) + OBJECT_OFFSETOF(BaselineExecutionCounter, m_activeThreshold); }
722     static ptrdiff_t offsetOfJITExecutionTotalCount() { return OBJECT_OFFSETOF(CodeBlock, m_jitExecuteCounter) + OBJECT_OFFSETOF(BaselineExecutionCounter, m_totalCount); }
723
724     const BaselineExecutionCounter& jitExecuteCounter() const { return m_jitExecuteCounter; }
725
726     unsigned optimizationDelayCounter() const { return m_optimizationDelayCounter; }
727
728     // Check if the optimization threshold has been reached, and if not,
729     // adjust the heuristics accordingly. Returns true if the threshold has
730     // been reached.
731     bool checkIfOptimizationThresholdReached();
732
733     // Call this to force the next optimization trigger to fire. This is
734     // rarely wise, since optimization triggers are typically more
735     // expensive than executing baseline code.
736     void optimizeNextInvocation();
737
738     // Call this to prevent optimization from happening again. Note that
739     // optimization will still happen after roughly 2^29 invocations,
740     // so this is really meant to delay that as much as possible. This
741     // is called if optimization failed, and we expect it to fail in
742     // the future as well.
743     void dontOptimizeAnytimeSoon();
744
745     // Call this to reinitialize the counter to its starting state,
746     // forcing a warm-up to happen before the next optimization trigger
747     // fires. This is called in the CodeBlock constructor. It also
748     // makes sense to call this if an OSR exit occurred. Note that
749     // OSR exit code is code generated, so the value of the execute
750     // counter that this corresponds to is also available directly.
751     void optimizeAfterWarmUp();
752
753     // Call this to force an optimization trigger to fire only after
754     // a lot of warm-up.
755     void optimizeAfterLongWarmUp();
756
757     // Call this to cause an optimization trigger to fire soon, but
758     // not necessarily the next one. This makes sense if optimization
759     // succeeds. Successfuly optimization means that all calls are
760     // relinked to the optimized code, so this only affects call
761     // frames that are still executing this CodeBlock. The value here
762     // is tuned to strike a balance between the cost of OSR entry
763     // (which is too high to warrant making every loop back edge to
764     // trigger OSR immediately) and the cost of executing baseline
765     // code (which is high enough that we don't necessarily want to
766     // have a full warm-up). The intuition for calling this instead of
767     // optimizeNextInvocation() is for the case of recursive functions
768     // with loops. Consider that there may be N call frames of some
769     // recursive function, for a reasonably large value of N. The top
770     // one triggers optimization, and then returns, and then all of
771     // the others return. We don't want optimization to be triggered on
772     // each return, as that would be superfluous. It only makes sense
773     // to trigger optimization if one of those functions becomes hot
774     // in the baseline code.
775     void optimizeSoon();
776
777     void forceOptimizationSlowPathConcurrently();
778
779     void setOptimizationThresholdBasedOnCompilationResult(CompilationResult);
780     
781     uint32_t osrExitCounter() const { return m_osrExitCounter; }
782
783     void countOSRExit() { m_osrExitCounter++; }
784
785     uint32_t* addressOfOSRExitCounter() { return &m_osrExitCounter; }
786
787     static ptrdiff_t offsetOfOSRExitCounter() { return OBJECT_OFFSETOF(CodeBlock, m_osrExitCounter); }
788
789     uint32_t adjustedExitCountThreshold(uint32_t desiredThreshold);
790     uint32_t exitCountThresholdForReoptimization();
791     uint32_t exitCountThresholdForReoptimizationFromLoop();
792     bool shouldReoptimizeNow();
793     bool shouldReoptimizeFromLoopNow();
794
795     void setCalleeSaveRegisters(RegisterSet);
796     void setCalleeSaveRegisters(std::unique_ptr<RegisterAtOffsetList>);
797     
798     RegisterAtOffsetList* calleeSaveRegisters() const { return m_calleeSaveRegisters.get(); }
799 #else // No JIT
800     static unsigned numberOfLLIntBaselineCalleeSaveRegisters() { return 0; }
801     static size_t llintBaselineCalleeSaveSpaceAsVirtualRegisters() { return 0; };
802     void optimizeAfterWarmUp() { }
803     unsigned numberOfDFGCompiles() { return 0; }
804 #endif
805
806     bool shouldOptimizeNow();
807     void updateAllValueProfilePredictions();
808     void updateAllArrayPredictions();
809     void updateAllPredictions();
810
811     unsigned frameRegisterCount();
812     int stackPointerOffset();
813
814     bool hasOpDebugForLineAndColumn(unsigned line, unsigned column);
815
816     bool hasDebuggerRequests() const { return m_debuggerRequests; }
817     void* debuggerRequestsAddress() { return &m_debuggerRequests; }
818
819     void addBreakpoint(unsigned numBreakpoints);
820     void removeBreakpoint(unsigned numBreakpoints)
821     {
822         ASSERT(m_numBreakpoints >= numBreakpoints);
823         m_numBreakpoints -= numBreakpoints;
824     }
825
826     enum SteppingMode {
827         SteppingModeDisabled,
828         SteppingModeEnabled
829     };
830     void setSteppingMode(SteppingMode);
831
832     void clearDebuggerRequests()
833     {
834         m_steppingMode = SteppingModeDisabled;
835         m_numBreakpoints = 0;
836     }
837     
838     // FIXME: Make these remaining members private.
839
840     int m_numCalleeLocals;
841     int m_numVars;
842     
843     // This is intentionally public; it's the responsibility of anyone doing any
844     // of the following to hold the lock:
845     //
846     // - Modifying any inline cache in this code block.
847     //
848     // - Quering any inline cache in this code block, from a thread other than
849     //   the main thread.
850     //
851     // Additionally, it's only legal to modify the inline cache on the main
852     // thread. This means that the main thread can query the inline cache without
853     // locking. This is crucial since executing the inline cache is effectively
854     // "querying" it.
855     //
856     // Another exception to the rules is that the GC can do whatever it wants
857     // without holding any locks, because the GC is guaranteed to wait until any
858     // concurrent compilation threads finish what they're doing.
859     mutable ConcurrentJITLock m_lock;
860
861     Atomic<bool> m_visitWeaklyHasBeenCalled;
862
863     bool m_shouldAlwaysBeInlined; // Not a bitfield because the JIT wants to store to it.
864
865 #if ENABLE(JIT)
866     unsigned m_capabilityLevelState : 2; // DFG::CapabilityLevel
867 #endif
868
869     bool m_allTransitionsHaveBeenMarked : 1; // Initialized and used on every GC.
870
871     bool m_didFailFTLCompilation : 1;
872     bool m_hasBeenCompiledWithFTL : 1;
873     bool m_isConstructor : 1;
874     bool m_isStrictMode : 1;
875     unsigned m_codeType : 2; // CodeType
876
877     // Internal methods for use by validation code. It would be private if it wasn't
878     // for the fact that we use it from anonymous namespaces.
879     void beginValidationDidFail();
880     NO_RETURN_DUE_TO_CRASH void endValidationDidFail();
881
882     struct RareData {
883         WTF_MAKE_FAST_ALLOCATED;
884     public:
885         Vector<HandlerInfo> m_exceptionHandlers;
886
887         // Buffers used for large array literals
888         Vector<Vector<JSValue>> m_constantBuffers;
889
890         // Jump Tables
891         Vector<SimpleJumpTable> m_switchJumpTables;
892         Vector<StringJumpTable> m_stringSwitchJumpTables;
893
894         Vector<FastBitVector> m_liveCalleeLocalsAtYield;
895
896         EvalCodeCache m_evalCodeCache;
897     };
898
899     void clearExceptionHandlers()
900     {
901         if (m_rareData)
902             m_rareData->m_exceptionHandlers.clear();
903     }
904
905     void appendExceptionHandler(const HandlerInfo& handler)
906     {
907         createRareDataIfNecessary(); // We may be handling the exception of an inlined call frame.
908         m_rareData->m_exceptionHandlers.append(handler);
909     }
910
911     CallSiteIndex newExceptionHandlingCallSiteIndex(CallSiteIndex originalCallSite);
912
913 #if ENABLE(JIT)
914     void setPCToCodeOriginMap(std::unique_ptr<PCToCodeOriginMap>&&);
915     Optional<CodeOrigin> findPC(void* pc);
916 #endif
917
918 protected:
919     void finalizeLLIntInlineCaches();
920     void finalizeBaselineJITInlineCaches();
921
922 #if ENABLE(DFG_JIT)
923     void tallyFrequentExitSites();
924 #else
925     void tallyFrequentExitSites() { }
926 #endif
927
928 private:
929     friend class CodeBlockSet;
930     
931     CodeBlock* specialOSREntryBlockOrNull();
932     
933     void noticeIncomingCall(ExecState* callerFrame);
934     
935     double optimizationThresholdScalingFactor();
936
937     void updateAllPredictionsAndCountLiveness(unsigned& numberOfLiveNonArgumentValueProfiles, unsigned& numberOfSamplesInProfiles);
938
939     void setConstantRegisters(const Vector<WriteBarrier<Unknown>>& constants, const Vector<SourceCodeRepresentation>& constantsSourceCodeRepresentation);
940
941     void replaceConstant(int index, JSValue value)
942     {
943         ASSERT(isConstantRegisterIndex(index) && static_cast<size_t>(index - FirstConstantRegisterIndex) < m_constantRegisters.size());
944         m_constantRegisters[index - FirstConstantRegisterIndex].set(m_globalObject->vm(), this, value);
945     }
946
947     void dumpBytecode(
948         PrintStream&, ExecState*, const Instruction* begin, const Instruction*&,
949         const StubInfoMap& = StubInfoMap(), const CallLinkInfoMap& = CallLinkInfoMap());
950
951     CString registerName(int r) const;
952     CString constantName(int index) const;
953     void printUnaryOp(PrintStream&, ExecState*, int location, const Instruction*&, const char* op);
954     void printBinaryOp(PrintStream&, ExecState*, int location, const Instruction*&, const char* op);
955     void printConditionalJump(PrintStream&, ExecState*, const Instruction*, const Instruction*&, int location, const char* op);
956     void printGetByIdOp(PrintStream&, ExecState*, int location, const Instruction*&);
957     void printGetByIdCacheStatus(PrintStream&, ExecState*, int location, const StubInfoMap&);
958     enum CacheDumpMode { DumpCaches, DontDumpCaches };
959     void printCallOp(PrintStream&, ExecState*, int location, const Instruction*&, const char* op, CacheDumpMode, bool& hasPrintedProfiling, const CallLinkInfoMap&);
960     void printPutByIdOp(PrintStream&, ExecState*, int location, const Instruction*&, const char* op);
961     void printPutByIdCacheStatus(PrintStream&, int location, const StubInfoMap&);
962     void printLocationAndOp(PrintStream&, ExecState*, int location, const Instruction*&, const char* op);
963     void printLocationOpAndRegisterOperand(PrintStream&, ExecState*, int location, const Instruction*& it, const char* op, int operand);
964
965     void beginDumpProfiling(PrintStream&, bool& hasPrintedProfiling);
966     void dumpValueProfiling(PrintStream&, const Instruction*&, bool& hasPrintedProfiling);
967     void dumpArrayProfiling(PrintStream&, const Instruction*&, bool& hasPrintedProfiling);
968     void dumpRareCaseProfile(PrintStream&, const char* name, RareCaseProfile*, bool& hasPrintedProfiling);
969     void dumpResultProfile(PrintStream&, ResultProfile*, bool& hasPrintedProfiling);
970
971     bool shouldVisitStrongly();
972     bool shouldJettisonDueToWeakReference();
973     bool shouldJettisonDueToOldAge();
974     
975     void propagateTransitions(SlotVisitor&);
976     void determineLiveness(SlotVisitor&);
977         
978     void stronglyVisitStrongReferences(SlotVisitor&);
979     void stronglyVisitWeakReferences(SlotVisitor&);
980     void visitOSRExitTargets(SlotVisitor&);
981
982     std::chrono::milliseconds timeSinceCreation()
983     {
984         return std::chrono::duration_cast<std::chrono::milliseconds>(
985             std::chrono::steady_clock::now() - m_creationTime);
986     }
987
988     void createRareDataIfNecessary()
989     {
990         if (!m_rareData)
991             m_rareData = std::make_unique<RareData>();
992     }
993
994     void insertBasicBlockBoundariesForControlFlowProfiler(RefCountedArray<Instruction>&);
995
996     WriteBarrier<UnlinkedCodeBlock> m_unlinkedCode;
997     int m_numParameters;
998     union {
999         unsigned m_debuggerRequests;
1000         struct {
1001             unsigned m_hasDebuggerStatement : 1;
1002             unsigned m_steppingMode : 1;
1003             unsigned m_numBreakpoints : 30;
1004         };
1005     };
1006     WriteBarrier<ExecutableBase> m_ownerExecutable;
1007     VM* m_vm;
1008
1009     RefCountedArray<Instruction> m_instructions;
1010     VirtualRegister m_thisRegister;
1011     VirtualRegister m_scopeRegister;
1012     mutable CodeBlockHash m_hash;
1013
1014     RefPtr<SourceProvider> m_source;
1015     unsigned m_sourceOffset;
1016     unsigned m_firstLineColumnOffset;
1017
1018     RefCountedArray<LLIntCallLinkInfo> m_llintCallLinkInfos;
1019     SentinelLinkedList<LLIntCallLinkInfo, BasicRawSentinelNode<LLIntCallLinkInfo>> m_incomingLLIntCalls;
1020     RefPtr<JITCode> m_jitCode;
1021 #if ENABLE(JIT)
1022     std::unique_ptr<RegisterAtOffsetList> m_calleeSaveRegisters;
1023     Bag<StructureStubInfo> m_stubInfos;
1024     Bag<ByValInfo> m_byValInfos;
1025     Bag<CallLinkInfo> m_callLinkInfos;
1026     SentinelLinkedList<CallLinkInfo, BasicRawSentinelNode<CallLinkInfo>> m_incomingCalls;
1027     SentinelLinkedList<PolymorphicCallNode, BasicRawSentinelNode<PolymorphicCallNode>> m_incomingPolymorphicCalls;
1028     std::unique_ptr<PCToCodeOriginMap> m_pcToCodeOriginMap;
1029 #endif
1030     std::unique_ptr<CompactJITCodeMap> m_jitCodeMap;
1031 #if ENABLE(DFG_JIT)
1032     // This is relevant to non-DFG code blocks that serve as the profiled code block
1033     // for DFG code blocks.
1034     DFG::ExitProfile m_exitProfile;
1035     CompressedLazyOperandValueProfileHolder m_lazyOperandValueProfiles;
1036 #endif
1037     RefCountedArray<ValueProfile> m_argumentValueProfiles;
1038     RefCountedArray<ValueProfile> m_valueProfiles;
1039     SegmentedVector<RareCaseProfile, 8> m_rareCaseProfiles;
1040     SegmentedVector<ResultProfile, 8> m_resultProfiles;
1041     typedef HashMap<unsigned, unsigned, IntHash<unsigned>, WTF::UnsignedWithZeroKeyHashTraits<unsigned>> BytecodeOffsetToResultProfileIndexMap;
1042     std::unique_ptr<BytecodeOffsetToResultProfileIndexMap> m_bytecodeOffsetToResultProfileIndexMap;
1043     RefCountedArray<ArrayAllocationProfile> m_arrayAllocationProfiles;
1044     ArrayProfileVector m_arrayProfiles;
1045     RefCountedArray<ObjectAllocationProfile> m_objectAllocationProfiles;
1046
1047     // Constant Pool
1048     COMPILE_ASSERT(sizeof(Register) == sizeof(WriteBarrier<Unknown>), Register_must_be_same_size_as_WriteBarrier_Unknown);
1049     // TODO: This could just be a pointer to m_unlinkedCodeBlock's data, but the DFG mutates
1050     // it, so we're stuck with it for now.
1051     Vector<WriteBarrier<Unknown>> m_constantRegisters;
1052     Vector<SourceCodeRepresentation> m_constantsSourceCodeRepresentation;
1053     RefCountedArray<WriteBarrier<FunctionExecutable>> m_functionDecls;
1054     RefCountedArray<WriteBarrier<FunctionExecutable>> m_functionExprs;
1055
1056     WriteBarrier<CodeBlock> m_alternative;
1057     
1058     BaselineExecutionCounter m_llintExecuteCounter;
1059
1060     BaselineExecutionCounter m_jitExecuteCounter;
1061     uint32_t m_osrExitCounter;
1062     uint16_t m_optimizationDelayCounter;
1063     uint16_t m_reoptimizationRetryCounter;
1064
1065     std::chrono::steady_clock::time_point m_creationTime;
1066
1067     std::unique_ptr<BytecodeLivenessAnalysis> m_livenessAnalysis;
1068
1069     std::unique_ptr<RareData> m_rareData;
1070
1071     UnconditionalFinalizer m_unconditionalFinalizer;
1072     WeakReferenceHarvester m_weakReferenceHarvester;
1073 };
1074
1075 // Program code is not marked by any function, so we make the global object
1076 // responsible for marking it.
1077
1078 class GlobalCodeBlock : public CodeBlock {
1079     typedef CodeBlock Base;
1080     DECLARE_INFO;
1081
1082 protected:
1083     GlobalCodeBlock(VM* vm, Structure* structure, CopyParsedBlockTag, GlobalCodeBlock& other)
1084         : CodeBlock(vm, structure, CopyParsedBlock, other)
1085     {
1086     }
1087
1088     GlobalCodeBlock(VM* vm, Structure* structure, ScriptExecutable* ownerExecutable, UnlinkedCodeBlock* unlinkedCodeBlock, JSScope* scope, PassRefPtr<SourceProvider> sourceProvider, unsigned sourceOffset, unsigned firstLineColumnOffset)
1089         : CodeBlock(vm, structure, ownerExecutable, unlinkedCodeBlock, scope, sourceProvider, sourceOffset, firstLineColumnOffset)
1090     {
1091     }
1092 };
1093
1094 class ProgramCodeBlock : public GlobalCodeBlock {
1095 public:
1096     typedef GlobalCodeBlock Base;
1097     DECLARE_INFO;
1098
1099     static ProgramCodeBlock* create(VM* vm, CopyParsedBlockTag, ProgramCodeBlock& other)
1100     {
1101         ProgramCodeBlock* instance = new (NotNull, allocateCell<ProgramCodeBlock>(vm->heap))
1102             ProgramCodeBlock(vm, vm->programCodeBlockStructure.get(), CopyParsedBlock, other);
1103         instance->finishCreation(*vm, CopyParsedBlock, other);
1104         return instance;
1105     }
1106
1107     static ProgramCodeBlock* create(VM* vm, ProgramExecutable* ownerExecutable, UnlinkedProgramCodeBlock* unlinkedCodeBlock,
1108         JSScope* scope, PassRefPtr<SourceProvider> sourceProvider, unsigned firstLineColumnOffset)
1109     {
1110         ProgramCodeBlock* instance = new (NotNull, allocateCell<ProgramCodeBlock>(vm->heap))
1111             ProgramCodeBlock(vm, vm->programCodeBlockStructure.get(), ownerExecutable, unlinkedCodeBlock, scope, sourceProvider, firstLineColumnOffset);
1112         instance->finishCreation(*vm, ownerExecutable, unlinkedCodeBlock, scope);
1113         return instance;
1114     }
1115
1116     static Structure* createStructure(VM& vm, JSGlobalObject* globalObject, JSValue prototype)
1117     {
1118         return Structure::create(vm, globalObject, prototype, TypeInfo(CellType, StructureFlags), info());
1119     }
1120
1121 private:
1122     ProgramCodeBlock(VM* vm, Structure* structure, CopyParsedBlockTag, ProgramCodeBlock& other)
1123         : GlobalCodeBlock(vm, structure, CopyParsedBlock, other)
1124     {
1125     }
1126
1127     ProgramCodeBlock(VM* vm, Structure* structure, ProgramExecutable* ownerExecutable, UnlinkedProgramCodeBlock* unlinkedCodeBlock,
1128         JSScope* scope, PassRefPtr<SourceProvider> sourceProvider, unsigned firstLineColumnOffset)
1129         : GlobalCodeBlock(vm, structure, ownerExecutable, unlinkedCodeBlock, scope, sourceProvider, 0, firstLineColumnOffset)
1130     {
1131     }
1132
1133     static void destroy(JSCell*);
1134 };
1135
1136 class ModuleProgramCodeBlock : public GlobalCodeBlock {
1137 public:
1138     typedef GlobalCodeBlock Base;
1139     DECLARE_INFO;
1140
1141     static ModuleProgramCodeBlock* create(VM* vm, CopyParsedBlockTag, ModuleProgramCodeBlock& other)
1142     {
1143         ModuleProgramCodeBlock* instance = new (NotNull, allocateCell<ModuleProgramCodeBlock>(vm->heap))
1144             ModuleProgramCodeBlock(vm, vm->moduleProgramCodeBlockStructure.get(), CopyParsedBlock, other);
1145         instance->finishCreation(*vm, CopyParsedBlock, other);
1146         return instance;
1147     }
1148
1149     static ModuleProgramCodeBlock* create(VM* vm, ModuleProgramExecutable* ownerExecutable, UnlinkedModuleProgramCodeBlock* unlinkedCodeBlock,
1150         JSScope* scope, PassRefPtr<SourceProvider> sourceProvider, unsigned firstLineColumnOffset)
1151     {
1152         ModuleProgramCodeBlock* instance = new (NotNull, allocateCell<ModuleProgramCodeBlock>(vm->heap))
1153             ModuleProgramCodeBlock(vm, vm->moduleProgramCodeBlockStructure.get(), ownerExecutable, unlinkedCodeBlock, scope, sourceProvider, firstLineColumnOffset);
1154         instance->finishCreation(*vm, ownerExecutable, unlinkedCodeBlock, scope);
1155         return instance;
1156     }
1157
1158     static Structure* createStructure(VM& vm, JSGlobalObject* globalObject, JSValue prototype)
1159     {
1160         return Structure::create(vm, globalObject, prototype, TypeInfo(CellType, StructureFlags), info());
1161     }
1162
1163 private:
1164     ModuleProgramCodeBlock(VM* vm, Structure* structure, CopyParsedBlockTag, ModuleProgramCodeBlock& other)
1165         : GlobalCodeBlock(vm, structure, CopyParsedBlock, other)
1166     {
1167     }
1168
1169     ModuleProgramCodeBlock(VM* vm, Structure* structure, ModuleProgramExecutable* ownerExecutable, UnlinkedModuleProgramCodeBlock* unlinkedCodeBlock,
1170         JSScope* scope, PassRefPtr<SourceProvider> sourceProvider, unsigned firstLineColumnOffset)
1171         : GlobalCodeBlock(vm, structure, ownerExecutable, unlinkedCodeBlock, scope, sourceProvider, 0, firstLineColumnOffset)
1172     {
1173     }
1174
1175     static void destroy(JSCell*);
1176 };
1177
1178 class EvalCodeBlock : public GlobalCodeBlock {
1179 public:
1180     typedef GlobalCodeBlock Base;
1181     DECLARE_INFO;
1182
1183     static EvalCodeBlock* create(VM* vm, CopyParsedBlockTag, EvalCodeBlock& other)
1184     {
1185         EvalCodeBlock* instance = new (NotNull, allocateCell<EvalCodeBlock>(vm->heap))
1186             EvalCodeBlock(vm, vm->evalCodeBlockStructure.get(), CopyParsedBlock, other);
1187         instance->finishCreation(*vm, CopyParsedBlock, other);
1188         return instance;
1189     }
1190
1191     static EvalCodeBlock* create(VM* vm, EvalExecutable* ownerExecutable, UnlinkedEvalCodeBlock* unlinkedCodeBlock,
1192         JSScope* scope, PassRefPtr<SourceProvider> sourceProvider)
1193     {
1194         EvalCodeBlock* instance = new (NotNull, allocateCell<EvalCodeBlock>(vm->heap))
1195             EvalCodeBlock(vm, vm->evalCodeBlockStructure.get(), ownerExecutable, unlinkedCodeBlock, scope, sourceProvider);
1196         instance->finishCreation(*vm, ownerExecutable, unlinkedCodeBlock, scope);
1197         return instance;
1198     }
1199
1200     static Structure* createStructure(VM& vm, JSGlobalObject* globalObject, JSValue prototype)
1201     {
1202         return Structure::create(vm, globalObject, prototype, TypeInfo(CellType, StructureFlags), info());
1203     }
1204
1205     const Identifier& variable(unsigned index) { return unlinkedEvalCodeBlock()->variable(index); }
1206     unsigned numVariables() { return unlinkedEvalCodeBlock()->numVariables(); }
1207     
1208 private:
1209     EvalCodeBlock(VM* vm, Structure* structure, CopyParsedBlockTag, EvalCodeBlock& other)
1210         : GlobalCodeBlock(vm, structure, CopyParsedBlock, other)
1211     {
1212     }
1213         
1214     EvalCodeBlock(VM* vm, Structure* structure, EvalExecutable* ownerExecutable, UnlinkedEvalCodeBlock* unlinkedCodeBlock,
1215         JSScope* scope, PassRefPtr<SourceProvider> sourceProvider)
1216         : GlobalCodeBlock(vm, structure, ownerExecutable, unlinkedCodeBlock, scope, sourceProvider, 0, 1)
1217     {
1218     }
1219     
1220     static void destroy(JSCell*);
1221
1222 private:
1223     UnlinkedEvalCodeBlock* unlinkedEvalCodeBlock() const { return jsCast<UnlinkedEvalCodeBlock*>(unlinkedCodeBlock()); }
1224 };
1225
1226 class FunctionCodeBlock : public CodeBlock {
1227 public:
1228     typedef CodeBlock Base;
1229     DECLARE_INFO;
1230
1231     static FunctionCodeBlock* create(VM* vm, CopyParsedBlockTag, FunctionCodeBlock& other)
1232     {
1233         FunctionCodeBlock* instance = new (NotNull, allocateCell<FunctionCodeBlock>(vm->heap))
1234             FunctionCodeBlock(vm, vm->functionCodeBlockStructure.get(), CopyParsedBlock, other);
1235         instance->finishCreation(*vm, CopyParsedBlock, other);
1236         return instance;
1237     }
1238
1239     static FunctionCodeBlock* create(VM* vm, FunctionExecutable* ownerExecutable, UnlinkedFunctionCodeBlock* unlinkedCodeBlock, JSScope* scope,
1240         PassRefPtr<SourceProvider> sourceProvider, unsigned sourceOffset, unsigned firstLineColumnOffset)
1241     {
1242         FunctionCodeBlock* instance = new (NotNull, allocateCell<FunctionCodeBlock>(vm->heap))
1243             FunctionCodeBlock(vm, vm->functionCodeBlockStructure.get(), ownerExecutable, unlinkedCodeBlock, scope, sourceProvider, sourceOffset, firstLineColumnOffset);
1244         instance->finishCreation(*vm, ownerExecutable, unlinkedCodeBlock, scope);
1245         return instance;
1246     }
1247
1248     static Structure* createStructure(VM& vm, JSGlobalObject* globalObject, JSValue prototype)
1249     {
1250         return Structure::create(vm, globalObject, prototype, TypeInfo(CellType, StructureFlags), info());
1251     }
1252
1253 private:
1254     FunctionCodeBlock(VM* vm, Structure* structure, CopyParsedBlockTag, FunctionCodeBlock& other)
1255         : CodeBlock(vm, structure, CopyParsedBlock, other)
1256     {
1257     }
1258
1259     FunctionCodeBlock(VM* vm, Structure* structure, FunctionExecutable* ownerExecutable, UnlinkedFunctionCodeBlock* unlinkedCodeBlock, JSScope* scope,
1260         PassRefPtr<SourceProvider> sourceProvider, unsigned sourceOffset, unsigned firstLineColumnOffset)
1261         : CodeBlock(vm, structure, ownerExecutable, unlinkedCodeBlock, scope, sourceProvider, sourceOffset, firstLineColumnOffset)
1262     {
1263     }
1264     
1265     static void destroy(JSCell*);
1266 };
1267
1268 #if ENABLE(WEBASSEMBLY)
1269 class WebAssemblyCodeBlock : public CodeBlock {
1270 public:
1271     typedef CodeBlock Base;
1272     DECLARE_INFO;
1273
1274     static WebAssemblyCodeBlock* create(VM* vm, CopyParsedBlockTag, WebAssemblyCodeBlock& other)
1275     {
1276         WebAssemblyCodeBlock* instance = new (NotNull, allocateCell<WebAssemblyCodeBlock>(vm->heap))
1277             WebAssemblyCodeBlock(vm, vm->webAssemblyCodeBlockStructure.get(), CopyParsedBlock, other);
1278         instance->finishCreation(*vm, CopyParsedBlock, other);
1279         return instance;
1280     }
1281
1282     static WebAssemblyCodeBlock* create(VM* vm, WebAssemblyExecutable* ownerExecutable, JSGlobalObject* globalObject)
1283     {
1284         WebAssemblyCodeBlock* instance = new (NotNull, allocateCell<WebAssemblyCodeBlock>(vm->heap))
1285             WebAssemblyCodeBlock(vm, vm->webAssemblyCodeBlockStructure.get(), ownerExecutable, globalObject);
1286         instance->finishCreation(*vm, ownerExecutable, globalObject);
1287         return instance;
1288     }
1289
1290     static Structure* createStructure(VM& vm, JSGlobalObject* globalObject, JSValue prototype)
1291     {
1292         return Structure::create(vm, globalObject, prototype, TypeInfo(CellType, StructureFlags), info());
1293     }
1294
1295 private:
1296     WebAssemblyCodeBlock(VM* vm, Structure* structure, CopyParsedBlockTag, WebAssemblyCodeBlock& other)
1297         : CodeBlock(vm, structure, CopyParsedBlock, other)
1298     {
1299     }
1300
1301     WebAssemblyCodeBlock(VM* vm, Structure* structure, WebAssemblyExecutable* ownerExecutable, JSGlobalObject* globalObject)
1302         : CodeBlock(vm, structure, ownerExecutable, globalObject)
1303     {
1304     }
1305
1306     static void destroy(JSCell*);
1307 };
1308 #endif
1309
1310 inline Register& ExecState::r(int index)
1311 {
1312     CodeBlock* codeBlock = this->codeBlock();
1313     if (codeBlock->isConstantRegisterIndex(index))
1314         return *reinterpret_cast<Register*>(&codeBlock->constantRegister(index));
1315     return this[index];
1316 }
1317
1318 inline Register& ExecState::r(VirtualRegister reg)
1319 {
1320     return r(reg.offset());
1321 }
1322
1323 inline Register& ExecState::uncheckedR(int index)
1324 {
1325     RELEASE_ASSERT(index < FirstConstantRegisterIndex);
1326     return this[index];
1327 }
1328
1329 inline Register& ExecState::uncheckedR(VirtualRegister reg)
1330 {
1331     return uncheckedR(reg.offset());
1332 }
1333
1334 inline void CodeBlock::clearVisitWeaklyHasBeenCalled()
1335 {
1336     m_visitWeaklyHasBeenCalled.store(false, std::memory_order_relaxed);
1337 }
1338
1339 inline void CodeBlockSet::mark(const LockHolder& locker, void* candidateCodeBlock)
1340 {
1341     ASSERT(m_lock.isLocked());
1342     // We have to check for 0 and -1 because those are used by the HashMap as markers.
1343     uintptr_t value = reinterpret_cast<uintptr_t>(candidateCodeBlock);
1344     
1345     // This checks for both of those nasty cases in one go.
1346     // 0 + 1 = 1
1347     // -1 + 1 = 0
1348     if (value + 1 <= 1)
1349         return;
1350
1351     CodeBlock* codeBlock = static_cast<CodeBlock*>(candidateCodeBlock); 
1352     if (!m_oldCodeBlocks.contains(codeBlock) && !m_newCodeBlocks.contains(codeBlock))
1353         return;
1354
1355     mark(locker, codeBlock);
1356 }
1357
1358 inline void CodeBlockSet::mark(const LockHolder&, CodeBlock* codeBlock)
1359 {
1360     if (!codeBlock)
1361         return;
1362
1363     // Try to recover gracefully if we forget to execute a barrier for a
1364     // CodeBlock that does value profiling. This is probably overkill, but we
1365     // have always done it.
1366     Heap::heap(codeBlock)->writeBarrier(codeBlock);
1367
1368     m_currentlyExecuting.add(codeBlock);
1369 }
1370
1371 template <typename Functor> inline void ScriptExecutable::forEachCodeBlock(Functor&& functor)
1372 {
1373     switch (type()) {
1374     case ProgramExecutableType: {
1375         if (CodeBlock* codeBlock = static_cast<CodeBlock*>(jsCast<ProgramExecutable*>(this)->m_programCodeBlock.get()))
1376             codeBlock->forEachRelatedCodeBlock(std::forward<Functor>(functor));
1377         break;
1378     }
1379
1380     case EvalExecutableType: {
1381         if (CodeBlock* codeBlock = static_cast<CodeBlock*>(jsCast<EvalExecutable*>(this)->m_evalCodeBlock.get()))
1382             codeBlock->forEachRelatedCodeBlock(std::forward<Functor>(functor));
1383         break;
1384     }
1385
1386     case FunctionExecutableType: {
1387         Functor f(std::forward<Functor>(functor));
1388         FunctionExecutable* executable = jsCast<FunctionExecutable*>(this);
1389         if (CodeBlock* codeBlock = static_cast<CodeBlock*>(executable->m_codeBlockForCall.get()))
1390             codeBlock->forEachRelatedCodeBlock(f);
1391         if (CodeBlock* codeBlock = static_cast<CodeBlock*>(executable->m_codeBlockForConstruct.get()))
1392             codeBlock->forEachRelatedCodeBlock(f);
1393         break;
1394     }
1395
1396     case ModuleProgramExecutableType: {
1397         if (CodeBlock* codeBlock = static_cast<CodeBlock*>(jsCast<ModuleProgramExecutable*>(this)->m_moduleProgramCodeBlock.get()))
1398             codeBlock->forEachRelatedCodeBlock(std::forward<Functor>(functor));
1399         break;
1400     }
1401
1402     default:
1403         RELEASE_ASSERT_NOT_REACHED();
1404     }
1405 }
1406
1407 } // namespace JSC
1408
1409 #endif // CodeBlock_h