Make the HeapVerifier useful again.
[WebKit-https.git] / Source / JavaScriptCore / heap / Heap.cpp
1 /*
2  *  Copyright (C) 2003-2017 Apple Inc. All rights reserved.
3  *  Copyright (C) 2007 Eric Seidel <eric@webkit.org>
4  *
5  *  This library is free software; you can redistribute it and/or
6  *  modify it under the terms of the GNU Lesser General Public
7  *  License as published by the Free Software Foundation; either
8  *  version 2 of the License, or (at your option) any later version.
9  *
10  *  This library is distributed in the hope that it will be useful,
11  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
12  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  *  Lesser General Public License for more details.
14  *
15  *  You should have received a copy of the GNU Lesser General Public
16  *  License along with this library; if not, write to the Free Software
17  *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
18  *
19  */
20
21 #include "config.h"
22 #include "Heap.h"
23
24 #include "CodeBlock.h"
25 #include "CodeBlockSetInlines.h"
26 #include "CollectingScope.h"
27 #include "ConservativeRoots.h"
28 #include "DFGWorklistInlines.h"
29 #include "EdenGCActivityCallback.h"
30 #include "Exception.h"
31 #include "FullGCActivityCallback.h"
32 #include "GCActivityCallback.h"
33 #include "GCIncomingRefCountedSetInlines.h"
34 #include "GCSegmentedArrayInlines.h"
35 #include "GCTypeMap.h"
36 #include "HasOwnPropertyCache.h"
37 #include "HeapHelperPool.h"
38 #include "HeapIterationScope.h"
39 #include "HeapProfiler.h"
40 #include "HeapSnapshot.h"
41 #include "HeapVerifier.h"
42 #include "IncrementalSweeper.h"
43 #include "Interpreter.h"
44 #include "JITStubRoutineSet.h"
45 #include "JITWorklist.h"
46 #include "JSCInlines.h"
47 #include "JSGlobalObject.h"
48 #include "JSLock.h"
49 #include "JSVirtualMachineInternal.h"
50 #include "MachineStackMarker.h"
51 #include "MarkedSpaceInlines.h"
52 #include "MarkingConstraintSet.h"
53 #include "PreventCollectionScope.h"
54 #include "SamplingProfiler.h"
55 #include "ShadowChicken.h"
56 #include "SpaceTimeMutatorScheduler.h"
57 #include "SuperSampler.h"
58 #include "StochasticSpaceTimeMutatorScheduler.h"
59 #include "StopIfNecessaryTimer.h"
60 #include "SweepingScope.h"
61 #include "SynchronousStopTheWorldMutatorScheduler.h"
62 #include "TypeProfilerLog.h"
63 #include "UnlinkedCodeBlock.h"
64 #include "VM.h"
65 #include "WeakSetInlines.h"
66 #include <algorithm>
67 #include <wtf/CurrentTime.h>
68 #include <wtf/MainThread.h>
69 #include <wtf/ParallelVectorIterator.h>
70 #include <wtf/ProcessID.h>
71 #include <wtf/RAMSize.h>
72 #include <wtf/SimpleStats.h>
73
74 #if USE(FOUNDATION)
75 #if __has_include(<objc/objc-internal.h>)
76 #include <objc/objc-internal.h>
77 #else
78 extern "C" void* objc_autoreleasePoolPush(void);
79 extern "C" void objc_autoreleasePoolPop(void *context);
80 #endif
81 #endif // USE(FOUNDATION)
82
83 using namespace std;
84
85 namespace JSC {
86
87 namespace {
88
89 bool verboseStop = false;
90
91 double maxPauseMS(double thisPauseMS)
92 {
93     static double maxPauseMS;
94     maxPauseMS = std::max(thisPauseMS, maxPauseMS);
95     return maxPauseMS;
96 }
97
98 size_t minHeapSize(HeapType heapType, size_t ramSize)
99 {
100     if (heapType == LargeHeap) {
101         double result = min(
102             static_cast<double>(Options::largeHeapSize()),
103             ramSize * Options::smallHeapRAMFraction());
104         return static_cast<size_t>(result);
105     }
106     return Options::smallHeapSize();
107 }
108
109 size_t proportionalHeapSize(size_t heapSize, size_t ramSize)
110 {
111     if (heapSize < ramSize * Options::smallHeapRAMFraction())
112         return Options::smallHeapGrowthFactor() * heapSize;
113     if (heapSize < ramSize * Options::mediumHeapRAMFraction())
114         return Options::mediumHeapGrowthFactor() * heapSize;
115     return Options::largeHeapGrowthFactor() * heapSize;
116 }
117
118 bool isValidSharedInstanceThreadState(VM* vm)
119 {
120     return vm->currentThreadIsHoldingAPILock();
121 }
122
123 bool isValidThreadState(VM* vm)
124 {
125     if (vm->atomicStringTable() != wtfThreadData().atomicStringTable())
126         return false;
127
128     if (vm->isSharedInstance() && !isValidSharedInstanceThreadState(vm))
129         return false;
130
131     return true;
132 }
133
134 void recordType(VM& vm, TypeCountSet& set, JSCell* cell)
135 {
136     const char* typeName = "[unknown]";
137     const ClassInfo* info = cell->classInfo(vm);
138     if (info && info->className)
139         typeName = info->className;
140     set.add(typeName);
141 }
142
143 bool measurePhaseTiming()
144 {
145     return false;
146 }
147
148 HashMap<const char*, GCTypeMap<SimpleStats>>& timingStats()
149 {
150     static HashMap<const char*, GCTypeMap<SimpleStats>>* result;
151     static std::once_flag once;
152     std::call_once(
153         once,
154         [] {
155             result = new HashMap<const char*, GCTypeMap<SimpleStats>>();
156         });
157     return *result;
158 }
159
160 SimpleStats& timingStats(const char* name, CollectionScope scope)
161 {
162     return timingStats().add(name, GCTypeMap<SimpleStats>()).iterator->value[scope];
163 }
164
165 class TimingScope {
166 public:
167     TimingScope(std::optional<CollectionScope> scope, const char* name)
168         : m_scope(scope)
169         , m_name(name)
170     {
171         if (measurePhaseTiming())
172             m_before = monotonicallyIncreasingTimeMS();
173     }
174     
175     TimingScope(Heap& heap, const char* name)
176         : TimingScope(heap.collectionScope(), name)
177     {
178     }
179     
180     void setScope(std::optional<CollectionScope> scope)
181     {
182         m_scope = scope;
183     }
184     
185     void setScope(Heap& heap)
186     {
187         setScope(heap.collectionScope());
188     }
189     
190     ~TimingScope()
191     {
192         if (measurePhaseTiming()) {
193             double after = monotonicallyIncreasingTimeMS();
194             double timing = after - m_before;
195             SimpleStats& stats = timingStats(m_name, *m_scope);
196             stats.add(timing);
197             dataLog("[GC:", *m_scope, "] ", m_name, " took: ", timing, "ms (average ", stats.mean(), "ms).\n");
198         }
199     }
200 private:
201     std::optional<CollectionScope> m_scope;
202     double m_before;
203     const char* m_name;
204 };
205
206 } // anonymous namespace
207
208 class Heap::Thread : public AutomaticThread {
209 public:
210     Thread(const AbstractLocker& locker, Heap& heap)
211         : AutomaticThread(locker, heap.m_threadLock, heap.m_threadCondition)
212         , m_heap(heap)
213     {
214     }
215     
216 protected:
217     PollResult poll(const AbstractLocker& locker) override
218     {
219         if (m_heap.m_threadShouldStop) {
220             m_heap.notifyThreadStopping(locker);
221             return PollResult::Stop;
222         }
223         if (m_heap.shouldCollectInCollectorThread(locker))
224             return PollResult::Work;
225         return PollResult::Wait;
226     }
227     
228     WorkResult work() override
229     {
230         m_heap.collectInCollectorThread();
231         return WorkResult::Continue;
232     }
233     
234     void threadDidStart() override
235     {
236         WTF::registerGCThread(GCThreadType::Main);
237     }
238
239 private:
240     Heap& m_heap;
241 };
242
243 Heap::Heap(VM* vm, HeapType heapType)
244     : m_heapType(heapType)
245     , m_ramSize(Options::forceRAMSize() ? Options::forceRAMSize() : ramSize())
246     , m_minBytesPerCycle(minHeapSize(m_heapType, m_ramSize))
247     , m_sizeAfterLastCollect(0)
248     , m_sizeAfterLastFullCollect(0)
249     , m_sizeBeforeLastFullCollect(0)
250     , m_sizeAfterLastEdenCollect(0)
251     , m_sizeBeforeLastEdenCollect(0)
252     , m_bytesAllocatedThisCycle(0)
253     , m_bytesAbandonedSinceLastFullCollect(0)
254     , m_maxEdenSize(m_minBytesPerCycle)
255     , m_maxHeapSize(m_minBytesPerCycle)
256     , m_shouldDoFullCollection(false)
257     , m_totalBytesVisited(0)
258     , m_objectSpace(this)
259     , m_extraMemorySize(0)
260     , m_deprecatedExtraMemorySize(0)
261     , m_machineThreads(std::make_unique<MachineThreads>())
262     , m_collectorSlotVisitor(std::make_unique<SlotVisitor>(*this, "C"))
263     , m_mutatorSlotVisitor(std::make_unique<SlotVisitor>(*this, "M"))
264     , m_mutatorMarkStack(std::make_unique<MarkStackArray>())
265     , m_raceMarkStack(std::make_unique<MarkStackArray>())
266     , m_constraintSet(std::make_unique<MarkingConstraintSet>())
267     , m_handleSet(vm)
268     , m_codeBlocks(std::make_unique<CodeBlockSet>())
269     , m_jitStubRoutines(std::make_unique<JITStubRoutineSet>())
270     , m_isSafeToCollect(false)
271     , m_vm(vm)
272     // We seed with 10ms so that GCActivityCallback::didAllocate doesn't continuously 
273     // schedule the timer if we've never done a collection.
274     , m_lastFullGCLength(0.01)
275     , m_lastEdenGCLength(0.01)
276 #if USE(CF)
277     , m_runLoop(CFRunLoopGetCurrent())
278 #endif // USE(CF)
279     , m_fullActivityCallback(GCActivityCallback::createFullTimer(this))
280     , m_edenActivityCallback(GCActivityCallback::createEdenTimer(this))
281     , m_sweeper(adoptRef(new IncrementalSweeper(this)))
282     , m_stopIfNecessaryTimer(adoptRef(new StopIfNecessaryTimer(vm)))
283     , m_deferralDepth(0)
284 #if USE(FOUNDATION)
285     , m_delayedReleaseRecursionCount(0)
286 #endif
287     , m_sharedCollectorMarkStack(std::make_unique<MarkStackArray>())
288     , m_sharedMutatorMarkStack(std::make_unique<MarkStackArray>())
289     , m_helperClient(&heapHelperPool())
290     , m_threadLock(Box<Lock>::create())
291     , m_threadCondition(AutomaticThreadCondition::create())
292 {
293     m_worldState.store(0);
294     
295     if (Options::useConcurrentGC()) {
296         if (Options::useStochasticMutatorScheduler())
297             m_scheduler = std::make_unique<StochasticSpaceTimeMutatorScheduler>(*this);
298         else
299             m_scheduler = std::make_unique<SpaceTimeMutatorScheduler>(*this);
300     } else {
301         // We simulate turning off concurrent GC by making the scheduler say that the world
302         // should always be stopped when the collector is running.
303         m_scheduler = std::make_unique<SynchronousStopTheWorldMutatorScheduler>();
304     }
305     
306     if (Options::verifyHeap())
307         m_verifier = std::make_unique<HeapVerifier>(this, Options::numberOfGCCyclesToRecordForVerification());
308     
309     m_collectorSlotVisitor->optimizeForStoppedMutator();
310
311     LockHolder locker(*m_threadLock);
312     m_thread = adoptRef(new Thread(locker, *this));
313 }
314
315 Heap::~Heap()
316 {
317     forEachSlotVisitor(
318         [&] (SlotVisitor& visitor) {
319             visitor.clearMarkStacks();
320         });
321     m_mutatorMarkStack->clear();
322     m_raceMarkStack->clear();
323     
324     for (WeakBlock* block : m_logicallyEmptyWeakBlocks)
325         WeakBlock::destroy(*this, block);
326 }
327
328 bool Heap::isPagedOut(double deadline)
329 {
330     return m_objectSpace.isPagedOut(deadline);
331 }
332
333 // The VM is being destroyed and the collector will never run again.
334 // Run all pending finalizers now because we won't get another chance.
335 void Heap::lastChanceToFinalize()
336 {
337     MonotonicTime before;
338     if (Options::logGC()) {
339         before = MonotonicTime::now();
340         dataLog("[GC<", RawPointer(this), ">: shutdown ");
341     }
342     
343     RELEASE_ASSERT(!m_vm->entryScope);
344     RELEASE_ASSERT(m_mutatorState == MutatorState::Running);
345     
346     if (m_collectContinuouslyThread) {
347         {
348             LockHolder locker(m_collectContinuouslyLock);
349             m_shouldStopCollectingContinuously = true;
350             m_collectContinuouslyCondition.notifyOne();
351         }
352         waitForThreadCompletion(m_collectContinuouslyThread);
353     }
354     
355     if (Options::logGC())
356         dataLog("1");
357     
358     // Prevent new collections from being started. This is probably not even necessary, since we're not
359     // going to call into anything that starts collections. Still, this makes the algorithm more
360     // obviously sound.
361     m_isSafeToCollect = false;
362     
363     if (Options::logGC())
364         dataLog("2");
365
366     bool isCollecting;
367     {
368         auto locker = holdLock(*m_threadLock);
369         RELEASE_ASSERT(m_lastServedTicket <= m_lastGrantedTicket);
370         isCollecting = m_lastServedTicket < m_lastGrantedTicket;
371     }
372     if (isCollecting) {
373         if (Options::logGC())
374             dataLog("...]\n");
375         
376         // Wait for the current collection to finish.
377         waitForCollector(
378             [&] (const AbstractLocker&) -> bool {
379                 RELEASE_ASSERT(m_lastServedTicket <= m_lastGrantedTicket);
380                 return m_lastServedTicket == m_lastGrantedTicket;
381             });
382         
383         if (Options::logGC())
384             dataLog("[GC<", RawPointer(this), ">: shutdown ");
385     }
386     if (Options::logGC())
387         dataLog("3");
388
389     RELEASE_ASSERT(m_requests.isEmpty());
390     RELEASE_ASSERT(m_lastServedTicket == m_lastGrantedTicket);
391     
392     // Carefully bring the thread down.
393     bool stopped = false;
394     {
395         LockHolder locker(*m_threadLock);
396         stopped = m_thread->tryStop(locker);
397         m_threadShouldStop = true;
398         if (!stopped)
399             m_threadCondition->notifyOne(locker);
400     }
401
402     if (Options::logGC())
403         dataLog("4");
404     
405     if (!stopped)
406         m_thread->join();
407     
408     if (Options::logGC())
409         dataLog("5 ");
410     
411     m_arrayBuffers.lastChanceToFinalize();
412     m_codeBlocks->lastChanceToFinalize(*m_vm);
413     m_objectSpace.stopAllocating();
414     m_objectSpace.lastChanceToFinalize();
415     releaseDelayedReleasedObjects();
416
417     sweepAllLogicallyEmptyWeakBlocks();
418     
419     if (Options::logGC())
420         dataLog((MonotonicTime::now() - before).milliseconds(), "ms]\n");
421 }
422
423 void Heap::releaseDelayedReleasedObjects()
424 {
425 #if USE(FOUNDATION)
426     // We need to guard against the case that releasing an object can create more objects due to the
427     // release calling into JS. When those JS call(s) exit and all locks are being dropped we end up
428     // back here and could try to recursively release objects. We guard that with a recursive entry
429     // count. Only the initial call will release objects, recursive calls simple return and let the
430     // the initial call to the function take care of any objects created during release time.
431     // This also means that we need to loop until there are no objects in m_delayedReleaseObjects
432     // and use a temp Vector for the actual releasing.
433     if (!m_delayedReleaseRecursionCount++) {
434         while (!m_delayedReleaseObjects.isEmpty()) {
435             ASSERT(m_vm->currentThreadIsHoldingAPILock());
436
437             Vector<RetainPtr<CFTypeRef>> objectsToRelease = WTFMove(m_delayedReleaseObjects);
438
439             {
440                 // We need to drop locks before calling out to arbitrary code.
441                 JSLock::DropAllLocks dropAllLocks(m_vm);
442
443                 void* context = objc_autoreleasePoolPush();
444                 objectsToRelease.clear();
445                 objc_autoreleasePoolPop(context);
446             }
447         }
448     }
449     m_delayedReleaseRecursionCount--;
450 #endif
451 }
452
453 void Heap::reportExtraMemoryAllocatedSlowCase(size_t size)
454 {
455     didAllocate(size);
456     collectIfNecessaryOrDefer();
457 }
458
459 void Heap::deprecatedReportExtraMemorySlowCase(size_t size)
460 {
461     m_deprecatedExtraMemorySize += size;
462     reportExtraMemoryAllocatedSlowCase(size);
463 }
464
465 void Heap::reportAbandonedObjectGraph()
466 {
467     // Our clients don't know exactly how much memory they
468     // are abandoning so we just guess for them.
469     size_t abandonedBytes = static_cast<size_t>(0.1 * capacity());
470
471     // We want to accelerate the next collection. Because memory has just 
472     // been abandoned, the next collection has the potential to 
473     // be more profitable. Since allocation is the trigger for collection, 
474     // we hasten the next collection by pretending that we've allocated more memory. 
475     if (m_fullActivityCallback) {
476         m_fullActivityCallback->didAllocate(
477             m_sizeAfterLastCollect - m_sizeAfterLastFullCollect + m_bytesAllocatedThisCycle + m_bytesAbandonedSinceLastFullCollect);
478     }
479     m_bytesAbandonedSinceLastFullCollect += abandonedBytes;
480 }
481
482 void Heap::protect(JSValue k)
483 {
484     ASSERT(k);
485     ASSERT(m_vm->currentThreadIsHoldingAPILock());
486
487     if (!k.isCell())
488         return;
489
490     m_protectedValues.add(k.asCell());
491 }
492
493 bool Heap::unprotect(JSValue k)
494 {
495     ASSERT(k);
496     ASSERT(m_vm->currentThreadIsHoldingAPILock());
497
498     if (!k.isCell())
499         return false;
500
501     return m_protectedValues.remove(k.asCell());
502 }
503
504 void Heap::addReference(JSCell* cell, ArrayBuffer* buffer)
505 {
506     if (m_arrayBuffers.addReference(cell, buffer)) {
507         collectIfNecessaryOrDefer();
508         didAllocate(buffer->gcSizeEstimateInBytes());
509     }
510 }
511
512 void Heap::finalizeUnconditionalFinalizers()
513 {
514     while (m_unconditionalFinalizers.hasNext()) {
515         UnconditionalFinalizer* finalizer = m_unconditionalFinalizers.removeNext();
516         finalizer->finalizeUnconditionally();
517     }
518 }
519
520 void Heap::willStartIterating()
521 {
522     m_objectSpace.willStartIterating();
523 }
524
525 void Heap::didFinishIterating()
526 {
527     m_objectSpace.didFinishIterating();
528 }
529
530 void Heap::completeAllJITPlans()
531 {
532 #if ENABLE(JIT)
533     JITWorklist::instance()->completeAllForVM(*m_vm);
534 #endif // ENABLE(JIT)
535     DFG::completeAllPlansForVM(*m_vm);
536 }
537
538 template<typename Func>
539 void Heap::iterateExecutingAndCompilingCodeBlocks(const Func& func)
540 {
541     m_codeBlocks->iterateCurrentlyExecuting(func);
542     DFG::iterateCodeBlocksForGC(*m_vm, func);
543 }
544
545 template<typename Func>
546 void Heap::iterateExecutingAndCompilingCodeBlocksWithoutHoldingLocks(const Func& func)
547 {
548     Vector<CodeBlock*, 256> codeBlocks;
549     iterateExecutingAndCompilingCodeBlocks(
550         [&] (CodeBlock* codeBlock) {
551             codeBlocks.append(codeBlock);
552         });
553     for (CodeBlock* codeBlock : codeBlocks)
554         func(codeBlock);
555 }
556
557 void Heap::assertSharedMarkStacksEmpty()
558 {
559     bool ok = true;
560     
561     if (!m_sharedCollectorMarkStack->isEmpty()) {
562         dataLog("FATAL: Shared collector mark stack not empty! It has ", m_sharedCollectorMarkStack->size(), " elements.\n");
563         ok = false;
564     }
565     
566     if (!m_sharedMutatorMarkStack->isEmpty()) {
567         dataLog("FATAL: Shared mutator mark stack not empty! It has ", m_sharedMutatorMarkStack->size(), " elements.\n");
568         ok = false;
569     }
570     
571     RELEASE_ASSERT(ok);
572 }
573
574 void Heap::gatherStackRoots(ConservativeRoots& roots)
575 {
576     m_machineThreads->gatherConservativeRoots(roots, *m_jitStubRoutines, *m_codeBlocks, m_currentThreadState);
577 }
578
579 void Heap::gatherJSStackRoots(ConservativeRoots& roots)
580 {
581 #if !ENABLE(JIT)
582     m_vm->interpreter->cloopStack().gatherConservativeRoots(roots, *m_jitStubRoutines, *m_codeBlocks);
583 #else
584     UNUSED_PARAM(roots);
585 #endif
586 }
587
588 void Heap::gatherScratchBufferRoots(ConservativeRoots& roots)
589 {
590 #if ENABLE(DFG_JIT)
591     m_vm->gatherConservativeRoots(roots);
592 #else
593     UNUSED_PARAM(roots);
594 #endif
595 }
596
597 void Heap::beginMarking()
598 {
599     TimingScope timingScope(*this, "Heap::beginMarking");
600     if (m_collectionScope == CollectionScope::Full)
601         m_codeBlocks->clearMarksForFullCollection();
602     m_jitStubRoutines->clearMarks();
603     m_objectSpace.beginMarking();
604     setMutatorShouldBeFenced(true);
605 }
606
607 void Heap::removeDeadCompilerWorklistEntries()
608 {
609 #if ENABLE(DFG_JIT)
610     for (unsigned i = DFG::numberOfWorklists(); i--;)
611         DFG::existingWorklistForIndex(i).removeDeadPlans(*m_vm);
612 #endif
613 }
614
615 bool Heap::isHeapSnapshotting() const
616 {
617     HeapProfiler* heapProfiler = m_vm->heapProfiler();
618     if (UNLIKELY(heapProfiler))
619         return heapProfiler->activeSnapshotBuilder();
620     return false;
621 }
622
623 struct GatherHeapSnapshotData : MarkedBlock::CountFunctor {
624     GatherHeapSnapshotData(HeapSnapshotBuilder& builder)
625         : m_builder(builder)
626     {
627     }
628
629     IterationStatus operator()(HeapCell* heapCell, HeapCell::Kind kind) const
630     {
631         if (kind == HeapCell::JSCell) {
632             JSCell* cell = static_cast<JSCell*>(heapCell);
633             cell->methodTable()->heapSnapshot(cell, m_builder);
634         }
635         return IterationStatus::Continue;
636     }
637
638     HeapSnapshotBuilder& m_builder;
639 };
640
641 void Heap::gatherExtraHeapSnapshotData(HeapProfiler& heapProfiler)
642 {
643     if (HeapSnapshotBuilder* builder = heapProfiler.activeSnapshotBuilder()) {
644         HeapIterationScope heapIterationScope(*this);
645         GatherHeapSnapshotData functor(*builder);
646         m_objectSpace.forEachLiveCell(heapIterationScope, functor);
647     }
648 }
649
650 struct RemoveDeadHeapSnapshotNodes : MarkedBlock::CountFunctor {
651     RemoveDeadHeapSnapshotNodes(HeapSnapshot& snapshot)
652         : m_snapshot(snapshot)
653     {
654     }
655
656     IterationStatus operator()(HeapCell* cell, HeapCell::Kind kind) const
657     {
658         if (kind == HeapCell::JSCell)
659             m_snapshot.sweepCell(static_cast<JSCell*>(cell));
660         return IterationStatus::Continue;
661     }
662
663     HeapSnapshot& m_snapshot;
664 };
665
666 void Heap::removeDeadHeapSnapshotNodes(HeapProfiler& heapProfiler)
667 {
668     if (HeapSnapshot* snapshot = heapProfiler.mostRecentSnapshot()) {
669         HeapIterationScope heapIterationScope(*this);
670         RemoveDeadHeapSnapshotNodes functor(*snapshot);
671         m_objectSpace.forEachDeadCell(heapIterationScope, functor);
672         snapshot->shrinkToFit();
673     }
674 }
675
676 void Heap::updateObjectCounts()
677 {
678     if (m_collectionScope == CollectionScope::Full)
679         m_totalBytesVisited = 0;
680
681     m_totalBytesVisitedThisCycle = bytesVisited();
682     
683     m_totalBytesVisited += m_totalBytesVisitedThisCycle;
684 }
685
686 void Heap::endMarking()
687 {
688     forEachSlotVisitor(
689         [&] (SlotVisitor& visitor) {
690             visitor.reset();
691         });
692
693     assertSharedMarkStacksEmpty();
694     m_weakReferenceHarvesters.removeAll();
695
696     RELEASE_ASSERT(m_raceMarkStack->isEmpty());
697     
698     m_objectSpace.endMarking();
699     setMutatorShouldBeFenced(Options::forceFencedBarrier());
700 }
701
702 size_t Heap::objectCount()
703 {
704     return m_objectSpace.objectCount();
705 }
706
707 size_t Heap::extraMemorySize()
708 {
709     return m_extraMemorySize + m_deprecatedExtraMemorySize + m_arrayBuffers.size();
710 }
711
712 size_t Heap::size()
713 {
714     return m_objectSpace.size() + extraMemorySize();
715 }
716
717 size_t Heap::capacity()
718 {
719     return m_objectSpace.capacity() + extraMemorySize();
720 }
721
722 size_t Heap::protectedGlobalObjectCount()
723 {
724     size_t result = 0;
725     forEachProtectedCell(
726         [&] (JSCell* cell) {
727             if (cell->isObject() && asObject(cell)->isGlobalObject())
728                 result++;
729         });
730     return result;
731 }
732
733 size_t Heap::globalObjectCount()
734 {
735     HeapIterationScope iterationScope(*this);
736     size_t result = 0;
737     m_objectSpace.forEachLiveCell(
738         iterationScope,
739         [&] (HeapCell* heapCell, HeapCell::Kind kind) -> IterationStatus {
740             if (kind != HeapCell::JSCell)
741                 return IterationStatus::Continue;
742             JSCell* cell = static_cast<JSCell*>(heapCell);
743             if (cell->isObject() && asObject(cell)->isGlobalObject())
744                 result++;
745             return IterationStatus::Continue;
746         });
747     return result;
748 }
749
750 size_t Heap::protectedObjectCount()
751 {
752     size_t result = 0;
753     forEachProtectedCell(
754         [&] (JSCell*) {
755             result++;
756         });
757     return result;
758 }
759
760 std::unique_ptr<TypeCountSet> Heap::protectedObjectTypeCounts()
761 {
762     std::unique_ptr<TypeCountSet> result = std::make_unique<TypeCountSet>();
763     forEachProtectedCell(
764         [&] (JSCell* cell) {
765             recordType(*vm(), *result, cell);
766         });
767     return result;
768 }
769
770 std::unique_ptr<TypeCountSet> Heap::objectTypeCounts()
771 {
772     std::unique_ptr<TypeCountSet> result = std::make_unique<TypeCountSet>();
773     HeapIterationScope iterationScope(*this);
774     m_objectSpace.forEachLiveCell(
775         iterationScope,
776         [&] (HeapCell* cell, HeapCell::Kind kind) -> IterationStatus {
777             if (kind == HeapCell::JSCell)
778                 recordType(*vm(), *result, static_cast<JSCell*>(cell));
779             return IterationStatus::Continue;
780         });
781     return result;
782 }
783
784 void Heap::deleteAllCodeBlocks(DeleteAllCodeEffort effort)
785 {
786     if (m_collectionScope && effort == DeleteAllCodeIfNotCollecting)
787         return;
788     
789     PreventCollectionScope preventCollectionScope(*this);
790     
791     // If JavaScript is running, it's not safe to delete all JavaScript code, since
792     // we'll end up returning to deleted code.
793     RELEASE_ASSERT(!m_vm->entryScope);
794     RELEASE_ASSERT(!m_collectionScope);
795
796     completeAllJITPlans();
797
798     for (ExecutableBase* executable : m_executables)
799         executable->clearCode();
800 }
801
802 void Heap::deleteAllUnlinkedCodeBlocks(DeleteAllCodeEffort effort)
803 {
804     if (m_collectionScope && effort == DeleteAllCodeIfNotCollecting)
805         return;
806     
807     PreventCollectionScope preventCollectionScope(*this);
808
809     RELEASE_ASSERT(!m_collectionScope);
810     
811     for (ExecutableBase* current : m_executables) {
812         if (!current->isFunctionExecutable())
813             continue;
814         static_cast<FunctionExecutable*>(current)->unlinkedExecutable()->clearCode();
815     }
816 }
817
818 void Heap::clearUnmarkedExecutables()
819 {
820     for (unsigned i = m_executables.size(); i--;) {
821         ExecutableBase* current = m_executables[i];
822         if (isMarked(current))
823             continue;
824
825         // Eagerly dereference the Executable's JITCode in order to run watchpoint
826         // destructors. Otherwise, watchpoints might fire for deleted CodeBlocks.
827         current->clearCode();
828         std::swap(m_executables[i], m_executables.last());
829         m_executables.removeLast();
830     }
831
832     m_executables.shrinkToFit();
833 }
834
835 void Heap::deleteUnmarkedCompiledCode()
836 {
837     clearUnmarkedExecutables();
838     m_codeBlocks->deleteUnmarkedAndUnreferenced(*m_vm, *m_lastCollectionScope);
839     m_jitStubRoutines->deleteUnmarkedJettisonedStubRoutines();
840 }
841
842 void Heap::addToRememberedSet(const JSCell* constCell)
843 {
844     JSCell* cell = const_cast<JSCell*>(constCell);
845     ASSERT(cell);
846     ASSERT(!Options::useConcurrentJIT() || !isCompilationThread());
847     m_barriersExecuted++;
848     if (m_mutatorShouldBeFenced) {
849         WTF::loadLoadFence();
850         if (!isMarkedConcurrently(cell)) {
851             // During a full collection a store into an unmarked object that had surivived past
852             // collections will manifest as a store to an unmarked PossiblyBlack object. If the
853             // object gets marked at some time after this then it will go down the normal marking
854             // path. So, we don't have to remember this object. We could return here. But we go
855             // further and attempt to re-white the object.
856             
857             RELEASE_ASSERT(m_collectionScope == CollectionScope::Full);
858             
859             if (cell->atomicCompareExchangeCellStateStrong(CellState::PossiblyBlack, CellState::DefinitelyWhite) == CellState::PossiblyBlack) {
860                 // Now we protect against this race:
861                 //
862                 //     1) Object starts out black + unmarked.
863                 //     --> We do isMarkedConcurrently here.
864                 //     2) Object is marked and greyed.
865                 //     3) Object is scanned and blacked.
866                 //     --> We do atomicCompareExchangeCellStateStrong here.
867                 //
868                 // In this case we would have made the object white again, even though it should
869                 // be black. This check lets us correct our mistake. This relies on the fact that
870                 // isMarkedConcurrently converges monotonically to true.
871                 if (isMarkedConcurrently(cell)) {
872                     // It's difficult to work out whether the object should be grey or black at
873                     // this point. We say black conservatively.
874                     cell->setCellState(CellState::PossiblyBlack);
875                 }
876                 
877                 // Either way, we can return. Most likely, the object was not marked, and so the
878                 // object is now labeled white. This means that future barrier executions will not
879                 // fire. In the unlikely event that the object had become marked, we can still
880                 // return anyway, since we proved that the object was not marked at the time that
881                 // we executed this slow path.
882             }
883             
884             return;
885         }
886     } else
887         ASSERT(Heap::isMarkedConcurrently(cell));
888     // It could be that the object was *just* marked. This means that the collector may set the
889     // state to DefinitelyGrey and then to PossiblyOldOrBlack at any time. It's OK for us to
890     // race with the collector here. If we win then this is accurate because the object _will_
891     // get scanned again. If we lose then someone else will barrier the object again. That would
892     // be unfortunate but not the end of the world.
893     cell->setCellState(CellState::PossiblyGrey);
894     m_mutatorMarkStack->append(cell);
895 }
896
897 void Heap::sweepSynchronously()
898 {
899     double before = 0;
900     if (Options::logGC()) {
901         dataLog("Full sweep: ", capacity() / 1024, "kb ");
902         before = currentTimeMS();
903     }
904     m_objectSpace.sweep();
905     m_objectSpace.shrink();
906     if (Options::logGC()) {
907         double after = currentTimeMS();
908         dataLog("=> ", capacity() / 1024, "kb, ", after - before, "ms");
909     }
910 }
911
912 void Heap::collectAllGarbage()
913 {
914     if (!m_isSafeToCollect)
915         return;
916     
917     collectSync(CollectionScope::Full);
918
919     DeferGCForAWhile deferGC(*this);
920     if (UNLIKELY(Options::useImmortalObjects()))
921         sweeper()->stopSweeping();
922
923     bool alreadySweptInCollectSync = Options::sweepSynchronously();
924     if (!alreadySweptInCollectSync) {
925         if (Options::logGC())
926             dataLog("[GC<", RawPointer(this), ">: ");
927         sweepSynchronously();
928         if (Options::logGC())
929             dataLog("]\n");
930     }
931     m_objectSpace.assertNoUnswept();
932
933     sweepAllLogicallyEmptyWeakBlocks();
934 }
935
936 void Heap::collectAsync(std::optional<CollectionScope> scope)
937 {
938     if (!m_isSafeToCollect)
939         return;
940
941     bool alreadyRequested = false;
942     {
943         LockHolder locker(*m_threadLock);
944         for (std::optional<CollectionScope> request : m_requests) {
945             if (scope) {
946                 if (scope == CollectionScope::Eden) {
947                     alreadyRequested = true;
948                     break;
949                 } else {
950                     RELEASE_ASSERT(scope == CollectionScope::Full);
951                     if (request == CollectionScope::Full) {
952                         alreadyRequested = true;
953                         break;
954                     }
955                 }
956             } else {
957                 if (!request || request == CollectionScope::Full) {
958                     alreadyRequested = true;
959                     break;
960                 }
961             }
962         }
963     }
964     if (alreadyRequested)
965         return;
966
967     requestCollection(scope);
968 }
969
970 void Heap::collectSync(std::optional<CollectionScope> scope)
971 {
972     if (!m_isSafeToCollect)
973         return;
974     
975     waitForCollection(requestCollection(scope));
976 }
977
978 bool Heap::shouldCollectInCollectorThread(const AbstractLocker&)
979 {
980     RELEASE_ASSERT(m_requests.isEmpty() == (m_lastServedTicket == m_lastGrantedTicket));
981     RELEASE_ASSERT(m_lastServedTicket <= m_lastGrantedTicket);
982     
983     if (false)
984         dataLog("Mutator has the conn = ", !!(m_worldState.load() & mutatorHasConnBit), "\n");
985     
986     return !m_requests.isEmpty() && !(m_worldState.load() & mutatorHasConnBit);
987 }
988
989 void Heap::collectInCollectorThread()
990 {
991     for (;;) {
992         RunCurrentPhaseResult result = runCurrentPhase(GCConductor::Collector, nullptr);
993         switch (result) {
994         case RunCurrentPhaseResult::Finished:
995             return;
996         case RunCurrentPhaseResult::Continue:
997             break;
998         case RunCurrentPhaseResult::NeedCurrentThreadState:
999             RELEASE_ASSERT_NOT_REACHED();
1000             break;
1001         }
1002     }
1003 }
1004
1005 void Heap::checkConn(GCConductor conn)
1006 {
1007     switch (conn) {
1008     case GCConductor::Mutator:
1009         RELEASE_ASSERT(m_worldState.load() & mutatorHasConnBit);
1010         return;
1011     case GCConductor::Collector:
1012         RELEASE_ASSERT(!(m_worldState.load() & mutatorHasConnBit));
1013         return;
1014     }
1015     RELEASE_ASSERT_NOT_REACHED();
1016 }
1017
1018 auto Heap::runCurrentPhase(GCConductor conn, CurrentThreadState* currentThreadState) -> RunCurrentPhaseResult
1019 {
1020     checkConn(conn);
1021     m_currentThreadState = currentThreadState;
1022     
1023     // If the collector transfers the conn to the mutator, it leaves us in between phases.
1024     if (!finishChangingPhase(conn)) {
1025         // A mischevious mutator could repeatedly relinquish the conn back to us. We try to avoid doing
1026         // this, but it's probably not the end of the world if it did happen.
1027         if (false)
1028             dataLog("Conn bounce-back.\n");
1029         return RunCurrentPhaseResult::Finished;
1030     }
1031     
1032     bool result = false;
1033     switch (m_currentPhase) {
1034     case CollectorPhase::NotRunning:
1035         result = runNotRunningPhase(conn);
1036         break;
1037         
1038     case CollectorPhase::Begin:
1039         result = runBeginPhase(conn);
1040         break;
1041         
1042     case CollectorPhase::Fixpoint:
1043         if (!currentThreadState && conn == GCConductor::Mutator)
1044             return RunCurrentPhaseResult::NeedCurrentThreadState;
1045         
1046         result = runFixpointPhase(conn);
1047         break;
1048         
1049     case CollectorPhase::Concurrent:
1050         result = runConcurrentPhase(conn);
1051         break;
1052         
1053     case CollectorPhase::Reloop:
1054         result = runReloopPhase(conn);
1055         break;
1056         
1057     case CollectorPhase::End:
1058         result = runEndPhase(conn);
1059         break;
1060     }
1061
1062     return result ? RunCurrentPhaseResult::Continue : RunCurrentPhaseResult::Finished;
1063 }
1064
1065 NEVER_INLINE bool Heap::runNotRunningPhase(GCConductor conn)
1066 {
1067     // Check m_requests since the mutator calls this to poll what's going on.
1068     {
1069         auto locker = holdLock(*m_threadLock);
1070         if (m_requests.isEmpty())
1071             return false;
1072     }
1073     
1074     return changePhase(conn, CollectorPhase::Begin);
1075 }
1076
1077 NEVER_INLINE bool Heap::runBeginPhase(GCConductor conn)
1078 {
1079     m_currentGCStartTime = MonotonicTime::now();
1080         
1081     std::optional<CollectionScope> scope;
1082     {
1083         LockHolder locker(*m_threadLock);
1084         RELEASE_ASSERT(!m_requests.isEmpty());
1085         scope = m_requests.first();
1086     }
1087         
1088     if (Options::logGC())
1089         dataLog("[GC<", RawPointer(this), ">: START ", gcConductorShortName(conn), " ", capacity() / 1024, "kb ");
1090
1091     m_beforeGC = MonotonicTime::now();
1092
1093     if (m_collectionScope) {
1094         dataLog("Collection scope already set during GC: ", *m_collectionScope, "\n");
1095         RELEASE_ASSERT_NOT_REACHED();
1096     }
1097         
1098     willStartCollection(scope);
1099         
1100     if (UNLIKELY(m_verifier)) {
1101         // Verify that live objects from the last GC cycle haven't been corrupted by
1102         // mutators before we begin this new GC cycle.
1103         m_verifier->verify(HeapVerifier::Phase::BeforeGC);
1104             
1105         m_verifier->startGC();
1106         m_verifier->gatherLiveCells(HeapVerifier::Phase::BeforeMarking);
1107     }
1108         
1109     prepareForMarking();
1110         
1111     if (m_collectionScope == CollectionScope::Full) {
1112         m_opaqueRoots.clear();
1113         m_collectorSlotVisitor->clearMarkStacks();
1114         m_mutatorMarkStack->clear();
1115     }
1116
1117     RELEASE_ASSERT(m_raceMarkStack->isEmpty());
1118
1119     beginMarking();
1120
1121     forEachSlotVisitor(
1122         [&] (SlotVisitor& visitor) {
1123             visitor.didStartMarking();
1124         });
1125
1126     m_parallelMarkersShouldExit = false;
1127
1128     m_helperClient.setFunction(
1129         [this] () {
1130             SlotVisitor* slotVisitor;
1131             {
1132                 LockHolder locker(m_parallelSlotVisitorLock);
1133                 if (m_availableParallelSlotVisitors.isEmpty()) {
1134                     std::unique_ptr<SlotVisitor> newVisitor = std::make_unique<SlotVisitor>(
1135                         *this, toCString("P", m_parallelSlotVisitors.size() + 1));
1136                     
1137                     if (Options::optimizeParallelSlotVisitorsForStoppedMutator())
1138                         newVisitor->optimizeForStoppedMutator();
1139                     
1140                     newVisitor->didStartMarking();
1141                     
1142                     slotVisitor = newVisitor.get();
1143                     m_parallelSlotVisitors.append(WTFMove(newVisitor));
1144                 } else
1145                     slotVisitor = m_availableParallelSlotVisitors.takeLast();
1146             }
1147
1148             WTF::registerGCThread(GCThreadType::Helper);
1149
1150             {
1151                 ParallelModeEnabler parallelModeEnabler(*slotVisitor);
1152                 slotVisitor->drainFromShared(SlotVisitor::SlaveDrain);
1153             }
1154
1155             {
1156                 LockHolder locker(m_parallelSlotVisitorLock);
1157                 m_availableParallelSlotVisitors.append(slotVisitor);
1158             }
1159         });
1160
1161     SlotVisitor& slotVisitor = *m_collectorSlotVisitor;
1162
1163     m_constraintSet->didStartMarking();
1164     
1165     m_scheduler->beginCollection();
1166     if (Options::logGC())
1167         m_scheduler->log();
1168     
1169     // After this, we will almost certainly fall through all of the "slotVisitor.isEmpty()"
1170     // checks because bootstrap would have put things into the visitor. So, we should fall
1171     // through to draining.
1172     
1173     if (!slotVisitor.didReachTermination()) {
1174         dataLog("Fatal: SlotVisitor should think that GC should terminate before constraint solving, but it does not think this.\n");
1175         dataLog("slotVisitor.isEmpty(): ", slotVisitor.isEmpty(), "\n");
1176         dataLog("slotVisitor.collectorMarkStack().isEmpty(): ", slotVisitor.collectorMarkStack().isEmpty(), "\n");
1177         dataLog("slotVisitor.mutatorMarkStack().isEmpty(): ", slotVisitor.mutatorMarkStack().isEmpty(), "\n");
1178         dataLog("m_numberOfActiveParallelMarkers: ", m_numberOfActiveParallelMarkers, "\n");
1179         dataLog("m_sharedCollectorMarkStack->isEmpty(): ", m_sharedCollectorMarkStack->isEmpty(), "\n");
1180         dataLog("m_sharedMutatorMarkStack->isEmpty(): ", m_sharedMutatorMarkStack->isEmpty(), "\n");
1181         dataLog("slotVisitor.didReachTermination(): ", slotVisitor.didReachTermination(), "\n");
1182         RELEASE_ASSERT_NOT_REACHED();
1183     }
1184         
1185     return changePhase(conn, CollectorPhase::Fixpoint);
1186 }
1187
1188 NEVER_INLINE bool Heap::runFixpointPhase(GCConductor conn)
1189 {
1190     RELEASE_ASSERT(conn == GCConductor::Collector || m_currentThreadState);
1191     
1192     SlotVisitor& slotVisitor = *m_collectorSlotVisitor;
1193     
1194     if (Options::logGC()) {
1195         HashMap<const char*, size_t> visitMap;
1196         forEachSlotVisitor(
1197             [&] (SlotVisitor& slotVisitor) {
1198                 visitMap.add(slotVisitor.codeName(), slotVisitor.bytesVisited() / 1024);
1199             });
1200         
1201         auto perVisitorDump = sortedMapDump(
1202             visitMap,
1203             [] (const char* a, const char* b) -> bool {
1204                 return strcmp(a, b) < 0;
1205             },
1206             ":", " ");
1207         
1208         dataLog("v=", bytesVisited() / 1024, "kb (", perVisitorDump, ") o=", m_opaqueRoots.size(), " b=", m_barriersExecuted, " ");
1209     }
1210         
1211     if (slotVisitor.didReachTermination()) {
1212         m_scheduler->didReachTermination();
1213             
1214         assertSharedMarkStacksEmpty();
1215             
1216         slotVisitor.mergeIfNecessary();
1217         for (auto& parallelVisitor : m_parallelSlotVisitors)
1218             parallelVisitor->mergeIfNecessary();
1219             
1220         // FIXME: Take m_mutatorDidRun into account when scheduling constraints. Most likely,
1221         // we don't have to execute root constraints again unless the mutator did run. At a
1222         // minimum, we could use this for work estimates - but it's probably more than just an
1223         // estimate.
1224         // https://bugs.webkit.org/show_bug.cgi?id=166828
1225             
1226         // FIXME: We should take advantage of the fact that we could timeout. This only comes
1227         // into play if we're executing constraints for the first time. But that will matter
1228         // when we have deep stacks or a lot of DOM stuff.
1229         // https://bugs.webkit.org/show_bug.cgi?id=166831
1230             
1231         // Wondering what this does? Look at Heap::addCoreConstraints(). The DOM and others can also
1232         // add their own using Heap::addMarkingConstraint().
1233         bool converged =
1234             m_constraintSet->executeConvergence(slotVisitor, MonotonicTime::infinity());
1235         if (converged && slotVisitor.isEmpty()) {
1236             assertSharedMarkStacksEmpty();
1237             return changePhase(conn, CollectorPhase::End);
1238         }
1239             
1240         m_scheduler->didExecuteConstraints();
1241     }
1242         
1243     if (Options::logGC())
1244         dataLog(slotVisitor.collectorMarkStack().size(), "+", m_mutatorMarkStack->size() + slotVisitor.mutatorMarkStack().size(), " ");
1245         
1246     {
1247         ParallelModeEnabler enabler(slotVisitor);
1248         slotVisitor.drainInParallel(m_scheduler->timeToResume());
1249     }
1250         
1251     m_scheduler->synchronousDrainingDidStall();
1252
1253     if (slotVisitor.didReachTermination())
1254         return true; // This is like relooping to the top if runFixpointPhase().
1255         
1256     if (!m_scheduler->shouldResume())
1257         return true;
1258
1259     m_scheduler->willResume();
1260         
1261     if (Options::logGC()) {
1262         double thisPauseMS = (MonotonicTime::now() - m_stopTime).milliseconds();
1263         dataLog("p=", thisPauseMS, "ms (max ", maxPauseMS(thisPauseMS), ")...]\n");
1264     }
1265
1266     // Forgive the mutator for its past failures to keep up.
1267     // FIXME: Figure out if moving this to different places results in perf changes.
1268     m_incrementBalance = 0;
1269         
1270     return changePhase(conn, CollectorPhase::Concurrent);
1271 }
1272
1273 NEVER_INLINE bool Heap::runConcurrentPhase(GCConductor conn)
1274 {
1275     SlotVisitor& slotVisitor = *m_collectorSlotVisitor;
1276
1277     switch (conn) {
1278     case GCConductor::Mutator: {
1279         // When the mutator has the conn, we poll runConcurrentPhase() on every time someone says
1280         // stopIfNecessary(), so on every allocation slow path. When that happens we poll if it's time
1281         // to stop and do some work.
1282         if (slotVisitor.didReachTermination()
1283             || m_scheduler->shouldStop())
1284             return changePhase(conn, CollectorPhase::Reloop);
1285         
1286         // We could be coming from a collector phase that stuffed our SlotVisitor, so make sure we donate
1287         // everything. This is super cheap if the SlotVisitor is already empty.
1288         slotVisitor.donateAll();
1289         return false;
1290     }
1291     case GCConductor::Collector: {
1292         {
1293             ParallelModeEnabler enabler(slotVisitor);
1294             slotVisitor.drainInParallelPassively(m_scheduler->timeToStop());
1295         }
1296         return changePhase(conn, CollectorPhase::Reloop);
1297     } }
1298     
1299     RELEASE_ASSERT_NOT_REACHED();
1300     return false;
1301 }
1302
1303 NEVER_INLINE bool Heap::runReloopPhase(GCConductor conn)
1304 {
1305     if (Options::logGC())
1306         dataLog("[GC<", RawPointer(this), ">: ", gcConductorShortName(conn), " ");
1307     
1308     m_scheduler->didStop();
1309     
1310     if (Options::logGC())
1311         m_scheduler->log();
1312     
1313     return changePhase(conn, CollectorPhase::Fixpoint);
1314 }
1315
1316 NEVER_INLINE bool Heap::runEndPhase(GCConductor conn)
1317 {
1318     m_scheduler->endCollection();
1319         
1320     {
1321         auto locker = holdLock(m_markingMutex);
1322         m_parallelMarkersShouldExit = true;
1323         m_markingConditionVariable.notifyAll();
1324     }
1325     m_helperClient.finish();
1326     
1327     iterateExecutingAndCompilingCodeBlocks(
1328         [&] (CodeBlock* codeBlock) {
1329             writeBarrier(codeBlock);
1330         });
1331         
1332     updateObjectCounts();
1333     endMarking();
1334         
1335     if (UNLIKELY(m_verifier)) {
1336         m_verifier->gatherLiveCells(HeapVerifier::Phase::AfterMarking);
1337         m_verifier->verify(HeapVerifier::Phase::AfterMarking);
1338     }
1339         
1340     if (vm()->typeProfiler())
1341         vm()->typeProfiler()->invalidateTypeSetCache();
1342         
1343     reapWeakHandles();
1344     pruneStaleEntriesFromWeakGCMaps();
1345     sweepArrayBuffers();
1346     snapshotUnswept();
1347     finalizeUnconditionalFinalizers();
1348     removeDeadCompilerWorklistEntries();
1349     notifyIncrementalSweeper();
1350     
1351     m_codeBlocks->iterateCurrentlyExecuting(
1352         [&] (CodeBlock* codeBlock) {
1353             writeBarrier(codeBlock);
1354         });
1355     m_codeBlocks->clearCurrentlyExecuting();
1356         
1357     m_objectSpace.prepareForAllocation();
1358     updateAllocationLimits();
1359
1360     if (UNLIKELY(m_verifier)) {
1361         m_verifier->trimDeadCells();
1362         m_verifier->verify(HeapVerifier::Phase::AfterGC);
1363     }
1364
1365     didFinishCollection();
1366
1367     if (false) {
1368         dataLog("Heap state after GC:\n");
1369         m_objectSpace.dumpBits();
1370     }
1371     
1372     if (Options::logGC()) {
1373         double thisPauseMS = (m_afterGC - m_stopTime).milliseconds();
1374         dataLog("p=", thisPauseMS, "ms (max ", maxPauseMS(thisPauseMS), "), cycle ", (m_afterGC - m_beforeGC).milliseconds(), "ms END]\n");
1375     }
1376     
1377     {
1378         auto locker = holdLock(*m_threadLock);
1379         m_requests.removeFirst();
1380         m_lastServedTicket++;
1381         clearMutatorWaiting();
1382     }
1383     ParkingLot::unparkAll(&m_worldState);
1384
1385     if (false)
1386         dataLog("GC END!\n");
1387
1388     setNeedFinalize();
1389
1390     m_lastGCStartTime = m_currentGCStartTime;
1391     m_lastGCEndTime = MonotonicTime::now();
1392         
1393     return changePhase(conn, CollectorPhase::NotRunning);
1394 }
1395
1396 bool Heap::changePhase(GCConductor conn, CollectorPhase nextPhase)
1397 {
1398     checkConn(conn);
1399
1400     m_nextPhase = nextPhase;
1401
1402     return finishChangingPhase(conn);
1403 }
1404
1405 NEVER_INLINE bool Heap::finishChangingPhase(GCConductor conn)
1406 {
1407     checkConn(conn);
1408     
1409     if (m_nextPhase == m_currentPhase)
1410         return true;
1411
1412     if (false)
1413         dataLog(conn, ": Going to phase: ", m_nextPhase, " (from ", m_currentPhase, ")\n");
1414     
1415     bool suspendedBefore = worldShouldBeSuspended(m_currentPhase);
1416     bool suspendedAfter = worldShouldBeSuspended(m_nextPhase);
1417     
1418     if (suspendedBefore != suspendedAfter) {
1419         if (suspendedBefore) {
1420             RELEASE_ASSERT(!suspendedAfter);
1421             
1422             resumeThePeriphery();
1423             if (conn == GCConductor::Collector)
1424                 resumeTheMutator();
1425             else
1426                 handleNeedFinalize();
1427         } else {
1428             RELEASE_ASSERT(!suspendedBefore);
1429             RELEASE_ASSERT(suspendedAfter);
1430             
1431             if (conn == GCConductor::Collector) {
1432                 waitWhileNeedFinalize();
1433                 if (!stopTheMutator()) {
1434                     if (false)
1435                         dataLog("Returning false.\n");
1436                     return false;
1437                 }
1438             } else {
1439                 sanitizeStackForVM(m_vm);
1440                 handleNeedFinalize();
1441             }
1442             stopThePeriphery(conn);
1443         }
1444     }
1445     
1446     m_currentPhase = m_nextPhase;
1447     return true;
1448 }
1449
1450 void Heap::stopThePeriphery(GCConductor conn)
1451 {
1452     if (m_collectorBelievesThatTheWorldIsStopped) {
1453         dataLog("FATAL: world already stopped.\n");
1454         RELEASE_ASSERT_NOT_REACHED();
1455     }
1456     
1457     if (m_mutatorDidRun)
1458         m_mutatorExecutionVersion++;
1459     
1460     m_mutatorDidRun = false;
1461
1462     suspendCompilerThreads();
1463     m_collectorBelievesThatTheWorldIsStopped = true;
1464
1465     forEachSlotVisitor(
1466         [&] (SlotVisitor& slotVisitor) {
1467             slotVisitor.updateMutatorIsStopped(NoLockingNecessary);
1468         });
1469
1470 #if ENABLE(JIT)
1471     {
1472         DeferGCForAWhile awhile(*this);
1473         if (JITWorklist::instance()->completeAllForVM(*m_vm)
1474             && conn == GCConductor::Collector)
1475             setGCDidJIT();
1476     }
1477 #else
1478     UNUSED_PARAM(conn);
1479 #endif // ENABLE(JIT)
1480     
1481     vm()->shadowChicken().update(*vm(), vm()->topCallFrame);
1482     
1483     m_structureIDTable.flushOldTables();
1484     m_objectSpace.stopAllocating();
1485     
1486     m_stopTime = MonotonicTime::now();
1487 }
1488
1489 NEVER_INLINE void Heap::resumeThePeriphery()
1490 {
1491     // Calling resumeAllocating does the Right Thing depending on whether this is the end of a
1492     // collection cycle or this is just a concurrent phase within a collection cycle:
1493     // - At end of collection cycle: it's a no-op because prepareForAllocation already cleared the
1494     //   last active block.
1495     // - During collection cycle: it reinstates the last active block.
1496     m_objectSpace.resumeAllocating();
1497     
1498     m_barriersExecuted = 0;
1499     
1500     if (!m_collectorBelievesThatTheWorldIsStopped) {
1501         dataLog("Fatal: collector does not believe that the world is stopped.\n");
1502         RELEASE_ASSERT_NOT_REACHED();
1503     }
1504     m_collectorBelievesThatTheWorldIsStopped = false;
1505     
1506     // FIXME: This could be vastly improved: we want to grab the locks in the order in which they
1507     // become available. We basically want a lockAny() method that will lock whatever lock is available
1508     // and tell you which one it locked. That would require teaching ParkingLot how to park on multiple
1509     // queues at once, which is totally achievable - it would just require memory allocation, which is
1510     // suboptimal but not a disaster. Alternatively, we could replace the SlotVisitor rightToRun lock
1511     // with a DLG-style handshake mechanism, but that seems not as general.
1512     Vector<SlotVisitor*, 8> slotVisitorsToUpdate;
1513
1514     forEachSlotVisitor(
1515         [&] (SlotVisitor& slotVisitor) {
1516             slotVisitorsToUpdate.append(&slotVisitor);
1517         });
1518     
1519     for (unsigned countdown = 40; !slotVisitorsToUpdate.isEmpty() && countdown--;) {
1520         for (unsigned index = 0; index < slotVisitorsToUpdate.size(); ++index) {
1521             SlotVisitor& slotVisitor = *slotVisitorsToUpdate[index];
1522             bool remove = false;
1523             if (slotVisitor.hasAcknowledgedThatTheMutatorIsResumed())
1524                 remove = true;
1525             else if (auto locker = tryHoldLock(slotVisitor.rightToRun())) {
1526                 slotVisitor.updateMutatorIsStopped(locker);
1527                 remove = true;
1528             }
1529             if (remove) {
1530                 slotVisitorsToUpdate[index--] = slotVisitorsToUpdate.last();
1531                 slotVisitorsToUpdate.takeLast();
1532             }
1533         }
1534         std::this_thread::yield();
1535     }
1536     
1537     for (SlotVisitor* slotVisitor : slotVisitorsToUpdate)
1538         slotVisitor->updateMutatorIsStopped();
1539     
1540     resumeCompilerThreads();
1541 }
1542
1543 bool Heap::stopTheMutator()
1544 {
1545     for (;;) {
1546         unsigned oldState = m_worldState.load();
1547         if (oldState & stoppedBit) {
1548             RELEASE_ASSERT(!(oldState & hasAccessBit));
1549             RELEASE_ASSERT(!(oldState & mutatorWaitingBit));
1550             RELEASE_ASSERT(!(oldState & mutatorHasConnBit));
1551             return true;
1552         }
1553         
1554         if (oldState & mutatorHasConnBit) {
1555             RELEASE_ASSERT(!(oldState & hasAccessBit));
1556             RELEASE_ASSERT(!(oldState & stoppedBit));
1557             return false;
1558         }
1559
1560         if (!(oldState & hasAccessBit)) {
1561             RELEASE_ASSERT(!(oldState & mutatorHasConnBit));
1562             RELEASE_ASSERT(!(oldState & mutatorWaitingBit));
1563             // We can stop the world instantly.
1564             if (m_worldState.compareExchangeWeak(oldState, oldState | stoppedBit))
1565                 return true;
1566             continue;
1567         }
1568         
1569         // Transfer the conn to the mutator and bail.
1570         RELEASE_ASSERT(oldState & hasAccessBit);
1571         RELEASE_ASSERT(!(oldState & stoppedBit));
1572         unsigned newState = (oldState | mutatorHasConnBit) & ~mutatorWaitingBit;
1573         if (m_worldState.compareExchangeWeak(oldState, newState)) {
1574             if (false)
1575                 dataLog("Handed off the conn.\n");
1576             m_stopIfNecessaryTimer->scheduleSoon();
1577             ParkingLot::unparkAll(&m_worldState);
1578             return false;
1579         }
1580     }
1581 }
1582
1583 NEVER_INLINE void Heap::resumeTheMutator()
1584 {
1585     if (false)
1586         dataLog("Resuming the mutator.\n");
1587     for (;;) {
1588         unsigned oldState = m_worldState.load();
1589         if (!!(oldState & hasAccessBit) != !(oldState & stoppedBit)) {
1590             dataLog("Fatal: hasAccess = ", !!(oldState & hasAccessBit), ", stopped = ", !!(oldState & stoppedBit), "\n");
1591             RELEASE_ASSERT_NOT_REACHED();
1592         }
1593         if (oldState & mutatorHasConnBit) {
1594             dataLog("Fatal: mutator has the conn.\n");
1595             RELEASE_ASSERT_NOT_REACHED();
1596         }
1597         
1598         if (!(oldState & stoppedBit)) {
1599             if (false)
1600                 dataLog("Returning because not stopped.\n");
1601             return;
1602         }
1603         
1604         if (m_worldState.compareExchangeWeak(oldState, oldState & ~stoppedBit)) {
1605             if (false)
1606                 dataLog("CASing and returning.\n");
1607             ParkingLot::unparkAll(&m_worldState);
1608             return;
1609         }
1610     }
1611 }
1612
1613 void Heap::stopIfNecessarySlow()
1614 {
1615     while (stopIfNecessarySlow(m_worldState.load())) { }
1616     
1617     RELEASE_ASSERT(m_worldState.load() & hasAccessBit);
1618     RELEASE_ASSERT(!(m_worldState.load() & stoppedBit));
1619     
1620     handleGCDidJIT();
1621     handleNeedFinalize();
1622     m_mutatorDidRun = true;
1623 }
1624
1625 bool Heap::stopIfNecessarySlow(unsigned oldState)
1626 {
1627     RELEASE_ASSERT(oldState & hasAccessBit);
1628     RELEASE_ASSERT(!(oldState & stoppedBit));
1629     
1630     // It's possible for us to wake up with finalization already requested but the world not yet
1631     // resumed. If that happens, we can't run finalization yet.
1632     if (handleNeedFinalize(oldState))
1633         return true;
1634
1635     // FIXME: When entering the concurrent phase, we could arrange for this branch not to fire, and then
1636     // have the SlotVisitor do things to the m_worldState to make this branch fire again. That would
1637     // prevent us from polling this so much. Ideally, stopIfNecessary would ignore the mutatorHasConnBit
1638     // and there would be some other bit indicating whether we were in some GC phase other than the
1639     // NotRunning or Concurrent ones.
1640     if (oldState & mutatorHasConnBit)
1641         collectInMutatorThread();
1642     
1643     return false;
1644 }
1645
1646 NEVER_INLINE void Heap::collectInMutatorThread()
1647 {
1648     CollectingScope collectingScope(*this);
1649     for (;;) {
1650         RunCurrentPhaseResult result = runCurrentPhase(GCConductor::Mutator, nullptr);
1651         switch (result) {
1652         case RunCurrentPhaseResult::Finished:
1653             return;
1654         case RunCurrentPhaseResult::Continue:
1655             break;
1656         case RunCurrentPhaseResult::NeedCurrentThreadState:
1657             sanitizeStackForVM(m_vm);
1658             auto lambda = [&] (CurrentThreadState& state) {
1659                 for (;;) {
1660                     RunCurrentPhaseResult result = runCurrentPhase(GCConductor::Mutator, &state);
1661                     switch (result) {
1662                     case RunCurrentPhaseResult::Finished:
1663                         return;
1664                     case RunCurrentPhaseResult::Continue:
1665                         break;
1666                     case RunCurrentPhaseResult::NeedCurrentThreadState:
1667                         RELEASE_ASSERT_NOT_REACHED();
1668                         break;
1669                     }
1670                 }
1671             };
1672             callWithCurrentThreadState(scopedLambda<void(CurrentThreadState&)>(WTFMove(lambda)));
1673             return;
1674         }
1675     }
1676 }
1677
1678 template<typename Func>
1679 void Heap::waitForCollector(const Func& func)
1680 {
1681     for (;;) {
1682         bool done;
1683         {
1684             LockHolder locker(*m_threadLock);
1685             done = func(locker);
1686             if (!done) {
1687                 setMutatorWaiting();
1688                 
1689                 // At this point, the collector knows that we intend to wait, and he will clear the
1690                 // waiting bit and then unparkAll when the GC cycle finishes. Clearing the bit
1691                 // prevents us from parking except if there is also stop-the-world. Unparking after
1692                 // clearing means that if the clearing happens after we park, then we will unpark.
1693             }
1694         }
1695         
1696         // If we're in a stop-the-world scenario, we need to wait for that even if done is true.
1697         unsigned oldState = m_worldState.load();
1698         if (stopIfNecessarySlow(oldState))
1699             continue;
1700         
1701         // FIXME: We wouldn't need this if stopIfNecessarySlow() had a mode where it knew to just
1702         // do the collection.
1703         relinquishConn();
1704         
1705         if (done) {
1706             clearMutatorWaiting(); // Clean up just in case.
1707             return;
1708         }
1709         
1710         // If mutatorWaitingBit is still set then we want to wait.
1711         ParkingLot::compareAndPark(&m_worldState, oldState | mutatorWaitingBit);
1712     }
1713 }
1714
1715 void Heap::acquireAccessSlow()
1716 {
1717     for (;;) {
1718         unsigned oldState = m_worldState.load();
1719         RELEASE_ASSERT(!(oldState & hasAccessBit));
1720         
1721         if (oldState & stoppedBit) {
1722             if (verboseStop) {
1723                 dataLog("Stopping in acquireAccess!\n");
1724                 WTFReportBacktrace();
1725             }
1726             // Wait until we're not stopped anymore.
1727             ParkingLot::compareAndPark(&m_worldState, oldState);
1728             continue;
1729         }
1730         
1731         RELEASE_ASSERT(!(oldState & stoppedBit));
1732         unsigned newState = oldState | hasAccessBit;
1733         if (m_worldState.compareExchangeWeak(oldState, newState)) {
1734             handleGCDidJIT();
1735             handleNeedFinalize();
1736             m_mutatorDidRun = true;
1737             stopIfNecessary();
1738             return;
1739         }
1740     }
1741 }
1742
1743 void Heap::releaseAccessSlow()
1744 {
1745     for (;;) {
1746         unsigned oldState = m_worldState.load();
1747         if (!(oldState & hasAccessBit)) {
1748             dataLog("FATAL: Attempting to release access but the mutator does not have access.\n");
1749             RELEASE_ASSERT_NOT_REACHED();
1750         }
1751         if (oldState & stoppedBit) {
1752             dataLog("FATAL: Attempting to release access but the mutator is stopped.\n");
1753             RELEASE_ASSERT_NOT_REACHED();
1754         }
1755         
1756         if (handleNeedFinalize(oldState))
1757             continue;
1758         
1759         unsigned newState = oldState & ~(hasAccessBit | mutatorHasConnBit);
1760         
1761         if ((oldState & mutatorHasConnBit)
1762             && m_nextPhase != m_currentPhase) {
1763             // This means that the collector thread had given us the conn so that we would do something
1764             // for it. Stop ourselves as we release access. This ensures that acquireAccess blocks. In
1765             // the meantime, since we're handing the conn over, the collector will be awoken and it is
1766             // sure to have work to do.
1767             newState |= stoppedBit;
1768         }
1769
1770         if (m_worldState.compareExchangeWeak(oldState, newState)) {
1771             if (oldState & mutatorHasConnBit)
1772                 finishRelinquishingConn();
1773             return;
1774         }
1775     }
1776 }
1777
1778 bool Heap::relinquishConn(unsigned oldState)
1779 {
1780     RELEASE_ASSERT(oldState & hasAccessBit);
1781     RELEASE_ASSERT(!(oldState & stoppedBit));
1782     
1783     if (!(oldState & mutatorHasConnBit))
1784         return false; // Done.
1785     
1786     if (m_threadShouldStop)
1787         return false;
1788     
1789     if (!m_worldState.compareExchangeWeak(oldState, oldState & ~mutatorHasConnBit))
1790         return true; // Loop around.
1791     
1792     finishRelinquishingConn();
1793     return true;
1794 }
1795
1796 void Heap::finishRelinquishingConn()
1797 {
1798     if (false)
1799         dataLog("Relinquished the conn.\n");
1800     
1801     sanitizeStackForVM(m_vm);
1802     
1803     auto locker = holdLock(*m_threadLock);
1804     if (!m_requests.isEmpty())
1805         m_threadCondition->notifyOne(locker);
1806     ParkingLot::unparkAll(&m_worldState);
1807 }
1808
1809 void Heap::relinquishConn()
1810 {
1811     while (relinquishConn(m_worldState.load())) { }
1812 }
1813
1814 bool Heap::handleGCDidJIT(unsigned oldState)
1815 {
1816     RELEASE_ASSERT(oldState & hasAccessBit);
1817     if (!(oldState & gcDidJITBit))
1818         return false;
1819     if (m_worldState.compareExchangeWeak(oldState, oldState & ~gcDidJITBit)) {
1820         WTF::crossModifyingCodeFence();
1821         return true;
1822     }
1823     return true;
1824 }
1825
1826 NEVER_INLINE bool Heap::handleNeedFinalize(unsigned oldState)
1827 {
1828     RELEASE_ASSERT(oldState & hasAccessBit);
1829     RELEASE_ASSERT(!(oldState & stoppedBit));
1830     
1831     if (!(oldState & needFinalizeBit))
1832         return false;
1833     if (m_worldState.compareExchangeWeak(oldState, oldState & ~needFinalizeBit)) {
1834         finalize();
1835         // Wake up anyone waiting for us to finalize. Note that they may have woken up already, in
1836         // which case they would be waiting for us to release heap access.
1837         ParkingLot::unparkAll(&m_worldState);
1838         return true;
1839     }
1840     return true;
1841 }
1842
1843 void Heap::handleGCDidJIT()
1844 {
1845     while (handleGCDidJIT(m_worldState.load())) { }
1846 }
1847
1848 void Heap::handleNeedFinalize()
1849 {
1850     while (handleNeedFinalize(m_worldState.load())) { }
1851 }
1852
1853 void Heap::setGCDidJIT()
1854 {
1855     m_worldState.transaction(
1856         [&] (unsigned& state) -> bool {
1857             RELEASE_ASSERT(state & stoppedBit);
1858             state |= gcDidJITBit;
1859             return true;
1860         });
1861 }
1862
1863 void Heap::setNeedFinalize()
1864 {
1865     m_worldState.exchangeOr(needFinalizeBit);
1866     ParkingLot::unparkAll(&m_worldState);
1867     m_stopIfNecessaryTimer->scheduleSoon();
1868 }
1869
1870 void Heap::waitWhileNeedFinalize()
1871 {
1872     for (;;) {
1873         unsigned oldState = m_worldState.load();
1874         if (!(oldState & needFinalizeBit)) {
1875             // This means that either there was no finalize request or the main thread will finalize
1876             // with heap access, so a subsequent call to stopTheWorld() will return only when
1877             // finalize finishes.
1878             return;
1879         }
1880         ParkingLot::compareAndPark(&m_worldState, oldState);
1881     }
1882 }
1883
1884 void Heap::setMutatorWaiting()
1885 {
1886     m_worldState.exchangeOr(mutatorWaitingBit);
1887 }
1888
1889 void Heap::clearMutatorWaiting()
1890 {
1891     m_worldState.exchangeAnd(~mutatorWaitingBit);
1892 }
1893
1894 void Heap::notifyThreadStopping(const AbstractLocker&)
1895 {
1896     m_threadIsStopping = true;
1897     clearMutatorWaiting();
1898     ParkingLot::unparkAll(&m_worldState);
1899 }
1900
1901 void Heap::finalize()
1902 {
1903     MonotonicTime before;
1904     if (Options::logGC()) {
1905         before = MonotonicTime::now();
1906         dataLog("[GC<", RawPointer(this), ">: finalize ");
1907     }
1908     
1909     {
1910         SweepingScope helpingGCScope(*this);
1911         deleteUnmarkedCompiledCode();
1912         deleteSourceProviderCaches();
1913         sweepLargeAllocations();
1914     }
1915     
1916     if (HasOwnPropertyCache* cache = vm()->hasOwnPropertyCache())
1917         cache->clear();
1918     
1919     if (Options::sweepSynchronously())
1920         sweepSynchronously();
1921
1922     if (Options::logGC()) {
1923         MonotonicTime after = MonotonicTime::now();
1924         dataLog((after - before).milliseconds(), "ms]\n");
1925     }
1926 }
1927
1928 Heap::Ticket Heap::requestCollection(std::optional<CollectionScope> scope)
1929 {
1930     stopIfNecessary();
1931     
1932     ASSERT(vm()->currentThreadIsHoldingAPILock());
1933     RELEASE_ASSERT(vm()->atomicStringTable() == wtfThreadData().atomicStringTable());
1934     
1935     LockHolder locker(*m_threadLock);
1936     // We may be able to steal the conn. That only works if the collector is definitely not running
1937     // right now. This is an optimization that prevents the collector thread from ever starting in most
1938     // cases.
1939     ASSERT(m_lastServedTicket <= m_lastGrantedTicket);
1940     if (m_lastServedTicket == m_lastGrantedTicket) {
1941         if (false)
1942             dataLog("Taking the conn.\n");
1943         m_worldState.exchangeOr(mutatorHasConnBit);
1944     }
1945     
1946     m_requests.append(scope);
1947     m_lastGrantedTicket++;
1948     if (!(m_worldState.load() & mutatorHasConnBit))
1949         m_threadCondition->notifyOne(locker);
1950     return m_lastGrantedTicket;
1951 }
1952
1953 void Heap::waitForCollection(Ticket ticket)
1954 {
1955     waitForCollector(
1956         [&] (const AbstractLocker&) -> bool {
1957             return m_lastServedTicket >= ticket;
1958         });
1959 }
1960
1961 void Heap::sweepLargeAllocations()
1962 {
1963     m_objectSpace.sweepLargeAllocations();
1964 }
1965
1966 void Heap::suspendCompilerThreads()
1967 {
1968 #if ENABLE(DFG_JIT)
1969     // We ensure the worklists so that it's not possible for the mutator to start a new worklist
1970     // after we have suspended the ones that he had started before. That's not very expensive since
1971     // the worklists use AutomaticThreads anyway.
1972     for (unsigned i = DFG::numberOfWorklists(); i--;)
1973         DFG::ensureWorklistForIndex(i).suspendAllThreads();
1974 #endif
1975 }
1976
1977 void Heap::willStartCollection(std::optional<CollectionScope> scope)
1978 {
1979     if (Options::logGC())
1980         dataLog("=> ");
1981     
1982     if (shouldDoFullCollection(scope)) {
1983         m_collectionScope = CollectionScope::Full;
1984         m_shouldDoFullCollection = false;
1985         if (Options::logGC())
1986             dataLog("FullCollection, ");
1987         if (false)
1988             dataLog("Full collection!\n");
1989     } else {
1990         m_collectionScope = CollectionScope::Eden;
1991         if (Options::logGC())
1992             dataLog("EdenCollection, ");
1993         if (false)
1994             dataLog("Eden collection!\n");
1995     }
1996     if (m_collectionScope == CollectionScope::Full) {
1997         m_sizeBeforeLastFullCollect = m_sizeAfterLastCollect + m_bytesAllocatedThisCycle;
1998         m_extraMemorySize = 0;
1999         m_deprecatedExtraMemorySize = 0;
2000 #if ENABLE(RESOURCE_USAGE)
2001         m_externalMemorySize = 0;
2002 #endif
2003
2004         if (m_fullActivityCallback)
2005             m_fullActivityCallback->willCollect();
2006     } else {
2007         ASSERT(m_collectionScope == CollectionScope::Eden);
2008         m_sizeBeforeLastEdenCollect = m_sizeAfterLastCollect + m_bytesAllocatedThisCycle;
2009     }
2010
2011     if (m_edenActivityCallback)
2012         m_edenActivityCallback->willCollect();
2013
2014     for (auto* observer : m_observers)
2015         observer->willGarbageCollect();
2016 }
2017
2018 void Heap::prepareForMarking()
2019 {
2020     m_objectSpace.prepareForMarking();
2021 }
2022
2023 void Heap::reapWeakHandles()
2024 {
2025     m_objectSpace.reapWeakSets();
2026 }
2027
2028 void Heap::pruneStaleEntriesFromWeakGCMaps()
2029 {
2030     if (m_collectionScope != CollectionScope::Full)
2031         return;
2032     for (auto& pruneCallback : m_weakGCMaps.values())
2033         pruneCallback();
2034 }
2035
2036 void Heap::sweepArrayBuffers()
2037 {
2038     m_arrayBuffers.sweep();
2039 }
2040
2041 void Heap::snapshotUnswept()
2042 {
2043     TimingScope timingScope(*this, "Heap::snapshotUnswept");
2044     m_objectSpace.snapshotUnswept();
2045 }
2046
2047 void Heap::deleteSourceProviderCaches()
2048 {
2049     if (*m_lastCollectionScope == CollectionScope::Full)
2050         m_vm->clearSourceProviderCaches();
2051 }
2052
2053 void Heap::notifyIncrementalSweeper()
2054 {
2055     if (m_collectionScope == CollectionScope::Full) {
2056         if (!m_logicallyEmptyWeakBlocks.isEmpty())
2057             m_indexOfNextLogicallyEmptyWeakBlockToSweep = 0;
2058     }
2059
2060     m_sweeper->startSweeping();
2061 }
2062
2063 void Heap::updateAllocationLimits()
2064 {
2065     static const bool verbose = false;
2066     
2067     if (verbose) {
2068         dataLog("\n");
2069         dataLog("bytesAllocatedThisCycle = ", m_bytesAllocatedThisCycle, "\n");
2070     }
2071     
2072     // Calculate our current heap size threshold for the purpose of figuring out when we should
2073     // run another collection. This isn't the same as either size() or capacity(), though it should
2074     // be somewhere between the two. The key is to match the size calculations involved calls to
2075     // didAllocate(), while never dangerously underestimating capacity(). In extreme cases of
2076     // fragmentation, we may have size() much smaller than capacity().
2077     size_t currentHeapSize = 0;
2078
2079     // For marked space, we use the total number of bytes visited. This matches the logic for
2080     // MarkedAllocator's calls to didAllocate(), which effectively accounts for the total size of
2081     // objects allocated rather than blocks used. This will underestimate capacity(), and in case
2082     // of fragmentation, this may be substantial. Fortunately, marked space rarely fragments because
2083     // cells usually have a narrow range of sizes. So, the underestimation is probably OK.
2084     currentHeapSize += m_totalBytesVisited;
2085     if (verbose)
2086         dataLog("totalBytesVisited = ", m_totalBytesVisited, ", currentHeapSize = ", currentHeapSize, "\n");
2087
2088     // It's up to the user to ensure that extraMemorySize() ends up corresponding to allocation-time
2089     // extra memory reporting.
2090     currentHeapSize += extraMemorySize();
2091
2092     if (verbose)
2093         dataLog("extraMemorySize() = ", extraMemorySize(), ", currentHeapSize = ", currentHeapSize, "\n");
2094     
2095     if (m_collectionScope == CollectionScope::Full) {
2096         // To avoid pathological GC churn in very small and very large heaps, we set
2097         // the new allocation limit based on the current size of the heap, with a
2098         // fixed minimum.
2099         m_maxHeapSize = max(minHeapSize(m_heapType, m_ramSize), proportionalHeapSize(currentHeapSize, m_ramSize));
2100         if (verbose)
2101             dataLog("Full: maxHeapSize = ", m_maxHeapSize, "\n");
2102         m_maxEdenSize = m_maxHeapSize - currentHeapSize;
2103         if (verbose)
2104             dataLog("Full: maxEdenSize = ", m_maxEdenSize, "\n");
2105         m_sizeAfterLastFullCollect = currentHeapSize;
2106         if (verbose)
2107             dataLog("Full: sizeAfterLastFullCollect = ", currentHeapSize, "\n");
2108         m_bytesAbandonedSinceLastFullCollect = 0;
2109         if (verbose)
2110             dataLog("Full: bytesAbandonedSinceLastFullCollect = ", 0, "\n");
2111     } else {
2112         ASSERT(currentHeapSize >= m_sizeAfterLastCollect);
2113         // Theoretically, we shouldn't ever scan more memory than the heap size we planned to have.
2114         // But we are sloppy, so we have to defend against the overflow.
2115         m_maxEdenSize = currentHeapSize > m_maxHeapSize ? 0 : m_maxHeapSize - currentHeapSize;
2116         if (verbose)
2117             dataLog("Eden: maxEdenSize = ", m_maxEdenSize, "\n");
2118         m_sizeAfterLastEdenCollect = currentHeapSize;
2119         if (verbose)
2120             dataLog("Eden: sizeAfterLastEdenCollect = ", currentHeapSize, "\n");
2121         double edenToOldGenerationRatio = (double)m_maxEdenSize / (double)m_maxHeapSize;
2122         double minEdenToOldGenerationRatio = 1.0 / 3.0;
2123         if (edenToOldGenerationRatio < minEdenToOldGenerationRatio)
2124             m_shouldDoFullCollection = true;
2125         // This seems suspect at first, but what it does is ensure that the nursery size is fixed.
2126         m_maxHeapSize += currentHeapSize - m_sizeAfterLastCollect;
2127         if (verbose)
2128             dataLog("Eden: maxHeapSize = ", m_maxHeapSize, "\n");
2129         m_maxEdenSize = m_maxHeapSize - currentHeapSize;
2130         if (verbose)
2131             dataLog("Eden: maxEdenSize = ", m_maxEdenSize, "\n");
2132         if (m_fullActivityCallback) {
2133             ASSERT(currentHeapSize >= m_sizeAfterLastFullCollect);
2134             m_fullActivityCallback->didAllocate(currentHeapSize - m_sizeAfterLastFullCollect);
2135         }
2136     }
2137
2138     m_sizeAfterLastCollect = currentHeapSize;
2139     if (verbose)
2140         dataLog("sizeAfterLastCollect = ", m_sizeAfterLastCollect, "\n");
2141     m_bytesAllocatedThisCycle = 0;
2142
2143     if (Options::logGC())
2144         dataLog("=> ", currentHeapSize / 1024, "kb, ");
2145 }
2146
2147 void Heap::didFinishCollection()
2148 {
2149     m_afterGC = MonotonicTime::now();
2150     CollectionScope scope = *m_collectionScope;
2151     if (scope == CollectionScope::Full)
2152         m_lastFullGCLength = m_afterGC - m_beforeGC;
2153     else
2154         m_lastEdenGCLength = m_afterGC - m_beforeGC;
2155
2156 #if ENABLE(RESOURCE_USAGE)
2157     ASSERT(externalMemorySize() <= extraMemorySize());
2158 #endif
2159
2160     if (HeapProfiler* heapProfiler = m_vm->heapProfiler()) {
2161         gatherExtraHeapSnapshotData(*heapProfiler);
2162         removeDeadHeapSnapshotNodes(*heapProfiler);
2163     }
2164
2165     if (UNLIKELY(m_verifier))
2166         m_verifier->endGC();
2167
2168     RELEASE_ASSERT(m_collectionScope);
2169     m_lastCollectionScope = m_collectionScope;
2170     m_collectionScope = std::nullopt;
2171
2172     for (auto* observer : m_observers)
2173         observer->didGarbageCollect(scope);
2174 }
2175
2176 void Heap::resumeCompilerThreads()
2177 {
2178 #if ENABLE(DFG_JIT)
2179     for (unsigned i = DFG::numberOfWorklists(); i--;)
2180         DFG::existingWorklistForIndex(i).resumeAllThreads();
2181 #endif
2182 }
2183
2184 GCActivityCallback* Heap::fullActivityCallback()
2185 {
2186     return m_fullActivityCallback.get();
2187 }
2188
2189 GCActivityCallback* Heap::edenActivityCallback()
2190 {
2191     return m_edenActivityCallback.get();
2192 }
2193
2194 IncrementalSweeper* Heap::sweeper()
2195 {
2196     return m_sweeper.get();
2197 }
2198
2199 void Heap::setGarbageCollectionTimerEnabled(bool enable)
2200 {
2201     if (m_fullActivityCallback)
2202         m_fullActivityCallback->setEnabled(enable);
2203     if (m_edenActivityCallback)
2204         m_edenActivityCallback->setEnabled(enable);
2205 }
2206
2207 void Heap::didAllocate(size_t bytes)
2208 {
2209     if (m_edenActivityCallback)
2210         m_edenActivityCallback->didAllocate(m_bytesAllocatedThisCycle + m_bytesAbandonedSinceLastFullCollect);
2211     m_bytesAllocatedThisCycle += bytes;
2212     performIncrement(bytes);
2213 }
2214
2215 bool Heap::isValidAllocation(size_t)
2216 {
2217     if (!isValidThreadState(m_vm))
2218         return false;
2219
2220     if (isCurrentThreadBusy())
2221         return false;
2222     
2223     return true;
2224 }
2225
2226 void Heap::addFinalizer(JSCell* cell, Finalizer finalizer)
2227 {
2228     WeakSet::allocate(cell, &m_finalizerOwner, reinterpret_cast<void*>(finalizer)); // Balanced by FinalizerOwner::finalize().
2229 }
2230
2231 void Heap::FinalizerOwner::finalize(Handle<Unknown> handle, void* context)
2232 {
2233     HandleSlot slot = handle.slot();
2234     Finalizer finalizer = reinterpret_cast<Finalizer>(context);
2235     finalizer(slot->asCell());
2236     WeakSet::deallocate(WeakImpl::asWeakImpl(slot));
2237 }
2238
2239 void Heap::addExecutable(ExecutableBase* executable)
2240 {
2241     m_executables.append(executable);
2242 }
2243
2244 void Heap::collectAllGarbageIfNotDoneRecently()
2245 {
2246     if (!m_fullActivityCallback) {
2247         collectAllGarbage();
2248         return;
2249     }
2250
2251     if (m_fullActivityCallback->didSyncGCRecently()) {
2252         // A synchronous GC was already requested recently so we merely accelerate next collection.
2253         reportAbandonedObjectGraph();
2254         return;
2255     }
2256
2257     m_fullActivityCallback->setDidSyncGCRecently();
2258     collectAllGarbage();
2259 }
2260
2261 bool Heap::shouldDoFullCollection(std::optional<CollectionScope> scope) const
2262 {
2263     if (!Options::useGenerationalGC())
2264         return true;
2265
2266     if (!scope)
2267         return m_shouldDoFullCollection;
2268     return *scope == CollectionScope::Full;
2269 }
2270
2271 void Heap::addLogicallyEmptyWeakBlock(WeakBlock* block)
2272 {
2273     m_logicallyEmptyWeakBlocks.append(block);
2274 }
2275
2276 void Heap::sweepAllLogicallyEmptyWeakBlocks()
2277 {
2278     if (m_logicallyEmptyWeakBlocks.isEmpty())
2279         return;
2280
2281     m_indexOfNextLogicallyEmptyWeakBlockToSweep = 0;
2282     while (sweepNextLogicallyEmptyWeakBlock()) { }
2283 }
2284
2285 bool Heap::sweepNextLogicallyEmptyWeakBlock()
2286 {
2287     if (m_indexOfNextLogicallyEmptyWeakBlockToSweep == WTF::notFound)
2288         return false;
2289
2290     WeakBlock* block = m_logicallyEmptyWeakBlocks[m_indexOfNextLogicallyEmptyWeakBlockToSweep];
2291
2292     block->sweep();
2293     if (block->isEmpty()) {
2294         std::swap(m_logicallyEmptyWeakBlocks[m_indexOfNextLogicallyEmptyWeakBlockToSweep], m_logicallyEmptyWeakBlocks.last());
2295         m_logicallyEmptyWeakBlocks.removeLast();
2296         WeakBlock::destroy(*this, block);
2297     } else
2298         m_indexOfNextLogicallyEmptyWeakBlockToSweep++;
2299
2300     if (m_indexOfNextLogicallyEmptyWeakBlockToSweep >= m_logicallyEmptyWeakBlocks.size()) {
2301         m_indexOfNextLogicallyEmptyWeakBlockToSweep = WTF::notFound;
2302         return false;
2303     }
2304
2305     return true;
2306 }
2307
2308 size_t Heap::visitCount()
2309 {
2310     size_t result = 0;
2311     forEachSlotVisitor(
2312         [&] (SlotVisitor& visitor) {
2313             result += visitor.visitCount();
2314         });
2315     return result;
2316 }
2317
2318 size_t Heap::bytesVisited()
2319 {
2320     size_t result = 0;
2321     forEachSlotVisitor(
2322         [&] (SlotVisitor& visitor) {
2323             result += visitor.bytesVisited();
2324         });
2325     return result;
2326 }
2327
2328 void Heap::forEachCodeBlockImpl(const ScopedLambda<bool(CodeBlock*)>& func)
2329 {
2330     // We don't know the full set of CodeBlocks until compilation has terminated.
2331     completeAllJITPlans();
2332
2333     return m_codeBlocks->iterate(func);
2334 }
2335
2336 void Heap::forEachCodeBlockIgnoringJITPlansImpl(const AbstractLocker& locker, const ScopedLambda<bool(CodeBlock*)>& func)
2337 {
2338     return m_codeBlocks->iterate(locker, func);
2339 }
2340
2341 void Heap::writeBarrierSlowPath(const JSCell* from)
2342 {
2343     if (UNLIKELY(mutatorShouldBeFenced())) {
2344         // In this case, the barrierThreshold is the tautological threshold, so from could still be
2345         // not black. But we can't know for sure until we fire off a fence.
2346         WTF::storeLoadFence();
2347         if (from->cellState() != CellState::PossiblyBlack)
2348             return;
2349     }
2350     
2351     addToRememberedSet(from);
2352 }
2353
2354 bool Heap::isCurrentThreadBusy()
2355 {
2356     return mayBeGCThread() || mutatorState() != MutatorState::Running;
2357 }
2358
2359 void Heap::reportExtraMemoryVisited(size_t size)
2360 {
2361     size_t* counter = &m_extraMemorySize;
2362     
2363     for (;;) {
2364         size_t oldSize = *counter;
2365         if (WTF::atomicCompareExchangeWeakRelaxed(counter, oldSize, oldSize + size))
2366             return;
2367     }
2368 }
2369
2370 #if ENABLE(RESOURCE_USAGE)
2371 void Heap::reportExternalMemoryVisited(size_t size)
2372 {
2373     size_t* counter = &m_externalMemorySize;
2374
2375     for (;;) {
2376         size_t oldSize = *counter;
2377         if (WTF::atomicCompareExchangeWeakRelaxed(counter, oldSize, oldSize + size))
2378             return;
2379     }
2380 }
2381 #endif
2382
2383 void Heap::collectIfNecessaryOrDefer(GCDeferralContext* deferralContext)
2384 {
2385     ASSERT(!DisallowGC::isGCDisallowedOnCurrentThread());
2386
2387     if (!m_isSafeToCollect)
2388         return;
2389     switch (mutatorState()) {
2390     case MutatorState::Running:
2391     case MutatorState::Allocating:
2392         break;
2393     case MutatorState::Sweeping:
2394     case MutatorState::Collecting:
2395         return;
2396     }
2397     if (!Options::useGC())
2398         return;
2399     
2400     if (mayNeedToStop()) {
2401         if (deferralContext)
2402             deferralContext->m_shouldGC = true;
2403         else if (isDeferred())
2404             m_didDeferGCWork = true;
2405         else
2406             stopIfNecessary();
2407     }
2408     
2409     if (UNLIKELY(Options::gcMaxHeapSize())) {
2410         if (m_bytesAllocatedThisCycle <= Options::gcMaxHeapSize())
2411             return;
2412     } else {
2413         if (m_bytesAllocatedThisCycle <= m_maxEdenSize)
2414             return;
2415     }
2416
2417     if (deferralContext)
2418         deferralContext->m_shouldGC = true;
2419     else if (isDeferred())
2420         m_didDeferGCWork = true;
2421     else {
2422         collectAsync();
2423         stopIfNecessary(); // This will immediately start the collection if we have the conn.
2424     }
2425 }
2426
2427 void Heap::decrementDeferralDepthAndGCIfNeededSlow()
2428 {
2429     // Can't do anything if we're still deferred.
2430     if (m_deferralDepth)
2431         return;
2432     
2433     ASSERT(!isDeferred());
2434     
2435     m_didDeferGCWork = false;
2436     // FIXME: Bring back something like the DeferGCProbability mode.
2437     // https://bugs.webkit.org/show_bug.cgi?id=166627
2438     collectIfNecessaryOrDefer();
2439 }
2440
2441 void Heap::registerWeakGCMap(void* weakGCMap, std::function<void()> pruningCallback)
2442 {
2443     m_weakGCMaps.add(weakGCMap, WTFMove(pruningCallback));
2444 }
2445
2446 void Heap::unregisterWeakGCMap(void* weakGCMap)
2447 {
2448     m_weakGCMaps.remove(weakGCMap);
2449 }
2450
2451 void Heap::didAllocateBlock(size_t capacity)
2452 {
2453 #if ENABLE(RESOURCE_USAGE)
2454     m_blockBytesAllocated += capacity;
2455 #else
2456     UNUSED_PARAM(capacity);
2457 #endif
2458 }
2459
2460 void Heap::didFreeBlock(size_t capacity)
2461 {
2462 #if ENABLE(RESOURCE_USAGE)
2463     m_blockBytesAllocated -= capacity;
2464 #else
2465     UNUSED_PARAM(capacity);
2466 #endif
2467 }
2468
2469 #if USE(CF)
2470 void Heap::setRunLoop(CFRunLoopRef runLoop)
2471 {
2472     m_runLoop = runLoop;
2473     m_fullActivityCallback->setRunLoop(runLoop);
2474     m_edenActivityCallback->setRunLoop(runLoop);
2475     m_sweeper->setRunLoop(runLoop);
2476 }
2477 #endif // USE(CF)
2478
2479 void Heap::addCoreConstraints()
2480 {
2481     m_constraintSet->add(
2482         "Cs", "Conservative Scan",
2483         [this] (SlotVisitor& slotVisitor, const VisitingTimeout&) {
2484             TimingScope preConvergenceTimingScope(*this, "Constraint: conservative scan");
2485             m_objectSpace.prepareForConservativeScan();
2486             ConservativeRoots conservativeRoots(*this);
2487             SuperSamplerScope superSamplerScope(false);
2488             gatherStackRoots(conservativeRoots);
2489             gatherJSStackRoots(conservativeRoots);
2490             gatherScratchBufferRoots(conservativeRoots);
2491             slotVisitor.append(conservativeRoots);
2492         },
2493         ConstraintVolatility::GreyedByExecution);
2494     
2495     m_constraintSet->add(
2496         "Msr", "Misc Small Roots",
2497         [this] (SlotVisitor& slotVisitor, const VisitingTimeout&) {
2498 #if JSC_OBJC_API_ENABLED
2499             scanExternalRememberedSet(*m_vm, slotVisitor);
2500 #endif
2501
2502             if (m_vm->smallStrings.needsToBeVisited(*m_collectionScope))
2503                 m_vm->smallStrings.visitStrongReferences(slotVisitor);
2504             
2505             for (auto& pair : m_protectedValues)
2506                 slotVisitor.appendUnbarriered(pair.key);
2507             
2508             if (m_markListSet && m_markListSet->size())
2509                 MarkedArgumentBuffer::markLists(slotVisitor, *m_markListSet);
2510             
2511             slotVisitor.appendUnbarriered(m_vm->exception());
2512             slotVisitor.appendUnbarriered(m_vm->lastException());
2513         },
2514         ConstraintVolatility::GreyedByExecution);
2515     
2516     m_constraintSet->add(
2517         "Sh", "Strong Handles",
2518         [this] (SlotVisitor& slotVisitor, const VisitingTimeout&) {
2519             m_handleSet.visitStrongHandles(slotVisitor);
2520             m_handleStack.visit(slotVisitor);
2521         },
2522         ConstraintVolatility::GreyedByExecution);
2523     
2524     m_constraintSet->add(
2525         "D", "Debugger",
2526         [this] (SlotVisitor& slotVisitor, const VisitingTimeout&) {
2527 #if ENABLE(SAMPLING_PROFILER)
2528             if (SamplingProfiler* samplingProfiler = m_vm->samplingProfiler()) {
2529                 LockHolder locker(samplingProfiler->getLock());
2530                 samplingProfiler->processUnverifiedStackTraces();
2531                 samplingProfiler->visit(slotVisitor);
2532                 if (Options::logGC() == GCLogging::Verbose)
2533                     dataLog("Sampling Profiler data:\n", slotVisitor);
2534             }
2535 #endif // ENABLE(SAMPLING_PROFILER)
2536             
2537             if (m_vm->typeProfiler())
2538                 m_vm->typeProfilerLog()->visit(slotVisitor);
2539             
2540             m_vm->shadowChicken().visitChildren(slotVisitor);
2541         },
2542         ConstraintVolatility::GreyedByExecution);
2543     
2544     m_constraintSet->add(
2545         "Jsr", "JIT Stub Routines",
2546         [this] (SlotVisitor& slotVisitor, const VisitingTimeout&) {
2547             m_jitStubRoutines->traceMarkedStubRoutines(slotVisitor);
2548         },
2549         ConstraintVolatility::GreyedByExecution);
2550     
2551     m_constraintSet->add(
2552         "Ws", "Weak Sets",
2553         [this] (SlotVisitor& slotVisitor, const VisitingTimeout&) {
2554             m_objectSpace.visitWeakSets(slotVisitor);
2555         },
2556         ConstraintVolatility::GreyedByMarking);
2557     
2558     m_constraintSet->add(
2559         "Wrh", "Weak Reference Harvesters",
2560         [this] (SlotVisitor& slotVisitor, const VisitingTimeout&) {
2561             for (WeakReferenceHarvester* current = m_weakReferenceHarvesters.head(); current; current = current->next())
2562                 current->visitWeakReferences(slotVisitor);
2563         },
2564         ConstraintVolatility::GreyedByMarking);
2565     
2566 #if ENABLE(DFG_JIT)
2567     m_constraintSet->add(
2568         "Dw", "DFG Worklists",
2569         [this] (SlotVisitor& slotVisitor, const VisitingTimeout&) {
2570             for (unsigned i = DFG::numberOfWorklists(); i--;)
2571                 DFG::existingWorklistForIndex(i).visitWeakReferences(slotVisitor);
2572             
2573             // FIXME: This is almost certainly unnecessary.
2574             // https://bugs.webkit.org/show_bug.cgi?id=166829
2575             DFG::iterateCodeBlocksForGC(
2576                 *m_vm,
2577                 [&] (CodeBlock* codeBlock) {
2578                     slotVisitor.appendUnbarriered(codeBlock);
2579                 });
2580             
2581             if (Options::logGC() == GCLogging::Verbose)
2582                 dataLog("DFG Worklists:\n", slotVisitor);
2583         },
2584         ConstraintVolatility::GreyedByMarking);
2585 #endif
2586     
2587     m_constraintSet->add(
2588         "Cb", "CodeBlocks",
2589         [this] (SlotVisitor& slotVisitor, const VisitingTimeout&) {
2590             iterateExecutingAndCompilingCodeBlocksWithoutHoldingLocks(
2591                 [&] (CodeBlock* codeBlock) {
2592                     // Visit the CodeBlock as a constraint only if it's black.
2593                     if (Heap::isMarked(codeBlock)
2594                         && codeBlock->cellState() == CellState::PossiblyBlack)
2595                         slotVisitor.visitAsConstraint(codeBlock);
2596                 });
2597         },
2598         ConstraintVolatility::SeldomGreyed);
2599     
2600     m_constraintSet->add(
2601         "Mrms", "Mutator+Race Mark Stack",
2602         [this] (SlotVisitor& slotVisitor, const VisitingTimeout&) {
2603             // Indicate to the fixpoint that we introduced work!
2604             size_t size = m_mutatorMarkStack->size() + m_raceMarkStack->size();
2605             slotVisitor.addToVisitCount(size);
2606             
2607             if (Options::logGC())
2608                 dataLog("(", size, ")");
2609             
2610             m_mutatorMarkStack->transferTo(slotVisitor.mutatorMarkStack());
2611             m_raceMarkStack->transferTo(slotVisitor.mutatorMarkStack());
2612         },
2613         [this] (SlotVisitor&) -> double {
2614             return m_mutatorMarkStack->size() + m_raceMarkStack->size();
2615         },
2616         ConstraintVolatility::GreyedByExecution);
2617 }
2618
2619 void Heap::addMarkingConstraint(std::unique_ptr<MarkingConstraint> constraint)
2620 {
2621     PreventCollectionScope preventCollectionScope(*this);
2622     m_constraintSet->add(WTFMove(constraint));
2623 }
2624
2625 void Heap::notifyIsSafeToCollect()
2626 {
2627     MonotonicTime before;
2628     if (Options::logGC()) {
2629         before = MonotonicTime::now();
2630         dataLog("[GC<", RawPointer(this), ">: starting ");
2631     }
2632     
2633     addCoreConstraints();
2634     
2635     m_isSafeToCollect = true;
2636     
2637     if (Options::collectContinuously()) {
2638         m_collectContinuouslyThread = createThread(
2639             "JSC DEBUG Continuous GC",
2640             [this] () {
2641                 MonotonicTime initialTime = MonotonicTime::now();
2642                 Seconds period = Seconds::fromMilliseconds(Options::collectContinuouslyPeriodMS());
2643                 while (!m_shouldStopCollectingContinuously) {
2644                     {
2645                         LockHolder locker(*m_threadLock);
2646                         if (m_requests.isEmpty()) {
2647                             m_requests.append(std::nullopt);
2648                             m_lastGrantedTicket++;
2649                             m_threadCondition->notifyOne(locker);
2650                         }
2651                     }
2652                     
2653                     {
2654                         LockHolder locker(m_collectContinuouslyLock);
2655                         Seconds elapsed = MonotonicTime::now() - initialTime;
2656                         Seconds elapsedInPeriod = elapsed % period;
2657                         MonotonicTime timeToWakeUp =
2658                             initialTime + elapsed - elapsedInPeriod + period;
2659                         while (!hasElapsed(timeToWakeUp) && !m_shouldStopCollectingContinuously) {
2660                             m_collectContinuouslyCondition.waitUntil(
2661                                 m_collectContinuouslyLock, timeToWakeUp);
2662                         }
2663                     }
2664                 }
2665             });
2666     }
2667     
2668     if (Options::logGC())
2669         dataLog((MonotonicTime::now() - before).milliseconds(), "ms]\n");
2670 }
2671
2672 void Heap::preventCollection()
2673 {
2674     if (!m_isSafeToCollect)
2675         return;
2676     
2677     // This prevents the collectContinuously thread from starting a collection.
2678     m_collectContinuouslyLock.lock();
2679     
2680     // Wait for all collections to finish.
2681     waitForCollector(
2682         [&] (const AbstractLocker&) -> bool {
2683             ASSERT(m_lastServedTicket <= m_lastGrantedTicket);
2684             return m_lastServedTicket == m_lastGrantedTicket;
2685         });
2686     
2687     // Now a collection can only start if this thread starts it.
2688     RELEASE_ASSERT(!m_collectionScope);
2689 }
2690
2691 void Heap::allowCollection()
2692 {
2693     if (!m_isSafeToCollect)
2694         return;
2695     
2696     m_collectContinuouslyLock.unlock();
2697 }
2698
2699 template<typename Func>
2700 void Heap::forEachSlotVisitor(const Func& func)
2701 {
2702     auto locker = holdLock(m_parallelSlotVisitorLock);
2703     func(*m_collectorSlotVisitor);
2704     func(*m_mutatorSlotVisitor);
2705     for (auto& slotVisitor : m_parallelSlotVisitors)
2706         func(*slotVisitor);
2707 }
2708
2709 void Heap::setMutatorShouldBeFenced(bool value)
2710 {
2711     m_mutatorShouldBeFenced = value;
2712     m_barrierThreshold = value ? tautologicalThreshold : blackThreshold;
2713 }
2714
2715 void Heap::performIncrement(size_t bytes)
2716 {
2717     if (!m_objectSpace.isMarking())
2718         return;
2719
2720     m_incrementBalance += bytes * Options::gcIncrementScale();
2721
2722     // Save ourselves from crazy. Since this is an optimization, it's OK to go back to any consistent
2723     // state when the double goes wild.
2724     if (std::isnan(m_incrementBalance) || std::isinf(m_incrementBalance))
2725         m_incrementBalance = 0;
2726     
2727     if (m_incrementBalance < static_cast<double>(Options::gcIncrementBytes()))
2728         return;
2729
2730     double targetBytes = m_incrementBalance;
2731     if (targetBytes <= 0)
2732         return;
2733     targetBytes = std::min(targetBytes, Options::gcIncrementMaxBytes());
2734
2735     SlotVisitor& slotVisitor = *m_mutatorSlotVisitor;
2736     ParallelModeEnabler parallelModeEnabler(slotVisitor);
2737     size_t bytesVisited = slotVisitor.performIncrementOfDraining(static_cast<size_t>(targetBytes));
2738     // incrementBalance may go negative here because it'll remember how many bytes we overshot.
2739     m_incrementBalance -= bytesVisited;
2740 }
2741
2742 } // namespace JSC