Debian Codegraph @

js/src/gc/Nursery.h

raw
1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*-
2 * vim: set ts=8 sw=2 et tw=80:
3 *
4 * This Source Code Form is subject to the terms of the Mozilla Public
5 * License, v. 2.0. If a copy of the MPL was not distributed with this file,
6 * You can obtain one at http://mozilla.org/MPL/2.0/. */
7
8 #ifndef gc_Nursery_h
9 #define gc_Nursery_h
10
11 #include "mozilla/EnumeratedArray.h"
12 #include "mozilla/TimeStamp.h"
13
14 #include <tuple>
15
16 #include "ds/LifoAlloc.h"
17 #include "ds/SlimLinkedList.h"
18 #include "gc/Allocator.h"
19 #include "gc/GCEnum.h"
20 #include "gc/GCProbes.h"
21 #include "gc/Heap.h"
22 #include "gc/MallocedBlockCache.h"
23 #include "gc/Pretenuring.h"
24 #include "js/AllocPolicy.h"
25 #include "js/Class.h"
26 #include "js/GCAPI.h"
27 #include "js/GCVector.h"
28 #include "js/HeapAPI.h"
29 #include "js/TypeDecls.h"
30 #include "js/UniquePtr.h"
31 #include "js/Utility.h"
32 #include "js/Vector.h"
33
34 #define FOR_EACH_NURSERY_PROFILE_TIME(_) \
35 /* Key Header text */ \
36 _(Total, "total") \
37 _(TraceValues, "mkVals") \
38 _(TraceCells, "mkClls") \
39 _(TraceSlots, "mkSlts") \
40 _(TraceWasmAnyRefs, "mkWars") \
41 _(TraceWholeCells, "mcWCll") \
42 _(TraceGenericEntries, "mkGnrc") \
43 _(CheckHashTables, "ckTbls") \
44 _(MarkRuntime, "mkRntm") \
45 _(MarkDebugger, "mkDbgr") \
46 _(SweepCaches, "swpCch") \
47 _(CollectToObjFP, "colObj") \
48 _(CollectToStrFP, "colStr") \
49 _(ObjectsTenuredCallback, "tenCB") \
50 _(Sweep, "sweep") \
51 _(UpdateJitActivations, "updtIn") \
52 _(FreeMallocedBuffers, "frSlts") \
53 _(FreeTrailerBlocks, "frTrBs") \
54 _(ClearNursery, "clear") \
55 _(PurgeStringToAtomCache, "pStoA") \
56 _(Pretenure, "pretnr")
57
58 template <typename T>
59 class SharedMem;
60
61 namespace mozilla {
62 class StringBuffer;
63 };
64
65 namespace js {
66
67 struct StringStats;
68 class AutoLockGCBgAlloc;
69 class ObjectElements;
70 struct NurseryChunk;
71 class HeapSlot;
72 class JSONPrinter;
73 class MapObject;
74 class NurseryDecommitTask;
75 class NurserySweepTask;
76 class SetObject;
77 class JS_PUBLIC_API Sprinter;
78
79 namespace gc {
80
81 class AutoGCSession;
82 struct Cell;
83 class GCSchedulingTunables;
84 struct LargeBuffer;
85 class StoreBuffer;
86 class TenuringTracer;
87
88 } // namespace gc
89
90 class Nursery {
91 public:
92 explicit Nursery(gc::GCRuntime* gc);
93 ~Nursery();
94
95 [[nodiscard]] bool init(AutoLockGCBgAlloc& lock);
96
97 void enable();
98 void disable();
99 bool isEnabled() const { return capacity() != 0; }
100
101 void enableStrings();
102 void disableStrings();
103 bool canAllocateStrings() const { return canAllocateStrings_; }
104
105 void enableBigInts();
106 void disableBigInts();
107 bool canAllocateBigInts() const { return canAllocateBigInts_; }
108
109 void setSemispaceEnabled(bool enabled);
110 bool semispaceEnabled() const { return semispaceEnabled_; }
111
112 // Return true if no allocations have been made since the last collection.
113 bool isEmpty() const;
114
115 // Check whether an arbitrary pointer is within the nursery. This is
116 // slower than IsInsideNursery(Cell*), but works on all types of pointers.
117 bool isInside(gc::Cell* cellp) const = delete;
118 inline bool isInside(const void* p) const;
119
120 template <typename T>
121 inline bool isInside(const SharedMem<T>& p) const;
122
123 // Allocate and return a pointer to a new GC thing. Returns nullptr if the
124 // Nursery is full.
125 void* allocateCell(gc::AllocSite* site, size_t size, JS::TraceKind kind);
126
127 // Allocate and return a pointer to a new GC thing. Returns nullptr if the
128 // handleAllocationFailure() needs to be called before retrying.
129 inline void* tryAllocateCell(gc::AllocSite* site, size_t size,
130 JS::TraceKind kind);
131
132 // Attempt to handle the failure of tryAllocate. Returns a GCReason if minor
133 // GC is required, or NO_REASON if the failure was handled and allocation will
134 // now succeed.
135 [[nodiscard]] JS::GCReason handleAllocationFailure();
136
137 static size_t nurseryCellHeaderSize() {
138 return sizeof(gc::NurseryCellHeader);
139 }
140
141 // Allocate a buffer for a given zone, using the nursery if possible. Returns
142 // <buffer, isMalloced> so the caller can register the buffer if
143 // needed. Returns false in |isMalloced| if the allocation fails.
144 //
145 // Use the following API if the owning Cell is already known.
146 std::tuple<void*, bool> allocNurseryOrMallocBuffer(JS::Zone* zone,
147 size_t nbytes,
148 arena_id_t arenaId);
149 std::tuple<void*, bool> allocateBuffer(JS::Zone* zone, size_t nbytes);
150
151 // Like allocNurseryOrMallocBuffer, but returns nullptr if the buffer can't
152 // be allocated in the nursery.
153 void* tryAllocateNurseryBuffer(JS::Zone* zone, size_t nbytes,
154 arena_id_t arenaId);
155
156 // Allocate a buffer for a given Cell, using the nursery if possible and
157 // owner is in the nursery.
158 void* allocNurseryOrMallocBuffer(JS::Zone* zone, gc::Cell* owner,
159 size_t nbytes, arena_id_t arenaId);
160 void* allocateBuffer(JS::Zone* zone, gc::Cell* owner, size_t nbytes);
161
162 // Allocate a zero-initialized buffer for a given zone, using the nursery if
163 // possible. If the buffer isn't allocated in the nursery, the given arena is
164 // used. Returns <buffer, isMalloced>. Returns false in |isMalloced| if the
165 // allocation fails.
166 std::tuple<void*, bool> allocateZeroedBuffer(JS::Zone* zone, size_t nbytes,
167 arena_id_t arena);
168
169 // Allocate a zero-initialized buffer for a given Cell, using the nursery if
170 // possible and |owner| is in the nursery. If the buffer isn't allocated in
171 // the nursery, the given arena is used.
172 void* allocateZeroedBuffer(gc::Cell* owner, size_t nbytes, arena_id_t arena);
173
174 // Resize an existing buffer.
175 void* reallocNurseryOrMallocBuffer(JS::Zone* zone, gc::Cell* cell,
176 void* oldBuffer, size_t oldBytes,
177 size_t newBytes, arena_id_t arena);
178
179 // Resize an existing buffer.
180 void* reallocateBuffer(JS::Zone* zone, gc::Cell* cell, void* oldBuffer,
181 size_t oldBytes, size_t newBytes);
182
183 // Free an object buffer.
184 void freeBuffer(void* buffer, size_t nbytes);
185
186 // The maximum number of bytes allowed to reside in nursery buffers.
187 static const size_t MaxNurseryBufferSize = 1024;
188
189 // Do a minor collection.
190 void collect(JS::GCOptions options, JS::GCReason reason);
191
192 // If the thing at |*ref| in the Nursery has been forwarded, set |*ref| to
193 // the new location and return true. Otherwise return false and leave
194 // |*ref| unset.
195 [[nodiscard]] MOZ_ALWAYS_INLINE static bool getForwardedPointer(
196 js::gc::Cell** ref);
197
198 // Forward a slots/elements pointer stored in an Ion frame.
199 void forwardBufferPointer(uintptr_t* pSlotsElems);
200
201 inline void maybeSetForwardingPointer(JSTracer* trc, void* oldData,
202 void* newData, bool direct);
203 inline void setForwardingPointerWhileTenuring(void* oldData, void* newData,
204 bool direct);
205
206 // Handle an external buffer when a cell is promoted. Updates the pointer to
207 // the (possibly moved) buffer and returns whether it was moved.
208 // bytesUsed can be less than bytesCapacity if not all bytes need to be copied
209 // when the buffer is moved.
210 enum WasBufferMoved : bool { BufferNotMoved = false, BufferMoved = true };
211 WasBufferMoved maybeMoveRawBufferOnPromotion(void** bufferp, gc::Cell* owner,
212 size_t bytesUsed,
213 size_t bytesCapacity,
214 MemoryUse use, arena_id_t arena);
215 template <typename T>
216 WasBufferMoved maybeMoveBufferOnPromotion(T** bufferp, gc::Cell* owner,
217 size_t bytesUsed,
218 size_t bytesCapacity, MemoryUse use,
219 arena_id_t arena) {
220 return maybeMoveRawBufferOnPromotion(reinterpret_cast<void**>(bufferp),
221 owner, bytesUsed, bytesCapacity, use,
222 arena);
223 }
224 template <typename T>
225 WasBufferMoved maybeMoveNurseryOrMallocBufferOnPromotion(T** bufferp,
226 gc::Cell* owner,
227 size_t nbytes,
228 MemoryUse use) {
229 return maybeMoveBufferOnPromotion(bufferp, owner, nbytes, nbytes, use,
230 MallocArena);
231 }
232
233 WasBufferMoved maybeMoveRawBufferOnPromotion(void** bufferp, gc::Cell* owner,
234 size_t nbytes);
235 template <typename T>
236 WasBufferMoved maybeMoveBufferOnPromotion(T** bufferp, gc::Cell* owner,
237 size_t nbytes) {
238 return maybeMoveRawBufferOnPromotion(reinterpret_cast<void**>(bufferp),
239 owner, nbytes);
240 }
241
242 // Register a malloced buffer that is held by a nursery object, which
243 // should be freed at the end of a minor GC. Buffers are unregistered when
244 // their owning objects are tenured.
245 [[nodiscard]] bool registerMallocedBuffer(void* buffer, size_t nbytes);
246 void registerBuffer(void* buffer, size_t nbytes);
247
248 // Mark a malloced buffer as no longer needing to be freed.
249 inline void removeMallocedBuffer(void* buffer, size_t nbytes);
250
251 // Mark a malloced buffer as no longer needing to be freed during minor
252 // GC. There's no need to account for the size here since all remaining
253 // buffers will soon be freed.
254 inline void removeMallocedBufferDuringMinorGC(void* buffer);
255
256 [[nodiscard]] bool addedUniqueIdToCell(gc::Cell* cell) {
257 MOZ_ASSERT(IsInsideNursery(cell));
258 MOZ_ASSERT(isEnabled());
259 return cellsWithUid_.append(cell);
260 }
261
262 [[nodiscard]] inline bool addStringBuffer(JSLinearString* s);
263
264 [[nodiscard]] inline bool addExtensibleStringBuffer(
265 JSLinearString* s, mozilla::StringBuffer* buffer,
266 bool updateMallocBytes = true);
267 inline void removeExtensibleStringBuffer(JSLinearString* s,
268 bool updateMallocBytes = true);
269
270 size_t sizeOfMallocedBuffers(mozilla::MallocSizeOf mallocSizeOf) const;
271
272 // Wasm "trailer" (C++-heap-allocated) blocks.
273 //
274 // All involved blocks are allocated/deallocated via this nursery's
275 // `mallocedBlockCache_`. Hence we must store both the block address and
276 // its freelist ID, wrapped up in a PointerAndUint7.
277 //
278 // Trailer blocks registered here are added to `trailersAdded_`. Those that
279 // are later deregistered as a result of `obj_moved` calls that indicate
280 // tenuring, should be added to `trailersRemoved_`.
281 //
282 // Unfortunately ::unregisterTrailer cannot be allowed to OOM. To get
283 // around this we rely on the observation that all deregistered blocks
284 // should previously have been registered, so the deregistered set can never
285 // be larger than the registered set. Hence ::registerTrailer effectively
286 // preallocates space in `trailersRemoved_` so as to ensure that, in the
287 // worst case, all registered blocks can be handed to ::unregisterTrailer
288 // without needing to resize `trailersRemoved_` in ::unregisterTrailer.
289 //
290 // The downside is that most of the space in `trailersRemoved_` is wasted in
291 // the case where there are few blocks deregistered. This is unfortunate
292 // but it's hard to see how to avoid it.
293 //
294 // At the end of a minor collection, all blocks in the set `trailersAdded_ -
295 // trailersRemoved_[0 .. trailersRemovedUsed_ - 1]` are handed back to the
296 // `mallocedBlockCache_`.
297 [[nodiscard]] inline bool registerTrailer(PointerAndUint7 blockAndListID,
298 size_t nBytes);
299 inline void unregisterTrailer(void* block);
300 size_t sizeOfTrailerBlockSets(mozilla::MallocSizeOf mallocSizeOf) const;
301
302 size_t totalCapacity() const;
303 size_t totalCommitted() const;
304
305 #ifdef JS_GC_ZEAL
306 void enterZealMode();
307 void leaveZealMode();
308 #endif
309
310 // Write profile time JSON on JSONPrinter.
311 void renderProfileJSON(JSONPrinter& json) const;
312
313 // Print header line for profile times.
314 void printProfileHeader();
315
316 // Print total profile times on shutdown.
317 void printTotalProfileTimes();
318
319 void* addressOfPosition() const { return (void**)&toSpace.position_; }
320 static constexpr int32_t offsetOfCurrentEndFromPosition() {
321 return offsetof(Nursery, toSpace.currentEnd_) -
322 offsetof(Nursery, toSpace.position_);
323 }
324
325 void* addressOfNurseryAllocatedSites() {
326 return pretenuringNursery.addressOfAllocatedSites();
327 }
328
329 void requestMinorGC(JS::GCReason reason);
330
331 bool minorGCRequested() const {
332 return minorGCTriggerReason_ != JS::GCReason::NO_REASON;
333 }
334 JS::GCReason minorGCTriggerReason() const { return minorGCTriggerReason_; }
335
336 bool wantEagerCollection() const;
337
338 bool enableProfiling() const { return enableProfiling_; }
339
340 bool addMapWithNurseryIterators(MapObject* obj) {
341 MOZ_ASSERT_IF(!mapsWithNurseryIterators_.empty(),
342 mapsWithNurseryIterators_.back() != obj);
343 return mapsWithNurseryIterators_.append(obj);
344 }
345 bool addSetWithNurseryIterators(SetObject* obj) {
346 MOZ_ASSERT_IF(!setsWithNurseryIterators_.empty(),
347 setsWithNurseryIterators_.back() != obj);
348 return setsWithNurseryIterators_.append(obj);
349 }
350
351 void joinSweepTask();
352 void joinDecommitTask();
353
354 #ifdef DEBUG
355 bool sweepTaskIsIdle();
356 #endif
357
358 mozilla::TimeStamp collectionStartTime() {
359 return startTimes_[ProfileKey::Total];
360 }
361
362 bool canCreateAllocSite() { return pretenuringNursery.canCreateAllocSite(); }
363 void noteAllocSiteCreated() { pretenuringNursery.noteAllocSiteCreated(); }
364 bool reportPretenuring() const { return pretenuringReportFilter_.enabled; }
365 void maybeStopPretenuring(gc::GCRuntime* gc) {
366 pretenuringNursery.maybeStopPretenuring(gc);
367 }
368
369 void setAllocFlagsForZone(JS::Zone* zone);
370
371 bool shouldTenureEverything(JS::GCReason reason);
372
373 inline bool inCollectedRegion(const gc::Cell* cell) const;
374 inline bool inCollectedRegion(void* ptr) const;
375
376 void trackMallocedBufferOnPromotion(void* buffer, gc::Cell* owner,
377 size_t nbytes, MemoryUse use);
378 void trackBufferOnPromotion(void* buffer, gc::Cell* owner, size_t nbytes);
379 void trackTrailerOnPromotion(void* buffer, gc::Cell* owner, size_t nbytes,
380 size_t overhead, MemoryUse use);
381
382 // Round a size in bytes to the nearest valid nursery size.
383 static size_t roundSize(size_t size);
384
385 // The malloc'd block cache.
386 gc::MallocedBlockCache& mallocedBlockCache() { return mallocedBlockCache_; }
387 size_t sizeOfMallocedBlockCache(mozilla::MallocSizeOf mallocSizeOf) const {
388 return mallocedBlockCache_.sizeOfExcludingThis(mallocSizeOf);
389 }
390
391 inline void addMallocedBufferBytes(size_t nbytes);
392
393 mozilla::TimeStamp lastCollectionEndTime() const;
394
395 private:
396 struct Space;
397
398 enum class ProfileKey {
399 #define DEFINE_TIME_KEY(name, text) name,
400 FOR_EACH_NURSERY_PROFILE_TIME(DEFINE_TIME_KEY)
401 #undef DEFINE_TIME_KEY
402 KeyCount
403 };
404
405 using ProfileTimes = mozilla::EnumeratedArray<ProfileKey, mozilla::TimeStamp,
406 size_t(ProfileKey::KeyCount)>;
407 using ProfileDurations =
408 mozilla::EnumeratedArray<ProfileKey, mozilla::TimeDuration,
409 size_t(ProfileKey::KeyCount)>;
410
411 size_t capacity() const { return capacity_; }
412
413 // Total number of chunks and the capacity of the current nursery
414 // space. Chunks will be lazily allocated and added to the chunks array up to
415 // this limit. After that the nursery must be collected. This limit may be
416 // changed at the end of collection by maybeResizeNursery.
417 uint32_t maxChunkCount() const {
418 MOZ_ASSERT(toSpace.maxChunkCount_);
419 return toSpace.maxChunkCount_;
420 }
421
422 // Number of allocated (ready to use) chunks.
423 unsigned allocatedChunkCount() const { return toSpace.chunks_.length(); }
424
425 uint32_t currentChunk() const { return toSpace.currentChunk_; }
426 uint32_t startChunk() const { return toSpace.startChunk_; }
427 uintptr_t startPosition() const { return toSpace.startPosition_; }
428
429 // Used and free space both include chunk headers for that part of the
430 // nursery.
431 MOZ_ALWAYS_INLINE size_t usedSpace() const {
432 return capacity() - freeSpace();
433 }
434 MOZ_ALWAYS_INLINE size_t freeSpace() const {
435 MOZ_ASSERT(isEnabled());
436 MOZ_ASSERT(currentChunk() < maxChunkCount());
437 return (currentEnd() - position()) +
438 (maxChunkCount() - currentChunk() - 1) * gc::ChunkSize;
439 }
440
441 // Calculate the promotion rate of the most recent minor GC.
442 // The valid_for_tenuring parameter is used to return whether this
443 // promotion rate is accurate enough (the nursery was full enough) to be
444 // used for tenuring and other decisions.
445 //
446 // Must only be called if the previousGC data is initialised.
447 double calcPromotionRate(bool* validForTenuring) const;
448
449 void freeTrailerBlocks(JS::GCOptions options, JS::GCReason reason);
450
451 NurseryChunk& chunk(unsigned index) const { return *toSpace.chunks_[index]; }
452
453 // Set the allocation position to the start of a chunk. This sets
454 // currentChunk_, position_ and currentEnd_ values as appropriate.
455 void moveToStartOfChunk(unsigned chunkno);
456
457 bool initFirstChunk(AutoLockGCBgAlloc& lock);
458 void setCapacity(size_t newCapacity);
459
460 void poisonAndInitCurrentChunk();
461
462 void setCurrentEnd();
463 void setStartToCurrentPosition();
464
465 // Allocate another chunk.
466 [[nodiscard]] bool allocateNextChunk(AutoLockGCBgAlloc& lock);
467
468 uintptr_t position() const { return toSpace.position_; }
469 uintptr_t currentEnd() const { return toSpace.currentEnd_; }
470
471 MOZ_ALWAYS_INLINE bool isSubChunkMode() const;
472
473 JSRuntime* runtime() const;
474 gcstats::Statistics& stats() const;
475
476 const js::gc::GCSchedulingTunables& tunables() const;
477
478 void getAllocFlagsForZone(JS::Zone* zone, bool* allocObjectsOut,
479 bool* allocStringsOut, bool* allocBigIntsOut);
480 void updateAllZoneAllocFlags();
481 void updateAllocFlagsForZone(JS::Zone* zone);
482 void discardCodeAndSetJitFlagsForZone(JS::Zone* zone);
483
484 void* allocate(size_t size);
485
486 // Common internal allocator function. If this fails, call
487 // handleAllocationFailure to see whether it's possible to retry.
488 inline void* tryAllocate(size_t size);
489
490 [[nodiscard]] bool moveToNextChunk();
491
492 bool freeSpaceIsBelowEagerThreshold() const;
493 bool isUnderused() const;
494
495 struct CollectionResult {
496 size_t tenuredBytes;
497 size_t tenuredCells;
498 };
499 CollectionResult doCollection(gc::AutoGCSession& session,
500 JS::GCOptions options, JS::GCReason reason);
501 void swapSpaces();
502 void traceRoots(gc::AutoGCSession& session, gc::TenuringTracer& mover);
503
504 size_t doPretenuring(JSRuntime* rt, JS::GCReason reason,
505 bool validPromotionRate, double promotionRate);
506
507 // Handle relocation of slots/elements pointers stored in Ion frames.
508 inline void setForwardingPointer(void* oldData, void* newData, bool direct);
509
510 inline void setDirectForwardingPointer(void* oldData, void* newData);
511 void setIndirectForwardingPointer(void* oldData, void* newData);
512
513 inline void setSlotsForwardingPointer(HeapSlot* oldSlots, HeapSlot* newSlots,
514 uint32_t nslots);
515 inline void setElementsForwardingPointer(ObjectElements* oldHeader,
516 ObjectElements* newHeader,
517 uint32_t capacity);
518
519 #ifdef DEBUG
520 bool checkForwardingPointerInsideNursery(void* ptr);
521 #endif
522
523 // Discard pointers to objects that have been freed.
524 void sweep();
525
526 // In a minor GC, resets the start and end positions, the current chunk and
527 // current position.
528 void setNewExtentAndPosition();
529
530 // the nursery on debug & nightly builds.
531 void clear();
532
533 void clearMapAndSetNurseryIterators();
534 void sweepMapAndSetObjects();
535
536 void sweepStringsWithBuffer();
537
538 void sweepBuffers();
539
540 // Get per-space size limits.
541 size_t maxSpaceSize() const;
542 size_t minSpaceSize() const;
543
544 // Change the allocable space provided by the nursery.
545 void maybeResizeNursery(JS::GCOptions options, JS::GCReason reason);
546 size_t targetSize(JS::GCOptions options, JS::GCReason reason);
547 void clearRecentGrowthData();
548 void growAllocableSpace(size_t newCapacity);
549 void shrinkAllocableSpace(size_t newCapacity);
550 void minimizeAllocableSpace();
551
552 // Free the chunks starting at firstFreeChunk until the end of the chunks
553 // vector. Shrinks the vector but does not update maxChunkCount().
554 void freeChunksFrom(Space& space, unsigned firstFreeChunk);
555
556 // During a semispace nursery collection, return whether a cell in fromspace
557 // was in the tospace of the previous collection, meaning that it should be
558 // tenured in this collection.
559 inline bool shouldTenure(gc::Cell* cell);
560
561 void sendTelemetry(JS::GCReason reason, mozilla::TimeDuration totalTime,
562 bool wasEmpty, double promotionRate,
563 size_t sitesPretenured);
564
565 void printCollectionProfile(JS::GCReason reason, double promotionRate);
566 void printDeduplicationData(js::StringStats& prev, js::StringStats& curr);
567
568 // Profile recording and printing.
569 void maybeClearProfileDurations();
570 void startProfile(ProfileKey key);
571 void endProfile(ProfileKey key);
572 static void printProfileDurations(const ProfileDurations& times,
573 Sprinter& sprinter);
574
575 mozilla::TimeStamp collectionStartTime() const;
576
577 private:
578 using BufferRelocationOverlay = void*;
579 using BufferSet = HashSet<void*, PointerHasher<void*>, SystemAllocPolicy>;
580
581 struct Space {
582 // Fields used during allocation fast path go first:
583
584 // Pointer to the first unallocated byte in the nursery.
585 uintptr_t position_ = 0;
586
587 // Pointer to the last byte of space in the current chunk.
588 uintptr_t currentEnd_ = 0;
589
590 // Vector of allocated chunks to allocate from.
591 Vector<NurseryChunk*, 0, SystemAllocPolicy> chunks_;
592
593 // The index of the chunk that is currently being allocated from.
594 uint32_t currentChunk_ = 0;
595
596 // The maximum number of chunks to allocate based on capacity_.
597 uint32_t maxChunkCount_ = 0;
598
599 // These fields refer to the beginning of the nursery. They're normally 0
600 // and chunk(0).start() respectively. Except when a generational GC zeal
601 // mode is active, then they may be arbitrary (see Nursery::clear()).
602 uint32_t startChunk_ = 0;
603 uintptr_t startPosition_ = 0;
604
605 // The set of malloc-allocated buffers owned by nursery objects. Any
606 // buffers that do not belong to a promoted thing at the end of a minor GC
607 // must be freed.
608 BufferSet mallocedBuffers;
609 size_t mallocedBufferBytes = 0;
610
611 // Wasm "trailer" (C++-heap-allocated) blocks. See comments above on
612 // ::registerTrailer and ::unregisterTrailer.
613 Vector<PointerAndUint7, 0, SystemAllocPolicy> trailersAdded_;
614 Vector<void*, 0, SystemAllocPolicy> trailersRemoved_;
615 size_t trailersRemovedUsed_ = 0;
616 size_t trailerBytes_ = 0;
617
618 gc::ChunkKind kind;
619
620 explicit Space(gc::ChunkKind kind);
621
622 inline bool isEmpty() const;
623 inline bool isInside(const void* p) const;
624
625 // Return the logical offset within the nursery of an address in a nursery
626 // chunk (chunks are discontiguous in memory).
627 inline size_t offsetFromAddress(uintptr_t addr) const;
628 inline size_t offsetFromExclusiveAddress(uintptr_t addr) const;
629
630 void setKind(gc::ChunkKind newKind);
631
632 void clear(Nursery* nursery);
633 void moveToStartOfChunk(Nursery* nursery, unsigned chunkno);
634 void setCurrentEnd(Nursery* nursery);
635 void setStartToCurrentPosition();
636 bool commitSubChunkRegion(size_t oldCapacity, size_t newCapacity);
637 void decommitSubChunkRegion(Nursery* nursery, size_t oldCapacity,
638 size_t newCapacity);
639 void freeTrailerBlocks(gc::MallocedBlockCache& mallocedBlockCache);
640
641 #ifdef DEBUG
642 void checkKind(gc::ChunkKind expected) const;
643 size_t findChunkIndex(uintptr_t chunkAddr) const;
644 #endif
645 };
646
647 Space toSpace;
648 Space fromSpace;
649
650 gc::GCRuntime* const gc;
651
652 // The current nursery capacity measured in bytes. It may grow up to this
653 // value without a collection, allocating chunks on demand. This limit may be
654 // changed by maybeResizeNursery() each collection. It includes chunk headers.
655 size_t capacity_;
656
657 uintptr_t tenureThreshold_ = 0;
658
659 gc::PretenuringNursery pretenuringNursery;
660
661 mozilla::TimeDuration timeInChunkAlloc_;
662
663 // Report minor collections taking at least this long, if enabled.
664 bool enableProfiling_ = false;
665 bool profileWorkers_ = false;
666
667 mozilla::TimeDuration profileThreshold_;
668
669 // Whether to use semispace collection.
670 bool semispaceEnabled_;
671
672 // Whether we will nursery-allocate strings.
673 bool canAllocateStrings_;
674
675 // Whether we will nursery-allocate BigInts.
676 bool canAllocateBigInts_;
677
678 // Report how many strings were deduplicated.
679 bool reportDeduplications_;
680
681 #ifdef JS_GC_ZEAL
682 // Report on the kinds of things promoted.
683 bool reportPromotion_;
684 #endif
685
686 // Whether to report information on pretenuring, and if so the allocation
687 // threshold at which to report details of each allocation site.
688 gc::AllocSiteFilter pretenuringReportFilter_;
689
690 // Whether and why a collection of this nursery has been requested. When this
691 // happens |prevPosition_| is set to the current position and |position_| set
692 // to the end of the chunk to force the next allocation to fail.
693 JS::GCReason minorGCTriggerReason_;
694 uintptr_t prevPosition_;
695
696 // Profiling data.
697
698 ProfileTimes startTimes_;
699 ProfileDurations profileDurations_;
700 ProfileDurations totalDurations_;
701
702 // Data about the previous collection.
703 struct PreviousGC {
704 JS::GCReason reason = JS::GCReason::NO_REASON;
705 size_t nurseryCapacity = 0;
706 size_t nurseryCommitted = 0;
707 size_t nurseryUsedBytes = 0;
708 size_t nurseryUsedChunkCount = 0;
709 size_t tenuredBytes = 0;
710 size_t tenuredCells = 0;
711 mozilla::TimeStamp endTime;
712 };
713 PreviousGC previousGC;
714
715 bool hasRecentGrowthData;
716 double smoothedTargetSize;
717
718 // During a collection most hoisted slot and element buffers indicate their
719 // new location with a forwarding pointer at the base. This does not work
720 // for buffers whose length is less than pointer width, or when different
721 // buffers might overlap each other. For these, an entry in the following
722 // table is used.
723 using ForwardedBufferMap =
724 HashMap<void*, void*, PointerHasher<void*>, SystemAllocPolicy>;
725 ForwardedBufferMap forwardedBuffers;
726
727 // When we assign a unique id to cell in the nursery, that almost always
728 // means that the cell will be in a hash table, and thus, held live,
729 // automatically moving the uid from the nursery to its new home in
730 // tenured. It is possible, if rare, for an object that acquired a uid to
731 // be dead before the next collection, in which case we need to know to
732 // remove it when we sweep.
733 //
734 // Note: we store the pointers as Cell* here, resulting in an ugly cast in
735 // sweep. This is because this structure is used to help implement
736 // stable object hashing and we have to break the cycle somehow.
737 using CellsWithUniqueIdVector = JS::GCVector<gc::Cell*, 8, SystemAllocPolicy>;
738 CellsWithUniqueIdVector cellsWithUid_;
739
740 // Lists of map and set objects with iterators allocated in the nursery. Such
741 // objects need to be swept after minor GC.
742 using MapObjectVector = Vector<MapObject*, 0, SystemAllocPolicy>;
743 MapObjectVector mapsWithNurseryIterators_;
744 using SetObjectVector = Vector<SetObject*, 0, SystemAllocPolicy>;
745 SetObjectVector setsWithNurseryIterators_;
746
747 // List of strings with StringBuffers allocated in the nursery. References
748 // to the buffers are dropped after minor GC. The list stores both the JS
749 // string and the StringBuffer to simplify interaction with AtomRefs and
750 // string deduplication.
751 using StringAndBuffer = std::pair<JSLinearString*, mozilla::StringBuffer*>;
752 using StringAndBufferVector =
753 JS::GCVector<StringAndBuffer, 8, SystemAllocPolicy>;
754 StringAndBufferVector stringBuffers_;
755
756 // Like stringBuffers_, but for extensible strings for flattened ropes. This
757 // requires a HashMap instead of a Vector because we need to remove the entry
758 // when transferring the buffer to a new extensible string during flattening.
759 using ExtensibleStringBuffers =
760 HashMap<JSLinearString*, mozilla::StringBuffer*,
761 js::PointerHasher<JSLinearString*>, js::SystemAllocPolicy>;
762 ExtensibleStringBuffers extensibleStringBuffers_;
763
764 // List of StringBuffers to release off-thread.
765 using StringBufferVector =
766 Vector<mozilla::StringBuffer*, 8, SystemAllocPolicy>;
767 StringBufferVector stringBuffersToReleaseAfterMinorGC_;
768
769 UniquePtr<NurserySweepTask> sweepTask;
770 UniquePtr<NurseryDecommitTask> decommitTask;
771
772 // A cache of small C++-heap allocated blocks associated with this Nursery.
773 // This provided so as to provide cheap allocation/deallocation of
774 // out-of-line storage areas as used by WasmStructObject and
775 // WasmArrayObject, although the mechanism is general and not specific to
776 // these object types. Regarding lifetimes, because the cache holds only
777 // blocks that are not currently in use, it can be flushed at any point with
778 // no correctness impact, only a performance impact.
779 gc::MallocedBlockCache mallocedBlockCache_;
780
781 // Whether the previous collection tenured everything. This may be false if
782 // semispace is in use.
783 bool tenuredEverything;
784
785 friend class gc::GCRuntime;
786 friend class gc::TenuringTracer;
787 friend struct NurseryChunk;
788 };
789
790 MOZ_ALWAYS_INLINE bool Nursery::isInside(const void* p) const {
791 // TODO: Split this into separate methods.
792 // TODO: Do we ever need to check both?
793 return toSpace.isInside(p) || fromSpace.isInside(p);
794 }
795
796 MOZ_ALWAYS_INLINE bool Nursery::Space::isInside(const void* p) const {
797 for (auto* chunk : chunks_) {
798 if (uintptr_t(p) - uintptr_t(chunk) < gc::ChunkSize) {
799 return true;
800 }
801 }
802 return false;
803 }
804
805 } // namespace js
806
807 #endif // gc_Nursery_h