1 // Copyright 2011 the V8 project authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #ifndef V8_HEAP_SPACES_H_
6 #define V8_HEAP_SPACES_H_
8 #include "src/allocation.h"
9 #include "src/base/atomicops.h"
10 #include "src/base/bits.h"
11 #include "src/base/platform/mutex.h"
12 #include "src/hashmap.h"
15 #include "src/utils.h"
22 // -----------------------------------------------------------------------------
25 // A JS heap consists of a young generation, an old generation, and a large
26 // object space. The young generation is divided into two semispaces. A
27 // scavenger implements Cheney's copying algorithm. The old generation is
28 // separated into a map space and an old object space. The map space contains
29 // all (and only) map objects, the rest of old objects go into the old space.
30 // The old generation is collected by a mark-sweep-compact collector.
32 // The semispaces of the young generation are contiguous. The old and map
33 // spaces consists of a list of pages. A page has a page header and an object
36 // There is a separate large object space for objects larger than
37 // Page::kMaxHeapObjectSize, so that they do not have to move during
38 // collection. The large object space is paged. Pages in large object space
39 // may be larger than the page size.
41 // A store-buffer based write barrier is used to keep track of intergenerational
42 // references. See heap/store-buffer.h.
44 // During scavenges and mark-sweep collections we sometimes (after a store
45 // buffer overflow) iterate intergenerational pointers without decoding heap
46 // object maps so if the page belongs to old pointer space or large object
47 // space it is essential to guarantee that the page does not contain any
48 // garbage pointers to new space: every pointer aligned word which satisfies
49 // the Heap::InNewSpace() predicate must be a pointer to a live heap object in
50 // new space. Thus objects in old pointer and large object spaces should have a
51 // special layout (e.g. no bare integer fields). This requirement does not
52 // apply to map space which is iterated in a special fashion. However we still
53 // require pointer fields of dead maps to be cleaned.
55 // To enable lazy cleaning of old space pages we can mark chunks of the page
56 // as being garbage. Garbage sections are marked with a special map. These
57 // sections are skipped when scanning the page, even if we are otherwise
58 // scanning without regard for object boundaries. Garbage sections are chained
59 // together to form a free list after a GC. Garbage sections created outside
60 // of GCs by object trunctation etc. may not be in the free list chain. Very
61 // small free spaces are ignored, they need only be cleaned of bogus pointers
64 // Each page may have up to one special garbage section. The start of this
65 // section is denoted by the top field in the space. The end of the section
66 // is denoted by the limit field in the space. This special garbage section
67 // is not marked with a free space map in the data. The point of this section
68 // is to enable linear allocation without having to constantly update the byte
69 // array every time the top field is updated and a new object is created. The
70 // special garbage section is not in the chain of garbage sections.
72 // Since the top and limit fields are in the space, not the page, only one page
73 // has a special garbage section, and if the top and limit are equal then there
74 // is no special garbage section.
76 // Some assertion macros used in the debugging mode.
78 #define DCHECK_PAGE_ALIGNED(address) \
79 DCHECK((OffsetFrom(address) & Page::kPageAlignmentMask) == 0)
81 #define DCHECK_OBJECT_ALIGNED(address) \
82 DCHECK((OffsetFrom(address) & kObjectAlignmentMask) == 0)
84 #define DCHECK_OBJECT_SIZE(size) \
85 DCHECK((0 < size) && (size <= Page::kMaxRegularHeapObjectSize))
87 #define DCHECK_PAGE_OFFSET(offset) \
88 DCHECK((Page::kObjectStartOffset <= offset) && (offset <= Page::kPageSize))
90 #define DCHECK_MAP_PAGE_INDEX(index) \
91 DCHECK((0 <= index) && (index <= MapSpace::kMaxMapPageIndex))
95 class MemoryAllocator;
103 typedef uint32_t CellType;
105 inline MarkBit(CellType* cell, CellType mask, bool data_only)
106 : cell_(cell), mask_(mask), data_only_(data_only) {}
108 inline CellType* cell() { return cell_; }
109 inline CellType mask() { return mask_; }
112 bool operator==(const MarkBit& other) {
113 return cell_ == other.cell_ && mask_ == other.mask_;
117 inline void Set() { *cell_ |= mask_; }
118 inline bool Get() { return (*cell_ & mask_) != 0; }
119 inline void Clear() { *cell_ &= ~mask_; }
121 inline bool data_only() { return data_only_; }
123 inline MarkBit Next() {
124 CellType new_mask = mask_ << 1;
126 return MarkBit(cell_ + 1, 1, data_only_);
128 return MarkBit(cell_, new_mask, data_only_);
135 // This boolean indicates that the object is in a data-only space with no
136 // pointers. This enables some optimizations when marking.
137 // It is expected that this field is inlined and turned into control flow
138 // at the place where the MarkBit object is created.
143 // Bitmap is a sequence of cells each containing fixed number of bits.
146 static const uint32_t kBitsPerCell = 32;
147 static const uint32_t kBitsPerCellLog2 = 5;
148 static const uint32_t kBitIndexMask = kBitsPerCell - 1;
149 static const uint32_t kBytesPerCell = kBitsPerCell / kBitsPerByte;
150 static const uint32_t kBytesPerCellLog2 = kBitsPerCellLog2 - kBitsPerByteLog2;
152 static const size_t kLength = (1 << kPageSizeBits) >> (kPointerSizeLog2);
154 static const size_t kSize =
155 (1 << kPageSizeBits) >> (kPointerSizeLog2 + kBitsPerByteLog2);
158 static int CellsForLength(int length) {
159 return (length + kBitsPerCell - 1) >> kBitsPerCellLog2;
162 int CellsCount() { return CellsForLength(kLength); }
164 static int SizeFor(int cells_count) {
165 return sizeof(MarkBit::CellType) * cells_count;
168 INLINE(static uint32_t IndexToCell(uint32_t index)) {
169 return index >> kBitsPerCellLog2;
172 INLINE(static uint32_t CellToIndex(uint32_t index)) {
173 return index << kBitsPerCellLog2;
176 INLINE(static uint32_t CellAlignIndex(uint32_t index)) {
177 return (index + kBitIndexMask) & ~kBitIndexMask;
180 INLINE(MarkBit::CellType* cells()) {
181 return reinterpret_cast<MarkBit::CellType*>(this);
184 INLINE(Address address()) { return reinterpret_cast<Address>(this); }
186 INLINE(static Bitmap* FromAddress(Address addr)) {
187 return reinterpret_cast<Bitmap*>(addr);
190 inline MarkBit MarkBitFromIndex(uint32_t index, bool data_only = false) {
191 MarkBit::CellType mask = 1 << (index & kBitIndexMask);
192 MarkBit::CellType* cell = this->cells() + (index >> kBitsPerCellLog2);
193 return MarkBit(cell, mask, data_only);
196 static inline void Clear(MemoryChunk* chunk);
198 static void PrintWord(uint32_t word, uint32_t himask = 0) {
199 for (uint32_t mask = 1; mask != 0; mask <<= 1) {
200 if ((mask & himask) != 0) PrintF("[");
201 PrintF((mask & word) ? "1" : "0");
202 if ((mask & himask) != 0) PrintF("]");
208 CellPrinter() : seq_start(0), seq_type(0), seq_length(0) {}
210 void Print(uint32_t pos, uint32_t cell) {
211 if (cell == seq_type) {
231 if (seq_length > 0) {
232 PrintF("%d: %dx%d\n", seq_start, seq_type == 0 ? 0 : 1,
233 seq_length * kBitsPerCell);
238 static bool IsSeq(uint32_t cell) { return cell == 0 || cell == 0xFFFFFFFF; }
248 for (int i = 0; i < CellsCount(); i++) {
249 printer.Print(i, cells()[i]);
256 for (int i = 0; i < CellsCount(); i++) {
257 if (cells()[i] != 0) {
269 // MemoryChunk represents a memory region owned by a specific space.
270 // It is divided into the header and the body. Chunk start is always
271 // 1MB aligned. Start of the body is aligned so it can accommodate
275 // Only works if the pointer is in the first kPageSize of the MemoryChunk.
276 static MemoryChunk* FromAddress(Address a) {
277 return reinterpret_cast<MemoryChunk*>(OffsetFrom(a) & ~kAlignmentMask);
279 static const MemoryChunk* FromAddress(const byte* a) {
280 return reinterpret_cast<const MemoryChunk*>(OffsetFrom(a) &
284 // Only works for addresses in pointer spaces, not data or code spaces.
285 static inline MemoryChunk* FromAnyPointerAddress(Heap* heap, Address addr);
287 Address address() { return reinterpret_cast<Address>(this); }
289 bool is_valid() { return address() != NULL; }
291 MemoryChunk* next_chunk() const {
292 return reinterpret_cast<MemoryChunk*>(base::Acquire_Load(&next_chunk_));
295 MemoryChunk* prev_chunk() const {
296 return reinterpret_cast<MemoryChunk*>(base::Acquire_Load(&prev_chunk_));
299 void set_next_chunk(MemoryChunk* next) {
300 base::Release_Store(&next_chunk_, reinterpret_cast<base::AtomicWord>(next));
303 void set_prev_chunk(MemoryChunk* prev) {
304 base::Release_Store(&prev_chunk_, reinterpret_cast<base::AtomicWord>(prev));
307 Space* owner() const {
308 if ((reinterpret_cast<intptr_t>(owner_) & kPageHeaderTagMask) ==
310 return reinterpret_cast<Space*>(reinterpret_cast<intptr_t>(owner_) -
317 void set_owner(Space* space) {
318 DCHECK((reinterpret_cast<intptr_t>(space) & kPageHeaderTagMask) == 0);
319 owner_ = reinterpret_cast<Address>(space) + kPageHeaderTag;
320 DCHECK((reinterpret_cast<intptr_t>(owner_) & kPageHeaderTagMask) ==
324 base::VirtualMemory* reserved_memory() { return &reservation_; }
326 void InitializeReservedMemory() { reservation_.Reset(); }
328 void set_reserved_memory(base::VirtualMemory* reservation) {
329 DCHECK_NOT_NULL(reservation);
330 reservation_.TakeControl(reservation);
333 bool scan_on_scavenge() { return IsFlagSet(SCAN_ON_SCAVENGE); }
334 void initialize_scan_on_scavenge(bool scan) {
336 SetFlag(SCAN_ON_SCAVENGE);
338 ClearFlag(SCAN_ON_SCAVENGE);
341 inline void set_scan_on_scavenge(bool scan);
343 int store_buffer_counter() { return store_buffer_counter_; }
344 void set_store_buffer_counter(int counter) {
345 store_buffer_counter_ = counter;
348 bool Contains(Address addr) {
349 return addr >= area_start() && addr < area_end();
352 // Checks whether addr can be a limit of addresses in this page.
353 // It's a limit if it's in the page, or if it's just after the
354 // last byte of the page.
355 bool ContainsLimit(Address addr) {
356 return addr >= area_start() && addr <= area_end();
359 // Every n write barrier invocations we go to runtime even though
360 // we could have handled it in generated code. This lets us check
361 // whether we have hit the limit and should do some more marking.
362 static const int kWriteBarrierCounterGranularity = 500;
364 enum MemoryChunkFlags {
367 POINTERS_TO_HERE_ARE_INTERESTING,
368 POINTERS_FROM_HERE_ARE_INTERESTING,
370 IN_FROM_SPACE, // Mutually exclusive with IN_TO_SPACE.
371 IN_TO_SPACE, // All pages in new space has one of these two set.
372 NEW_SPACE_BELOW_AGE_MARK,
374 EVACUATION_CANDIDATE,
375 RESCAN_ON_EVACUATION,
376 NEVER_EVACUATE, // May contain immortal immutables.
378 // WAS_SWEPT indicates that marking bits have been cleared by the sweeper,
379 // otherwise marking bits are still intact.
382 // Large objects can have a progress bar in their page header. These object
383 // are scanned in increments and will be kept black while being scanned.
384 // Even if the mutator writes to them they will be kept black and a white
385 // to grey transition is performed in the value.
388 // This flag is intended to be used for testing. Works only when both
389 // FLAG_stress_compaction and FLAG_manual_evacuation_candidates_selection
390 // are set. It forces the page to become an evacuation candidate at next
391 // candidates selection cycle.
392 FORCE_EVACUATION_CANDIDATE_FOR_TESTING,
394 // Last flag, keep at bottom.
395 NUM_MEMORY_CHUNK_FLAGS
399 static const int kPointersToHereAreInterestingMask =
400 1 << POINTERS_TO_HERE_ARE_INTERESTING;
402 static const int kPointersFromHereAreInterestingMask =
403 1 << POINTERS_FROM_HERE_ARE_INTERESTING;
405 static const int kEvacuationCandidateMask = 1 << EVACUATION_CANDIDATE;
407 static const int kSkipEvacuationSlotsRecordingMask =
408 (1 << EVACUATION_CANDIDATE) | (1 << RESCAN_ON_EVACUATION) |
409 (1 << IN_FROM_SPACE) | (1 << IN_TO_SPACE);
412 void SetFlag(int flag) { flags_ |= static_cast<uintptr_t>(1) << flag; }
414 void ClearFlag(int flag) { flags_ &= ~(static_cast<uintptr_t>(1) << flag); }
416 void SetFlagTo(int flag, bool value) {
424 bool IsFlagSet(int flag) {
425 return (flags_ & (static_cast<uintptr_t>(1) << flag)) != 0;
428 // Set or clear multiple flags at a time. The flags in the mask
429 // are set to the value in "flags", the rest retain the current value
431 void SetFlags(intptr_t flags, intptr_t mask) {
432 flags_ = (flags_ & ~mask) | (flags & mask);
435 // Return all current flags.
436 intptr_t GetFlags() { return flags_; }
439 // SWEEPING_DONE - The page state when sweeping is complete or sweeping must
440 // not be performed on that page.
441 // SWEEPING_FINALIZE - A sweeper thread is done sweeping this page and will
442 // not touch the page memory anymore.
443 // SWEEPING_IN_PROGRESS - This page is currently swept by a sweeper thread.
444 // SWEEPING_PENDING - This page is ready for parallel sweeping.
445 enum ParallelSweepingState {
448 SWEEPING_IN_PROGRESS,
452 ParallelSweepingState parallel_sweeping() {
453 return static_cast<ParallelSweepingState>(
454 base::Acquire_Load(¶llel_sweeping_));
457 void set_parallel_sweeping(ParallelSweepingState state) {
458 base::Release_Store(¶llel_sweeping_, state);
461 bool TryParallelSweeping() {
462 return base::Acquire_CompareAndSwap(¶llel_sweeping_, SWEEPING_PENDING,
463 SWEEPING_IN_PROGRESS) ==
467 bool SweepingCompleted() { return parallel_sweeping() <= SWEEPING_FINALIZE; }
469 // Manage live byte count (count of bytes known to be live,
470 // because they are marked black).
471 void ResetLiveBytes() {
472 if (FLAG_gc_verbose) {
473 PrintF("ResetLiveBytes:%p:%x->0\n", static_cast<void*>(this),
476 live_byte_count_ = 0;
478 void IncrementLiveBytes(int by) {
479 if (FLAG_gc_verbose) {
480 printf("UpdateLiveBytes:%p:%x%c=%x->%x\n", static_cast<void*>(this),
481 live_byte_count_, ((by < 0) ? '-' : '+'), ((by < 0) ? -by : by),
482 live_byte_count_ + by);
484 live_byte_count_ += by;
485 DCHECK_LE(static_cast<unsigned>(live_byte_count_), size_);
488 DCHECK(static_cast<unsigned>(live_byte_count_) <= size_);
489 return live_byte_count_;
492 int write_barrier_counter() {
493 return static_cast<int>(write_barrier_counter_);
496 void set_write_barrier_counter(int counter) {
497 write_barrier_counter_ = counter;
501 DCHECK(IsFlagSet(HAS_PROGRESS_BAR));
502 return progress_bar_;
505 void set_progress_bar(int progress_bar) {
506 DCHECK(IsFlagSet(HAS_PROGRESS_BAR));
507 progress_bar_ = progress_bar;
510 void ResetProgressBar() {
511 if (IsFlagSet(MemoryChunk::HAS_PROGRESS_BAR)) {
513 ClearFlag(MemoryChunk::HAS_PROGRESS_BAR);
517 bool IsLeftOfProgressBar(Object** slot) {
518 Address slot_address = reinterpret_cast<Address>(slot);
519 DCHECK(slot_address > this->address());
520 return (slot_address - (this->address() + kObjectStartOffset)) <
524 static void IncrementLiveBytesFromGC(Address address, int by) {
525 MemoryChunk::FromAddress(address)->IncrementLiveBytes(by);
528 static void IncrementLiveBytesFromMutator(Address address, int by);
530 static const intptr_t kAlignment =
531 (static_cast<uintptr_t>(1) << kPageSizeBits);
533 static const intptr_t kAlignmentMask = kAlignment - 1;
535 static const intptr_t kSizeOffset = 0;
537 static const intptr_t kLiveBytesOffset =
538 kSizeOffset + kPointerSize + kPointerSize + kPointerSize + kPointerSize +
539 kPointerSize + kPointerSize + kPointerSize + kPointerSize + kIntSize;
541 static const size_t kSlotsBufferOffset = kLiveBytesOffset + kIntSize;
543 static const size_t kWriteBarrierCounterOffset =
544 kSlotsBufferOffset + kPointerSize + kPointerSize;
546 static const size_t kHeaderSize =
547 kWriteBarrierCounterOffset + kPointerSize + kIntSize + kIntSize +
548 kPointerSize + 5 * kPointerSize + kPointerSize + kPointerSize;
550 static const int kBodyOffset =
551 CODE_POINTER_ALIGN(kHeaderSize + Bitmap::kSize);
553 // The start offset of the object area in a page. Aligned to both maps and
554 // code alignment to be suitable for both. Also aligned to 32 words because
555 // the marking bitmap is arranged in 32 bit chunks.
556 static const int kObjectStartAlignment = 32 * kPointerSize;
557 static const int kObjectStartOffset =
559 (kObjectStartAlignment - (kBodyOffset - 1) % kObjectStartAlignment);
561 size_t size() const { return size_; }
563 void set_size(size_t size) { size_ = size; }
565 void SetArea(Address area_start, Address area_end) {
566 area_start_ = area_start;
567 area_end_ = area_end;
570 Executability executable() {
571 return IsFlagSet(IS_EXECUTABLE) ? EXECUTABLE : NOT_EXECUTABLE;
574 bool ContainsOnlyData() { return IsFlagSet(CONTAINS_ONLY_DATA); }
577 return (flags_ & ((1 << IN_FROM_SPACE) | (1 << IN_TO_SPACE))) != 0;
580 bool InToSpace() { return IsFlagSet(IN_TO_SPACE); }
582 bool InFromSpace() { return IsFlagSet(IN_FROM_SPACE); }
584 // ---------------------------------------------------------------------
587 inline Bitmap* markbits() {
588 return Bitmap::FromAddress(address() + kHeaderSize);
591 void PrintMarkbits() { markbits()->Print(); }
593 inline uint32_t AddressToMarkbitIndex(Address addr) {
594 return static_cast<uint32_t>(addr - this->address()) >> kPointerSizeLog2;
597 inline static uint32_t FastAddressToMarkbitIndex(Address addr) {
598 const intptr_t offset = reinterpret_cast<intptr_t>(addr) & kAlignmentMask;
600 return static_cast<uint32_t>(offset) >> kPointerSizeLog2;
603 inline Address MarkbitIndexToAddress(uint32_t index) {
604 return this->address() + (index << kPointerSizeLog2);
607 void InsertAfter(MemoryChunk* other);
610 inline Heap* heap() const { return heap_; }
612 static const int kFlagsOffset = kPointerSize;
614 bool NeverEvacuate() { return IsFlagSet(NEVER_EVACUATE); }
616 void MarkNeverEvacuate() { SetFlag(NEVER_EVACUATE); }
618 bool IsEvacuationCandidate() {
619 DCHECK(!(IsFlagSet(NEVER_EVACUATE) && IsFlagSet(EVACUATION_CANDIDATE)));
620 return IsFlagSet(EVACUATION_CANDIDATE);
623 bool ShouldSkipEvacuationSlotRecording() {
624 return (flags_ & kSkipEvacuationSlotsRecordingMask) != 0;
627 inline SkipList* skip_list() { return skip_list_; }
629 inline void set_skip_list(SkipList* skip_list) { skip_list_ = skip_list; }
631 inline SlotsBuffer* slots_buffer() { return slots_buffer_; }
633 inline SlotsBuffer** slots_buffer_address() { return &slots_buffer_; }
635 void MarkEvacuationCandidate() {
636 DCHECK(!IsFlagSet(NEVER_EVACUATE));
637 DCHECK(slots_buffer_ == NULL);
638 SetFlag(EVACUATION_CANDIDATE);
641 void ClearEvacuationCandidate() {
642 DCHECK(slots_buffer_ == NULL);
643 ClearFlag(EVACUATION_CANDIDATE);
646 Address area_start() { return area_start_; }
647 Address area_end() { return area_end_; }
648 int area_size() { return static_cast<int>(area_end() - area_start()); }
649 bool CommitArea(size_t requested);
651 // Approximate amount of physical memory committed for this chunk.
652 size_t CommittedPhysicalMemory() { return high_water_mark_; }
654 static inline void UpdateHighWaterMark(Address mark);
660 // Start and end of allocatable memory on this chunk.
664 // If the chunk needs to remember its memory reservation, it is stored here.
665 base::VirtualMemory reservation_;
666 // The identity of the owning space. This is tagged as a failure pointer, but
667 // no failure can be in an object, so this can be distinguished from any entry
671 // Used by the store buffer to keep track of which pages to mark scan-on-
673 int store_buffer_counter_;
674 // Count of bytes marked black on page.
675 int live_byte_count_;
676 SlotsBuffer* slots_buffer_;
677 SkipList* skip_list_;
678 intptr_t write_barrier_counter_;
679 // Used by the incremental marker to keep track of the scanning progress in
680 // large objects that have a progress bar and are scanned in increments.
682 // Assuming the initial allocation on a page is sequential,
683 // count highest number of bytes ever allocated on the page.
684 int high_water_mark_;
686 base::AtomicWord parallel_sweeping_;
688 // PagedSpace free-list statistics.
689 intptr_t available_in_small_free_list_;
690 intptr_t available_in_medium_free_list_;
691 intptr_t available_in_large_free_list_;
692 intptr_t available_in_huge_free_list_;
693 intptr_t non_available_small_blocks_;
695 static MemoryChunk* Initialize(Heap* heap, Address base, size_t size,
696 Address area_start, Address area_end,
697 Executability executable, Space* owner);
700 // next_chunk_ holds a pointer of type MemoryChunk
701 base::AtomicWord next_chunk_;
702 // prev_chunk_ holds a pointer of type MemoryChunk
703 base::AtomicWord prev_chunk_;
705 friend class MemoryAllocator;
709 STATIC_ASSERT(sizeof(MemoryChunk) <= MemoryChunk::kHeaderSize);
712 // -----------------------------------------------------------------------------
713 // A page is a memory chunk of a size 1MB. Large object pages may be larger.
715 // The only way to get a page pointer is by calling factory methods:
716 // Page* p = Page::FromAddress(addr); or
717 // Page* p = Page::FromAllocationTop(top);
718 class Page : public MemoryChunk {
720 // Returns the page containing a given address. The address ranges
721 // from [page_addr .. page_addr + kPageSize[
722 // This only works if the object is in fact in a page. See also MemoryChunk::
723 // FromAddress() and FromAnyAddress().
724 INLINE(static Page* FromAddress(Address a)) {
725 return reinterpret_cast<Page*>(OffsetFrom(a) & ~kPageAlignmentMask);
728 // Returns the page containing an allocation top. Because an allocation
729 // top address can be the upper bound of the page, we need to subtract
730 // it with kPointerSize first. The address ranges from
731 // [page_addr + kObjectStartOffset .. page_addr + kPageSize].
732 INLINE(static Page* FromAllocationTop(Address top)) {
733 Page* p = FromAddress(top - kPointerSize);
737 // Returns the next page in the chain of pages owned by a space.
738 inline Page* next_page();
739 inline Page* prev_page();
740 inline void set_next_page(Page* page);
741 inline void set_prev_page(Page* page);
743 // Checks whether an address is page aligned.
744 static bool IsAlignedToPageSize(Address a) {
745 return 0 == (OffsetFrom(a) & kPageAlignmentMask);
748 // Returns the offset of a given address to this page.
749 INLINE(int Offset(Address a)) {
750 int offset = static_cast<int>(a - address());
754 // Returns the address for a given offset to the this page.
755 Address OffsetToAddress(int offset) {
756 DCHECK_PAGE_OFFSET(offset);
757 return address() + offset;
760 // ---------------------------------------------------------------------
762 // Page size in bytes. This must be a multiple of the OS page size.
763 static const int kPageSize = 1 << kPageSizeBits;
765 // Maximum object size that fits in a page. Objects larger than that size
766 // are allocated in large object space and are never moved in memory. This
767 // also applies to new space allocation, since objects are never migrated
768 // from new space to large object space. Takes double alignment into account.
769 static const int kMaxRegularHeapObjectSize = kPageSize - kObjectStartOffset;
772 static const intptr_t kPageAlignmentMask = (1 << kPageSizeBits) - 1;
774 inline void ClearGCFields();
776 static inline Page* Initialize(Heap* heap, MemoryChunk* chunk,
777 Executability executable, PagedSpace* owner);
779 void InitializeAsAnchor(PagedSpace* owner);
781 bool WasSwept() { return IsFlagSet(WAS_SWEPT); }
782 void SetWasSwept() { SetFlag(WAS_SWEPT); }
783 void ClearWasSwept() { ClearFlag(WAS_SWEPT); }
785 void ResetFreeListStatistics();
787 #define FRAGMENTATION_STATS_ACCESSORS(type, name) \
788 type name() { return name##_; } \
789 void set_##name(type name) { name##_ = name; } \
790 void add_##name(type name) { name##_ += name; }
792 FRAGMENTATION_STATS_ACCESSORS(intptr_t, non_available_small_blocks)
793 FRAGMENTATION_STATS_ACCESSORS(intptr_t, available_in_small_free_list)
794 FRAGMENTATION_STATS_ACCESSORS(intptr_t, available_in_medium_free_list)
795 FRAGMENTATION_STATS_ACCESSORS(intptr_t, available_in_large_free_list)
796 FRAGMENTATION_STATS_ACCESSORS(intptr_t, available_in_huge_free_list)
798 #undef FRAGMENTATION_STATS_ACCESSORS
804 friend class MemoryAllocator;
808 STATIC_ASSERT(sizeof(Page) <= MemoryChunk::kHeaderSize);
811 class LargePage : public MemoryChunk {
813 HeapObject* GetObject() { return HeapObject::FromAddress(area_start()); }
815 inline LargePage* next_page() const {
816 return static_cast<LargePage*>(next_chunk());
819 inline void set_next_page(LargePage* page) { set_next_chunk(page); }
822 static inline LargePage* Initialize(Heap* heap, MemoryChunk* chunk);
824 friend class MemoryAllocator;
827 STATIC_ASSERT(sizeof(LargePage) <= MemoryChunk::kHeaderSize);
829 // ----------------------------------------------------------------------------
830 // Space is the abstract superclass for all allocation spaces.
831 class Space : public Malloced {
833 Space(Heap* heap, AllocationSpace id, Executability executable)
834 : heap_(heap), id_(id), executable_(executable) {}
838 Heap* heap() const { return heap_; }
840 // Does the space need executable memory?
841 Executability executable() { return executable_; }
843 // Identity used in error reporting.
844 AllocationSpace identity() { return id_; }
846 // Returns allocated size.
847 virtual intptr_t Size() = 0;
849 // Returns size of objects. Can differ from the allocated size
850 // (e.g. see LargeObjectSpace).
851 virtual intptr_t SizeOfObjects() { return Size(); }
853 virtual int RoundSizeDownToObjectAlignment(int size) {
854 if (id_ == CODE_SPACE) {
855 return RoundDown(size, kCodeAlignment);
857 return RoundDown(size, kPointerSize);
862 virtual void Print() = 0;
868 Executability executable_;
872 // ----------------------------------------------------------------------------
873 // All heap objects containing executable code (code objects) must be allocated
874 // from a 2 GB range of memory, so that they can call each other using 32-bit
875 // displacements. This happens automatically on 32-bit platforms, where 32-bit
876 // displacements cover the entire 4GB virtual address space. On 64-bit
877 // platforms, we support this using the CodeRange object, which reserves and
878 // manages a range of virtual memory.
881 explicit CodeRange(Isolate* isolate);
882 ~CodeRange() { TearDown(); }
884 // Reserves a range of virtual memory, but does not commit any of it.
885 // Can only be called once, at heap initialization time.
886 // Returns false on failure.
887 bool SetUp(size_t requested_size);
889 // Frees the range of virtual memory, and frees the data structures used to
893 bool valid() { return code_range_ != NULL; }
896 return static_cast<Address>(code_range_->address());
900 return code_range_->size();
902 bool contains(Address address) {
903 if (!valid()) return false;
904 Address start = static_cast<Address>(code_range_->address());
905 return start <= address && address < start + code_range_->size();
908 // Allocates a chunk of memory from the large-object portion of
909 // the code range. On platforms with no separate code range, should
911 MUST_USE_RESULT Address AllocateRawMemory(const size_t requested_size,
912 const size_t commit_size,
914 bool CommitRawMemory(Address start, size_t length);
915 bool UncommitRawMemory(Address start, size_t length);
916 void FreeRawMemory(Address buf, size_t length);
918 void ReserveEmergencyBlock();
919 void ReleaseEmergencyBlock();
924 // The reserved range of virtual memory that all code objects are put in.
925 base::VirtualMemory* code_range_;
926 // Plain old data class, just a struct plus a constructor.
929 FreeBlock() : start(0), size(0) {}
930 FreeBlock(Address start_arg, size_t size_arg)
931 : start(start_arg), size(size_arg) {
932 DCHECK(IsAddressAligned(start, MemoryChunk::kAlignment));
933 DCHECK(size >= static_cast<size_t>(Page::kPageSize));
935 FreeBlock(void* start_arg, size_t size_arg)
936 : start(static_cast<Address>(start_arg)), size(size_arg) {
937 DCHECK(IsAddressAligned(start, MemoryChunk::kAlignment));
938 DCHECK(size >= static_cast<size_t>(Page::kPageSize));
945 // Freed blocks of memory are added to the free list. When the allocation
946 // list is exhausted, the free list is sorted and merged to make the new
948 List<FreeBlock> free_list_;
949 // Memory is allocated from the free blocks on the allocation list.
950 // The block at current_allocation_block_index_ is the current block.
951 List<FreeBlock> allocation_list_;
952 int current_allocation_block_index_;
954 // Emergency block guarantees that we can always allocate a page for
955 // evacuation candidates when code space is compacted. Emergency block is
956 // reserved immediately after GC and is released immedietely before
957 // allocating a page for evacuation.
958 FreeBlock emergency_block_;
960 // Finds a block on the allocation list that contains at least the
961 // requested amount of memory. If none is found, sorts and merges
962 // the existing free memory blocks, and searches again.
963 // If none can be found, returns false.
964 bool GetNextAllocationBlock(size_t requested);
965 // Compares the start addresses of two free blocks.
966 static int CompareFreeBlockAddress(const FreeBlock* left,
967 const FreeBlock* right);
968 bool ReserveBlock(const size_t requested_size, FreeBlock* block);
969 void ReleaseBlock(const FreeBlock* block);
971 DISALLOW_COPY_AND_ASSIGN(CodeRange);
977 SkipList() { Clear(); }
980 for (int idx = 0; idx < kSize; idx++) {
981 starts_[idx] = reinterpret_cast<Address>(-1);
985 Address StartFor(Address addr) { return starts_[RegionNumber(addr)]; }
987 void AddObject(Address addr, int size) {
988 int start_region = RegionNumber(addr);
989 int end_region = RegionNumber(addr + size - kPointerSize);
990 for (int idx = start_region; idx <= end_region; idx++) {
991 if (starts_[idx] > addr) starts_[idx] = addr;
995 static inline int RegionNumber(Address addr) {
996 return (OffsetFrom(addr) & Page::kPageAlignmentMask) >> kRegionSizeLog2;
999 static void Update(Address addr, int size) {
1000 Page* page = Page::FromAddress(addr);
1001 SkipList* list = page->skip_list();
1003 list = new SkipList();
1004 page->set_skip_list(list);
1007 list->AddObject(addr, size);
1011 static const int kRegionSizeLog2 = 13;
1012 static const int kRegionSize = 1 << kRegionSizeLog2;
1013 static const int kSize = Page::kPageSize / kRegionSize;
1015 STATIC_ASSERT(Page::kPageSize % kRegionSize == 0);
1017 Address starts_[kSize];
1021 // ----------------------------------------------------------------------------
1022 // A space acquires chunks of memory from the operating system. The memory
1023 // allocator allocated and deallocates pages for the paged heap spaces and large
1024 // pages for large object space.
1026 // Each space has to manage it's own pages.
1028 class MemoryAllocator {
1030 explicit MemoryAllocator(Isolate* isolate);
1032 // Initializes its internal bookkeeping structures.
1033 // Max capacity of the total space and executable memory limit.
1034 bool SetUp(intptr_t max_capacity, intptr_t capacity_executable);
1038 Page* AllocatePage(intptr_t size, PagedSpace* owner,
1039 Executability executable);
1041 LargePage* AllocateLargePage(intptr_t object_size, Space* owner,
1042 Executability executable);
1044 void Free(MemoryChunk* chunk);
1046 // Returns the maximum available bytes of heaps.
1047 intptr_t Available() { return capacity_ < size_ ? 0 : capacity_ - size_; }
1049 // Returns allocated spaces in bytes.
1050 intptr_t Size() { return size_; }
1052 // Returns the maximum available executable bytes of heaps.
1053 intptr_t AvailableExecutable() {
1054 if (capacity_executable_ < size_executable_) return 0;
1055 return capacity_executable_ - size_executable_;
1058 // Returns allocated executable spaces in bytes.
1059 intptr_t SizeExecutable() { return size_executable_; }
1061 // Returns maximum available bytes that the old space can have.
1062 intptr_t MaxAvailable() {
1063 return (Available() / Page::kPageSize) * Page::kMaxRegularHeapObjectSize;
1066 // Returns an indication of whether a pointer is in a space that has
1067 // been allocated by this MemoryAllocator.
1068 V8_INLINE bool IsOutsideAllocatedSpace(const void* address) const {
1069 return address < lowest_ever_allocated_ ||
1070 address >= highest_ever_allocated_;
1074 // Reports statistic info of the space.
1075 void ReportStatistics();
1078 // Returns a MemoryChunk in which the memory region from commit_area_size to
1079 // reserve_area_size of the chunk area is reserved but not committed, it
1080 // could be committed later by calling MemoryChunk::CommitArea.
1081 MemoryChunk* AllocateChunk(intptr_t reserve_area_size,
1082 intptr_t commit_area_size,
1083 Executability executable, Space* space);
1085 Address ReserveAlignedMemory(size_t requested, size_t alignment,
1086 base::VirtualMemory* controller);
1087 Address AllocateAlignedMemory(size_t reserve_size, size_t commit_size,
1088 size_t alignment, Executability executable,
1089 base::VirtualMemory* controller);
1091 bool CommitMemory(Address addr, size_t size, Executability executable);
1093 void FreeMemory(base::VirtualMemory* reservation, Executability executable);
1094 void FreeMemory(Address addr, size_t size, Executability executable);
1096 // Commit a contiguous block of memory from the initial chunk. Assumes that
1097 // the address is not NULL, the size is greater than zero, and that the
1098 // block is contained in the initial chunk. Returns true if it succeeded
1099 // and false otherwise.
1100 bool CommitBlock(Address start, size_t size, Executability executable);
1102 // Uncommit a contiguous block of memory [start..(start+size)[.
1103 // start is not NULL, the size is greater than zero, and the
1104 // block is contained in the initial chunk. Returns true if it succeeded
1105 // and false otherwise.
1106 bool UncommitBlock(Address start, size_t size);
1108 // Zaps a contiguous block of memory [start..(start+size)[ thus
1109 // filling it up with a recognizable non-NULL bit pattern.
1110 void ZapBlock(Address start, size_t size);
1112 void PerformAllocationCallback(ObjectSpace space, AllocationAction action,
1115 void AddMemoryAllocationCallback(MemoryAllocationCallback callback,
1116 ObjectSpace space, AllocationAction action);
1118 void RemoveMemoryAllocationCallback(MemoryAllocationCallback callback);
1120 bool MemoryAllocationCallbackRegistered(MemoryAllocationCallback callback);
1122 static int CodePageGuardStartOffset();
1124 static int CodePageGuardSize();
1126 static int CodePageAreaStartOffset();
1128 static int CodePageAreaEndOffset();
1130 static int CodePageAreaSize() {
1131 return CodePageAreaEndOffset() - CodePageAreaStartOffset();
1134 static int PageAreaSize(AllocationSpace space) {
1135 DCHECK_NE(LO_SPACE, space);
1136 return (space == CODE_SPACE) ? CodePageAreaSize()
1137 : Page::kMaxRegularHeapObjectSize;
1140 MUST_USE_RESULT bool CommitExecutableMemory(base::VirtualMemory* vm,
1141 Address start, size_t commit_size,
1142 size_t reserved_size);
1147 // Maximum space size in bytes.
1149 // Maximum subset of capacity_ that can be executable
1150 size_t capacity_executable_;
1152 // Allocated space size in bytes.
1154 // Allocated executable space size in bytes.
1155 size_t size_executable_;
1157 // We keep the lowest and highest addresses allocated as a quick way
1158 // of determining that pointers are outside the heap. The estimate is
1159 // conservative, i.e. not all addrsses in 'allocated' space are allocated
1160 // to our heap. The range is [lowest, highest[, inclusive on the low end
1161 // and exclusive on the high end.
1162 void* lowest_ever_allocated_;
1163 void* highest_ever_allocated_;
1165 struct MemoryAllocationCallbackRegistration {
1166 MemoryAllocationCallbackRegistration(MemoryAllocationCallback callback,
1168 AllocationAction action)
1169 : callback(callback), space(space), action(action) {}
1170 MemoryAllocationCallback callback;
1172 AllocationAction action;
1175 // A List of callback that are triggered when memory is allocated or free'd
1176 List<MemoryAllocationCallbackRegistration> memory_allocation_callbacks_;
1178 // Initializes pages in a chunk. Returns the first page address.
1179 // This function and GetChunkId() are provided for the mark-compact
1180 // collector to rebuild page headers in the from space, which is
1181 // used as a marking stack and its page headers are destroyed.
1182 Page* InitializePagesInChunk(int chunk_id, int pages_in_chunk,
1185 void UpdateAllocatedSpaceLimits(void* low, void* high) {
1186 lowest_ever_allocated_ = Min(lowest_ever_allocated_, low);
1187 highest_ever_allocated_ = Max(highest_ever_allocated_, high);
1190 DISALLOW_IMPLICIT_CONSTRUCTORS(MemoryAllocator);
1194 // -----------------------------------------------------------------------------
1195 // Interface for heap object iterator to be implemented by all object space
1196 // object iterators.
1198 // NOTE: The space specific object iterators also implements the own next()
1199 // method which is used to avoid using virtual functions
1200 // iterating a specific space.
1202 class ObjectIterator : public Malloced {
1204 virtual ~ObjectIterator() {}
1206 virtual HeapObject* next_object() = 0;
1210 // -----------------------------------------------------------------------------
1211 // Heap object iterator in new/old/map spaces.
1213 // A HeapObjectIterator iterates objects from the bottom of the given space
1214 // to its top or from the bottom of the given page to its top.
1216 // If objects are allocated in the page during iteration the iterator may
1217 // or may not iterate over those objects. The caller must create a new
1218 // iterator in order to be sure to visit these new objects.
1219 class HeapObjectIterator : public ObjectIterator {
1221 // Creates a new object iterator in a given space.
1222 // If the size function is not given, the iterator calls the default
1224 explicit HeapObjectIterator(PagedSpace* space);
1225 HeapObjectIterator(PagedSpace* space, HeapObjectCallback size_func);
1226 HeapObjectIterator(Page* page, HeapObjectCallback size_func);
1228 // Advance to the next object, skipping free spaces and other fillers and
1229 // skipping the special garbage section of which there is one per space.
1230 // Returns NULL when the iteration has ended.
1231 inline HeapObject* Next() {
1233 HeapObject* next_obj = FromCurrentPage();
1234 if (next_obj != NULL) return next_obj;
1235 } while (AdvanceToNextPage());
1239 virtual HeapObject* next_object() { return Next(); }
1242 enum PageMode { kOnePageOnly, kAllPagesInSpace };
1244 Address cur_addr_; // Current iteration point.
1245 Address cur_end_; // End iteration point.
1246 HeapObjectCallback size_func_; // Size function or NULL.
1248 PageMode page_mode_;
1250 // Fast (inlined) path of next().
1251 inline HeapObject* FromCurrentPage();
1253 // Slow path of next(), goes into the next page. Returns false if the
1254 // iteration has ended.
1255 bool AdvanceToNextPage();
1257 // Initializes fields.
1258 inline void Initialize(PagedSpace* owner, Address start, Address end,
1259 PageMode mode, HeapObjectCallback size_func);
1263 // -----------------------------------------------------------------------------
1264 // A PageIterator iterates the pages in a paged space.
1266 class PageIterator BASE_EMBEDDED {
1268 explicit inline PageIterator(PagedSpace* space);
1270 inline bool has_next();
1271 inline Page* next();
1275 Page* prev_page_; // Previous page returned.
1276 // Next page that will be returned. Cached here so that we can use this
1277 // iterator for operations that deallocate pages.
1282 // -----------------------------------------------------------------------------
1283 // A space has a circular list of pages. The next page can be accessed via
1284 // Page::next_page() call.
1286 // An abstraction of allocation and relocation pointers in a page-structured
1288 class AllocationInfo {
1290 AllocationInfo() : top_(NULL), limit_(NULL) {}
1292 INLINE(void set_top(Address top)) {
1293 SLOW_DCHECK(top == NULL ||
1294 (reinterpret_cast<intptr_t>(top) & kHeapObjectTagMask) == 0);
1298 INLINE(Address top()) const {
1299 SLOW_DCHECK(top_ == NULL ||
1300 (reinterpret_cast<intptr_t>(top_) & kHeapObjectTagMask) == 0);
1304 Address* top_address() { return &top_; }
1306 INLINE(void set_limit(Address limit)) {
1307 SLOW_DCHECK(limit == NULL ||
1308 (reinterpret_cast<intptr_t>(limit) & kHeapObjectTagMask) == 0);
1312 INLINE(Address limit()) const {
1313 SLOW_DCHECK(limit_ == NULL ||
1314 (reinterpret_cast<intptr_t>(limit_) & kHeapObjectTagMask) ==
1319 Address* limit_address() { return &limit_; }
1322 bool VerifyPagedAllocation() {
1323 return (Page::FromAllocationTop(top_) == Page::FromAllocationTop(limit_)) &&
1329 // Current allocation top.
1331 // Current allocation limit.
1336 // An abstraction of the accounting statistics of a page-structured space.
1337 // The 'capacity' of a space is the number of object-area bytes (i.e., not
1338 // including page bookkeeping structures) currently in the space. The 'size'
1339 // of a space is the number of allocated bytes, the 'waste' in the space is
1340 // the number of bytes that are not allocated and not available to
1341 // allocation without reorganizing the space via a GC (e.g. small blocks due
1342 // to internal fragmentation, top of page areas in map space), and the bytes
1343 // 'available' is the number of unallocated bytes that are not waste. The
1344 // capacity is the sum of size, waste, and available.
1346 // The stats are only set by functions that ensure they stay balanced. These
1347 // functions increase or decrease one of the non-capacity stats in
1348 // conjunction with capacity, or else they always balance increases and
1349 // decreases to the non-capacity stats.
1350 class AllocationStats BASE_EMBEDDED {
1352 AllocationStats() { Clear(); }
1354 // Zero out all the allocation statistics (i.e., no capacity).
1362 void ClearSizeWaste() {
1367 // Reset the allocation statistics (i.e., available = capacity with no
1368 // wasted or allocated bytes).
1374 // Accessors for the allocation statistics.
1375 intptr_t Capacity() { return capacity_; }
1376 intptr_t MaxCapacity() { return max_capacity_; }
1377 intptr_t Size() { return size_; }
1378 intptr_t Waste() { return waste_; }
1380 // Grow the space by adding available bytes. They are initially marked as
1381 // being in use (part of the size), but will normally be immediately freed,
1382 // putting them on the free list and removing them from size_.
1383 void ExpandSpace(int size_in_bytes) {
1384 capacity_ += size_in_bytes;
1385 size_ += size_in_bytes;
1386 if (capacity_ > max_capacity_) {
1387 max_capacity_ = capacity_;
1392 // Shrink the space by removing available bytes. Since shrinking is done
1393 // during sweeping, bytes have been marked as being in use (part of the size)
1394 // and are hereby freed.
1395 void ShrinkSpace(int size_in_bytes) {
1396 capacity_ -= size_in_bytes;
1397 size_ -= size_in_bytes;
1401 // Allocate from available bytes (available -> size).
1402 void AllocateBytes(intptr_t size_in_bytes) {
1403 size_ += size_in_bytes;
1407 // Free allocated bytes, making them available (size -> available).
1408 void DeallocateBytes(intptr_t size_in_bytes) {
1409 size_ -= size_in_bytes;
1413 // Waste free bytes (available -> waste).
1414 void WasteBytes(int size_in_bytes) {
1415 DCHECK(size_in_bytes >= 0);
1416 waste_ += size_in_bytes;
1421 intptr_t max_capacity_;
1427 // -----------------------------------------------------------------------------
1428 // Free lists for old object spaces
1430 // The free list category holds a pointer to the top element and a pointer to
1431 // the end element of the linked list of free memory blocks.
1432 class FreeListCategory {
1434 FreeListCategory() : top_(0), end_(NULL), available_(0) {}
1436 intptr_t Concatenate(FreeListCategory* category);
1440 void Free(FreeSpace* node, int size_in_bytes);
1442 FreeSpace* PickNodeFromList(int* node_size);
1443 FreeSpace* PickNodeFromList(int size_in_bytes, int* node_size);
1445 intptr_t EvictFreeListItemsInList(Page* p);
1446 bool ContainsPageFreeListItemsInList(Page* p);
1448 void RepairFreeList(Heap* heap);
1450 FreeSpace* top() const {
1451 return reinterpret_cast<FreeSpace*>(base::NoBarrier_Load(&top_));
1454 void set_top(FreeSpace* top) {
1455 base::NoBarrier_Store(&top_, reinterpret_cast<base::AtomicWord>(top));
1458 FreeSpace* end() const { return end_; }
1459 void set_end(FreeSpace* end) { end_ = end; }
1461 int* GetAvailableAddress() { return &available_; }
1462 int available() const { return available_; }
1463 void set_available(int available) { available_ = available; }
1465 base::Mutex* mutex() { return &mutex_; }
1467 bool IsEmpty() { return top() == 0; }
1470 intptr_t SumFreeList();
1471 int FreeListLength();
1475 // top_ points to the top FreeSpace* in the free list category.
1476 base::AtomicWord top_;
1480 // Total available bytes in all blocks of this free list category.
1485 // The free list for the old space. The free list is organized in such a way
1486 // as to encourage objects allocated around the same time to be near each
1487 // other. The normal way to allocate is intended to be by bumping a 'top'
1488 // pointer until it hits a 'limit' pointer. When the limit is hit we need to
1489 // find a new space to allocate from. This is done with the free list, which
1490 // is divided up into rough categories to cut down on waste. Having finer
1491 // categories would scatter allocation more.
1493 // The old space free list is organized in categories.
1494 // 1-31 words: Such small free areas are discarded for efficiency reasons.
1495 // They can be reclaimed by the compactor. However the distance between top
1496 // and limit may be this small.
1497 // 32-255 words: There is a list of spaces this large. It is used for top and
1498 // limit when the object we need to allocate is 1-31 words in size. These
1499 // spaces are called small.
1500 // 256-2047 words: There is a list of spaces this large. It is used for top and
1501 // limit when the object we need to allocate is 32-255 words in size. These
1502 // spaces are called medium.
1503 // 1048-16383 words: There is a list of spaces this large. It is used for top
1504 // and limit when the object we need to allocate is 256-2047 words in size.
1505 // These spaces are call large.
1506 // At least 16384 words. This list is for objects of 2048 words or larger.
1507 // Empty pages are added to this list. These spaces are called huge.
1510 explicit FreeList(PagedSpace* owner);
1512 intptr_t Concatenate(FreeList* free_list);
1514 // Clear the free list.
1517 // Return the number of bytes available on the free list.
1518 intptr_t available() {
1519 return small_list_.available() + medium_list_.available() +
1520 large_list_.available() + huge_list_.available();
1523 // Place a node on the free list. The block of size 'size_in_bytes'
1524 // starting at 'start' is placed on the free list. The return value is the
1525 // number of bytes that have been lost due to internal fragmentation by
1526 // freeing the block. Bookkeeping information will be written to the block,
1527 // i.e., its contents will be destroyed. The start address should be word
1528 // aligned, and the size should be a non-zero multiple of the word size.
1529 int Free(Address start, int size_in_bytes);
1531 // This method returns how much memory can be allocated after freeing
1532 // maximum_freed memory.
1533 static inline int GuaranteedAllocatable(int maximum_freed) {
1534 if (maximum_freed < kSmallListMin) {
1536 } else if (maximum_freed <= kSmallListMax) {
1537 return kSmallAllocationMax;
1538 } else if (maximum_freed <= kMediumListMax) {
1539 return kMediumAllocationMax;
1540 } else if (maximum_freed <= kLargeListMax) {
1541 return kLargeAllocationMax;
1543 return maximum_freed;
1546 // Allocate a block of size 'size_in_bytes' from the free list. The block
1547 // is unitialized. A failure is returned if no block is available. The
1548 // number of bytes lost to fragmentation is returned in the output parameter
1549 // 'wasted_bytes'. The size should be a non-zero multiple of the word size.
1550 MUST_USE_RESULT HeapObject* Allocate(int size_in_bytes);
1553 return small_list_.IsEmpty() && medium_list_.IsEmpty() &&
1554 large_list_.IsEmpty() && huge_list_.IsEmpty();
1559 intptr_t SumFreeLists();
1563 // Used after booting the VM.
1564 void RepairLists(Heap* heap);
1566 intptr_t EvictFreeListItems(Page* p);
1567 bool ContainsPageFreeListItems(Page* p);
1569 FreeListCategory* small_list() { return &small_list_; }
1570 FreeListCategory* medium_list() { return &medium_list_; }
1571 FreeListCategory* large_list() { return &large_list_; }
1572 FreeListCategory* huge_list() { return &huge_list_; }
1574 static const int kSmallListMin = 0x20 * kPointerSize;
1577 // The size range of blocks, in bytes.
1578 static const int kMinBlockSize = 3 * kPointerSize;
1579 static const int kMaxBlockSize = Page::kMaxRegularHeapObjectSize;
1581 FreeSpace* FindNodeFor(int size_in_bytes, int* node_size);
1586 static const int kSmallListMax = 0xff * kPointerSize;
1587 static const int kMediumListMax = 0x7ff * kPointerSize;
1588 static const int kLargeListMax = 0x3fff * kPointerSize;
1589 static const int kSmallAllocationMax = kSmallListMin - kPointerSize;
1590 static const int kMediumAllocationMax = kSmallListMax;
1591 static const int kLargeAllocationMax = kMediumListMax;
1592 FreeListCategory small_list_;
1593 FreeListCategory medium_list_;
1594 FreeListCategory large_list_;
1595 FreeListCategory huge_list_;
1597 DISALLOW_IMPLICIT_CONSTRUCTORS(FreeList);
1601 class AllocationResult {
1603 // Implicit constructor from Object*.
1604 AllocationResult(Object* object) // NOLINT
1606 // AllocationResults can't return Smis, which are used to represent
1607 // failure and the space to retry in.
1608 CHECK(!object->IsSmi());
1611 AllocationResult() : object_(Smi::FromInt(NEW_SPACE)) {}
1613 static inline AllocationResult Retry(AllocationSpace space = NEW_SPACE) {
1614 return AllocationResult(space);
1617 inline bool IsRetry() { return object_->IsSmi(); }
1619 template <typename T>
1621 if (IsRetry()) return false;
1622 *obj = T::cast(object_);
1626 Object* ToObjectChecked() {
1631 AllocationSpace RetrySpace() {
1633 return static_cast<AllocationSpace>(Smi::cast(object_)->value());
1637 explicit AllocationResult(AllocationSpace space)
1638 : object_(Smi::FromInt(static_cast<int>(space))) {}
1644 STATIC_ASSERT(sizeof(AllocationResult) == kPointerSize);
1647 class PagedSpace : public Space {
1649 // Creates a space with a maximum capacity, and an id.
1650 PagedSpace(Heap* heap, intptr_t max_capacity, AllocationSpace id,
1651 Executability executable);
1653 virtual ~PagedSpace() {}
1655 // Set up the space using the given address range of virtual memory (from
1656 // the memory allocator's initial chunk) if possible. If the block of
1657 // addresses is not big enough to contain a single page-aligned page, a
1658 // fresh chunk will be allocated.
1661 // Returns true if the space has been successfully set up and not
1662 // subsequently torn down.
1663 bool HasBeenSetUp();
1665 // Cleans up the space, frees all pages in this space except those belonging
1666 // to the initial chunk, uncommits addresses in the initial chunk.
1669 // Checks whether an object/address is in this space.
1670 inline bool Contains(Address a);
1671 bool Contains(HeapObject* o) { return Contains(o->address()); }
1672 // Unlike Contains() methods it is safe to call this one even for addresses
1673 // of unmapped memory.
1674 bool ContainsSafe(Address addr);
1676 // Given an address occupied by a live object, return that object if it is
1677 // in this space, or a Smi if it is not. The implementation iterates over
1678 // objects in the page containing the address, the cost is linear in the
1679 // number of objects in the page. It may be slow.
1680 Object* FindObject(Address addr);
1682 // During boot the free_space_map is created, and afterwards we may need
1683 // to write it into the free list nodes that were already created.
1684 void RepairFreeListsAfterDeserialization();
1686 // Prepares for a mark-compact GC.
1687 void PrepareForMarkCompact();
1689 // Current capacity without growing (Size() + Available()).
1690 intptr_t Capacity() { return accounting_stats_.Capacity(); }
1692 // Total amount of memory committed for this space. For paged
1693 // spaces this equals the capacity.
1694 intptr_t CommittedMemory() { return Capacity(); }
1696 // The maximum amount of memory ever committed for this space.
1697 intptr_t MaximumCommittedMemory() { return accounting_stats_.MaxCapacity(); }
1699 // Approximate amount of physical memory committed for this space.
1700 size_t CommittedPhysicalMemory();
1704 return small_size_ + medium_size_ + large_size_ + huge_size_;
1707 intptr_t small_size_;
1708 intptr_t medium_size_;
1709 intptr_t large_size_;
1710 intptr_t huge_size_;
1713 void ObtainFreeListStatistics(Page* p, SizeStats* sizes);
1714 void ResetFreeListStatistics();
1716 // Sets the capacity, the available space and the wasted space to zero.
1717 // The stats are rebuilt during sweeping by adding each page to the
1718 // capacity and the size when it is encountered. As free spaces are
1719 // discovered during the sweeping they are subtracted from the size and added
1720 // to the available and wasted totals.
1722 accounting_stats_.ClearSizeWaste();
1723 ResetFreeListStatistics();
1726 // Increases the number of available bytes of that space.
1727 void AddToAccountingStats(intptr_t bytes) {
1728 accounting_stats_.DeallocateBytes(bytes);
1731 // Available bytes without growing. These are the bytes on the free list.
1732 // The bytes in the linear allocation area are not included in this total
1733 // because updating the stats would slow down allocation. New pages are
1734 // immediately added to the free list so they show up here.
1735 intptr_t Available() { return free_list_.available(); }
1737 // Allocated bytes in this space. Garbage bytes that were not found due to
1738 // concurrent sweeping are counted as being allocated! The bytes in the
1739 // current linear allocation area (between top and limit) are also counted
1741 virtual intptr_t Size() { return accounting_stats_.Size(); }
1743 // As size, but the bytes in lazily swept pages are estimated and the bytes
1744 // in the current linear allocation area are not included.
1745 virtual intptr_t SizeOfObjects();
1747 // Wasted bytes in this space. These are just the bytes that were thrown away
1748 // due to being too small to use for allocation. They do not include the
1749 // free bytes that were not found at all due to lazy sweeping.
1750 virtual intptr_t Waste() { return accounting_stats_.Waste(); }
1752 // Returns the allocation pointer in this space.
1753 Address top() { return allocation_info_.top(); }
1754 Address limit() { return allocation_info_.limit(); }
1756 // The allocation top address.
1757 Address* allocation_top_address() { return allocation_info_.top_address(); }
1759 // The allocation limit address.
1760 Address* allocation_limit_address() {
1761 return allocation_info_.limit_address();
1764 // Allocate the requested number of bytes in the space if possible, return a
1765 // failure object if not.
1766 MUST_USE_RESULT inline AllocationResult AllocateRaw(int size_in_bytes);
1768 // Give a block of memory to the space's free list. It might be added to
1769 // the free list or accounted as waste.
1770 // If add_to_freelist is false then just accounting stats are updated and
1771 // no attempt to add area to free list is made.
1772 int Free(Address start, int size_in_bytes) {
1773 int wasted = free_list_.Free(start, size_in_bytes);
1774 accounting_stats_.DeallocateBytes(size_in_bytes);
1775 accounting_stats_.WasteBytes(wasted);
1776 return size_in_bytes - wasted;
1779 void ResetFreeList() { free_list_.Reset(); }
1781 // Set space allocation info.
1782 void SetTopAndLimit(Address top, Address limit) {
1783 DCHECK(top == limit ||
1784 Page::FromAddress(top) == Page::FromAddress(limit - 1));
1785 MemoryChunk::UpdateHighWaterMark(allocation_info_.top());
1786 allocation_info_.set_top(top);
1787 allocation_info_.set_limit(limit);
1790 // Empty space allocation info, returning unused area to free list.
1791 void EmptyAllocationInfo() {
1792 // Mark the old linear allocation area with a free space map so it can be
1793 // skipped when scanning the heap.
1794 int old_linear_size = static_cast<int>(limit() - top());
1795 Free(top(), old_linear_size);
1796 SetTopAndLimit(NULL, NULL);
1799 void Allocate(int bytes) { accounting_stats_.AllocateBytes(bytes); }
1801 void IncreaseCapacity(int size);
1803 // Releases an unused page and shrinks the space.
1804 void ReleasePage(Page* page);
1806 // The dummy page that anchors the linked list of pages.
1807 Page* anchor() { return &anchor_; }
1810 // Verify integrity of this space.
1811 virtual void Verify(ObjectVisitor* visitor);
1813 // Overridden by subclasses to verify space-specific object
1814 // properties (e.g., only maps or free-list nodes are in map space).
1815 virtual void VerifyObject(HeapObject* obj) {}
1819 // Print meta info and objects in this space.
1820 virtual void Print();
1822 // Reports statistics for the space
1823 void ReportStatistics();
1825 // Report code object related statistics
1826 void CollectCodeStatistics();
1827 static void ReportCodeStatistics(Isolate* isolate);
1828 static void ResetCodeStatistics(Isolate* isolate);
1831 // Evacuation candidates are swept by evacuator. Needs to return a valid
1832 // result before _and_ after evacuation has finished.
1833 static bool ShouldBeSweptBySweeperThreads(Page* p) {
1834 return !p->IsEvacuationCandidate() &&
1835 !p->IsFlagSet(Page::RESCAN_ON_EVACUATION) && !p->WasSwept();
1838 void IncrementUnsweptFreeBytes(intptr_t by) { unswept_free_bytes_ += by; }
1840 void IncreaseUnsweptFreeBytes(Page* p) {
1841 DCHECK(ShouldBeSweptBySweeperThreads(p));
1842 unswept_free_bytes_ += (p->area_size() - p->LiveBytes());
1845 void DecrementUnsweptFreeBytes(intptr_t by) { unswept_free_bytes_ -= by; }
1847 void DecreaseUnsweptFreeBytes(Page* p) {
1848 DCHECK(ShouldBeSweptBySweeperThreads(p));
1849 unswept_free_bytes_ -= (p->area_size() - p->LiveBytes());
1852 void ResetUnsweptFreeBytes() { unswept_free_bytes_ = 0; }
1854 // This function tries to steal size_in_bytes memory from the sweeper threads
1855 // free-lists. If it does not succeed stealing enough memory, it will wait
1856 // for the sweeper threads to finish sweeping.
1857 // It returns true when sweeping is completed and false otherwise.
1858 bool EnsureSweeperProgress(intptr_t size_in_bytes);
1860 void set_end_of_unswept_pages(Page* page) { end_of_unswept_pages_ = page; }
1862 Page* end_of_unswept_pages() { return end_of_unswept_pages_; }
1864 Page* FirstPage() { return anchor_.next_page(); }
1865 Page* LastPage() { return anchor_.prev_page(); }
1867 void EvictEvacuationCandidatesFromFreeLists();
1871 // Returns the number of total pages in this space.
1872 int CountTotalPages();
1874 // Return size of allocatable area on a page in this space.
1875 inline int AreaSize() { return area_size_; }
1877 void CreateEmergencyMemory();
1878 void FreeEmergencyMemory();
1879 void UseEmergencyMemory();
1880 intptr_t MaxEmergencyMemoryAllocated();
1882 bool HasEmergencyMemory() { return emergency_memory_ != NULL; }
1885 FreeList* free_list() { return &free_list_; }
1889 // Maximum capacity of this space.
1890 intptr_t max_capacity_;
1892 // Accounting information for this space.
1893 AllocationStats accounting_stats_;
1895 // The dummy page that anchors the double linked list of pages.
1898 // The space's free list.
1899 FreeList free_list_;
1901 // Normal allocation information.
1902 AllocationInfo allocation_info_;
1904 // The number of free bytes which could be reclaimed by advancing the
1905 // concurrent sweeper threads.
1906 intptr_t unswept_free_bytes_;
1908 // The sweeper threads iterate over the list of pointer and data space pages
1909 // and sweep these pages concurrently. They will stop sweeping after the
1910 // end_of_unswept_pages_ page.
1911 Page* end_of_unswept_pages_;
1913 // Emergency memory is the memory of a full page for a given space, allocated
1914 // conservatively before evacuating a page. If compaction fails due to out
1915 // of memory error the emergency memory can be used to complete compaction.
1916 // If not used, the emergency memory is released after compaction.
1917 MemoryChunk* emergency_memory_;
1919 // Expands the space by allocating a fixed number of pages. Returns false if
1920 // it cannot allocate requested number of pages from OS, or if the hard heap
1921 // size limit has been hit.
1924 // Generic fast case allocation function that tries linear allocation at the
1925 // address denoted by top in allocation_info_.
1926 inline HeapObject* AllocateLinearly(int size_in_bytes);
1928 // If sweeping is still in progress try to sweep unswept pages. If that is
1929 // not successful, wait for the sweeper threads and re-try free-list
1931 MUST_USE_RESULT HeapObject* WaitForSweeperThreadsAndRetryAllocation(
1934 // Slow path of AllocateRaw. This function is space-dependent.
1935 MUST_USE_RESULT HeapObject* SlowAllocateRaw(int size_in_bytes);
1937 friend class PageIterator;
1938 friend class MarkCompactCollector;
1942 class NumberAndSizeInfo BASE_EMBEDDED {
1944 NumberAndSizeInfo() : number_(0), bytes_(0) {}
1946 int number() const { return number_; }
1947 void increment_number(int num) { number_ += num; }
1949 int bytes() const { return bytes_; }
1950 void increment_bytes(int size) { bytes_ += size; }
1963 // HistogramInfo class for recording a single "bar" of a histogram. This
1964 // class is used for collecting statistics to print to the log file.
1965 class HistogramInfo : public NumberAndSizeInfo {
1967 HistogramInfo() : NumberAndSizeInfo() {}
1969 const char* name() { return name_; }
1970 void set_name(const char* name) { name_ = name; }
1977 enum SemiSpaceId { kFromSpace = 0, kToSpace = 1 };
1983 class NewSpacePage : public MemoryChunk {
1985 // GC related flags copied from from-space to to-space when
1986 // flipping semispaces.
1987 static const intptr_t kCopyOnFlipFlagsMask =
1988 (1 << MemoryChunk::POINTERS_TO_HERE_ARE_INTERESTING) |
1989 (1 << MemoryChunk::POINTERS_FROM_HERE_ARE_INTERESTING) |
1990 (1 << MemoryChunk::SCAN_ON_SCAVENGE);
1992 static const int kAreaSize = Page::kMaxRegularHeapObjectSize;
1994 inline NewSpacePage* next_page() const {
1995 return static_cast<NewSpacePage*>(next_chunk());
1998 inline void set_next_page(NewSpacePage* page) { set_next_chunk(page); }
2000 inline NewSpacePage* prev_page() const {
2001 return static_cast<NewSpacePage*>(prev_chunk());
2004 inline void set_prev_page(NewSpacePage* page) { set_prev_chunk(page); }
2006 SemiSpace* semi_space() { return reinterpret_cast<SemiSpace*>(owner()); }
2008 bool is_anchor() { return !this->InNewSpace(); }
2010 static bool IsAtStart(Address addr) {
2011 return (reinterpret_cast<intptr_t>(addr) & Page::kPageAlignmentMask) ==
2015 static bool IsAtEnd(Address addr) {
2016 return (reinterpret_cast<intptr_t>(addr) & Page::kPageAlignmentMask) == 0;
2019 Address address() { return reinterpret_cast<Address>(this); }
2021 // Finds the NewSpacePage containing the given address.
2022 static inline NewSpacePage* FromAddress(Address address_in_page) {
2023 Address page_start =
2024 reinterpret_cast<Address>(reinterpret_cast<uintptr_t>(address_in_page) &
2025 ~Page::kPageAlignmentMask);
2026 NewSpacePage* page = reinterpret_cast<NewSpacePage*>(page_start);
2030 // Find the page for a limit address. A limit address is either an address
2031 // inside a page, or the address right after the last byte of a page.
2032 static inline NewSpacePage* FromLimit(Address address_limit) {
2033 return NewSpacePage::FromAddress(address_limit - 1);
2036 // Checks if address1 and address2 are on the same new space page.
2037 static inline bool OnSamePage(Address address1, Address address2) {
2038 return NewSpacePage::FromAddress(address1) ==
2039 NewSpacePage::FromAddress(address2);
2043 // Create a NewSpacePage object that is only used as anchor
2044 // for the doubly-linked list of real pages.
2045 explicit NewSpacePage(SemiSpace* owner) { InitializeAsAnchor(owner); }
2047 static NewSpacePage* Initialize(Heap* heap, Address start,
2048 SemiSpace* semi_space);
2050 // Intialize a fake NewSpacePage used as sentinel at the ends
2051 // of a doubly-linked list of real NewSpacePages.
2052 // Only uses the prev/next links, and sets flags to not be in new-space.
2053 void InitializeAsAnchor(SemiSpace* owner);
2055 friend class SemiSpace;
2056 friend class SemiSpaceIterator;
2060 // -----------------------------------------------------------------------------
2061 // SemiSpace in young generation
2063 // A semispace is a contiguous chunk of memory holding page-like memory
2064 // chunks. The mark-compact collector uses the memory of the first page in
2065 // the from space as a marking stack when tracing live objects.
2067 class SemiSpace : public Space {
2070 SemiSpace(Heap* heap, SemiSpaceId semispace)
2071 : Space(heap, NEW_SPACE, NOT_EXECUTABLE),
2076 current_page_(NULL) {}
2078 // Sets up the semispace using the given chunk.
2079 void SetUp(Address start, int initial_capacity, int target_capacity,
2080 int maximum_capacity);
2082 // Tear down the space. Heap memory was not allocated by the space, so it
2083 // is not deallocated here.
2086 // True if the space has been set up but not torn down.
2087 bool HasBeenSetUp() { return start_ != NULL; }
2089 // Grow the semispace to the new capacity. The new capacity
2090 // requested must be larger than the current capacity and less than
2091 // the maximum capacity.
2092 bool GrowTo(int new_capacity);
2094 // Shrinks the semispace to the new capacity. The new capacity
2095 // requested must be more than the amount of used memory in the
2096 // semispace and less than the current capacity.
2097 bool ShrinkTo(int new_capacity);
2099 // Sets the total capacity. Only possible when the space is not committed.
2100 bool SetTotalCapacity(int new_capacity);
2102 // Returns the start address of the first page of the space.
2103 Address space_start() {
2104 DCHECK(anchor_.next_page() != &anchor_);
2105 return anchor_.next_page()->area_start();
2108 // Returns the start address of the current page of the space.
2109 Address page_low() { return current_page_->area_start(); }
2111 // Returns one past the end address of the space.
2112 Address space_end() { return anchor_.prev_page()->area_end(); }
2114 // Returns one past the end address of the current page of the space.
2115 Address page_high() { return current_page_->area_end(); }
2117 bool AdvancePage() {
2118 NewSpacePage* next_page = current_page_->next_page();
2119 if (next_page == anchor()) return false;
2120 current_page_ = next_page;
2124 // Resets the space to using the first page.
2127 // Age mark accessors.
2128 Address age_mark() { return age_mark_; }
2129 void set_age_mark(Address mark);
2131 // True if the address is in the address range of this semispace (not
2132 // necessarily below the allocation pointer).
2133 bool Contains(Address a) {
2134 return (reinterpret_cast<uintptr_t>(a) & address_mask_) ==
2135 reinterpret_cast<uintptr_t>(start_);
2138 // True if the object is a heap object in the address range of this
2139 // semispace (not necessarily below the allocation pointer).
2140 bool Contains(Object* o) {
2141 return (reinterpret_cast<uintptr_t>(o) & object_mask_) == object_expected_;
2144 // If we don't have these here then SemiSpace will be abstract. However
2145 // they should never be called.
2146 virtual intptr_t Size() {
2151 bool is_committed() { return committed_; }
2155 NewSpacePage* first_page() { return anchor_.next_page(); }
2156 NewSpacePage* current_page() { return current_page_; }
2159 virtual void Verify();
2163 virtual void Print();
2164 // Validate a range of of addresses in a SemiSpace.
2165 // The "from" address must be on a page prior to the "to" address,
2166 // in the linked page order, or it must be earlier on the same page.
2167 static void AssertValidRange(Address from, Address to);
2170 inline static void AssertValidRange(Address from, Address to) {}
2173 // Returns the current total capacity of the semispace.
2174 int TotalCapacity() { return total_capacity_; }
2176 // Returns the target for total capacity of the semispace.
2177 int TargetCapacity() { return target_capacity_; }
2179 // Returns the maximum total capacity of the semispace.
2180 int MaximumTotalCapacity() { return maximum_total_capacity_; }
2182 // Returns the initial capacity of the semispace.
2183 int InitialTotalCapacity() { return initial_total_capacity_; }
2185 SemiSpaceId id() { return id_; }
2187 static void Swap(SemiSpace* from, SemiSpace* to);
2189 // Returns the maximum amount of memory ever committed by the semi space.
2190 size_t MaximumCommittedMemory() { return maximum_committed_; }
2192 // Approximate amount of physical memory committed for this space.
2193 size_t CommittedPhysicalMemory();
2196 // Flips the semispace between being from-space and to-space.
2197 // Copies the flags into the masked positions on all pages in the space.
2198 void FlipPages(intptr_t flags, intptr_t flag_mask);
2200 // Updates Capacity and MaximumCommitted based on new capacity.
2201 void SetCapacity(int new_capacity);
2203 NewSpacePage* anchor() { return &anchor_; }
2205 // The current and maximum total capacity of the space.
2206 int total_capacity_;
2207 int target_capacity_;
2208 int maximum_total_capacity_;
2209 int initial_total_capacity_;
2211 intptr_t maximum_committed_;
2213 // The start address of the space.
2215 // Used to govern object promotion during mark-compact collection.
2218 // Masks and comparison values to test for containment in this semispace.
2219 uintptr_t address_mask_;
2220 uintptr_t object_mask_;
2221 uintptr_t object_expected_;
2226 NewSpacePage anchor_;
2227 NewSpacePage* current_page_;
2229 friend class SemiSpaceIterator;
2230 friend class NewSpacePageIterator;
2233 TRACK_MEMORY("SemiSpace")
2237 // A SemiSpaceIterator is an ObjectIterator that iterates over the active
2238 // semispace of the heap's new space. It iterates over the objects in the
2239 // semispace from a given start address (defaulting to the bottom of the
2240 // semispace) to the top of the semispace. New objects allocated after the
2241 // iterator is created are not iterated.
2242 class SemiSpaceIterator : public ObjectIterator {
2244 // Create an iterator over the objects in the given space. If no start
2245 // address is given, the iterator starts from the bottom of the space. If
2246 // no size function is given, the iterator calls Object::Size().
2248 // Iterate over all of allocated to-space.
2249 explicit SemiSpaceIterator(NewSpace* space);
2250 // Iterate over all of allocated to-space, with a custome size function.
2251 SemiSpaceIterator(NewSpace* space, HeapObjectCallback size_func);
2252 // Iterate over part of allocated to-space, from start to the end
2254 SemiSpaceIterator(NewSpace* space, Address start);
2255 // Iterate from one address to another in the same semi-space.
2256 SemiSpaceIterator(Address from, Address to);
2258 HeapObject* Next() {
2259 if (current_ == limit_) return NULL;
2260 if (NewSpacePage::IsAtEnd(current_)) {
2261 NewSpacePage* page = NewSpacePage::FromLimit(current_);
2262 page = page->next_page();
2263 DCHECK(!page->is_anchor());
2264 current_ = page->area_start();
2265 if (current_ == limit_) return NULL;
2268 HeapObject* object = HeapObject::FromAddress(current_);
2269 int size = (size_func_ == NULL) ? object->Size() : size_func_(object);
2275 // Implementation of the ObjectIterator functions.
2276 virtual HeapObject* next_object() { return Next(); }
2279 void Initialize(Address start, Address end, HeapObjectCallback size_func);
2281 // The current iteration point.
2283 // The end of iteration.
2285 // The callback function.
2286 HeapObjectCallback size_func_;
2290 // -----------------------------------------------------------------------------
2291 // A PageIterator iterates the pages in a semi-space.
2292 class NewSpacePageIterator BASE_EMBEDDED {
2294 // Make an iterator that runs over all pages in to-space.
2295 explicit inline NewSpacePageIterator(NewSpace* space);
2297 // Make an iterator that runs over all pages in the given semispace,
2298 // even those not used in allocation.
2299 explicit inline NewSpacePageIterator(SemiSpace* space);
2301 // Make iterator that iterates from the page containing start
2302 // to the page that contains limit in the same semispace.
2303 inline NewSpacePageIterator(Address start, Address limit);
2305 inline bool has_next();
2306 inline NewSpacePage* next();
2309 NewSpacePage* prev_page_; // Previous page returned.
2310 // Next page that will be returned. Cached here so that we can use this
2311 // iterator for operations that deallocate pages.
2312 NewSpacePage* next_page_;
2313 // Last page returned.
2314 NewSpacePage* last_page_;
2318 // -----------------------------------------------------------------------------
2319 // The young generation space.
2321 // The new space consists of a contiguous pair of semispaces. It simply
2322 // forwards most functions to the appropriate semispace.
2324 class NewSpace : public Space {
2327 explicit NewSpace(Heap* heap)
2328 : Space(heap, NEW_SPACE, NOT_EXECUTABLE),
2329 to_space_(heap, kToSpace),
2330 from_space_(heap, kFromSpace),
2332 inline_allocation_limit_step_(0) {}
2334 // Sets up the new space using the given chunk.
2335 bool SetUp(int reserved_semispace_size_, int max_semi_space_size);
2337 // Tears down the space. Heap memory was not allocated by the space, so it
2338 // is not deallocated here.
2341 // True if the space has been set up but not torn down.
2342 bool HasBeenSetUp() {
2343 return to_space_.HasBeenSetUp() && from_space_.HasBeenSetUp();
2346 // Flip the pair of spaces.
2349 // Grow the capacity of the semispaces. Assumes that they are not at
2350 // their maximum capacity.
2353 // Grow the capacity of the semispaces by one page.
2356 // Shrink the capacity of the semispaces.
2359 // True if the address or object lies in the address range of either
2360 // semispace (not necessarily below the allocation pointer).
2361 bool Contains(Address a) {
2362 return (reinterpret_cast<uintptr_t>(a) & address_mask_) ==
2363 reinterpret_cast<uintptr_t>(start_);
2366 bool Contains(Object* o) {
2367 Address a = reinterpret_cast<Address>(o);
2368 return (reinterpret_cast<uintptr_t>(a) & object_mask_) == object_expected_;
2371 // Return the allocated bytes in the active semispace.
2372 virtual intptr_t Size() {
2373 return pages_used_ * NewSpacePage::kAreaSize +
2374 static_cast<int>(top() - to_space_.page_low());
2377 // The same, but returning an int. We have to have the one that returns
2378 // intptr_t because it is inherited, but if we know we are dealing with the
2379 // new space, which can't get as big as the other spaces then this is useful:
2380 int SizeAsInt() { return static_cast<int>(Size()); }
2382 // Return the allocatable capacity of a semispace.
2383 intptr_t Capacity() {
2384 SLOW_DCHECK(to_space_.TotalCapacity() == from_space_.TotalCapacity());
2385 return (to_space_.TotalCapacity() / Page::kPageSize) *
2386 NewSpacePage::kAreaSize;
2389 // Return the current size of a semispace, allocatable and non-allocatable
2391 intptr_t TotalCapacity() {
2392 DCHECK(to_space_.TotalCapacity() == from_space_.TotalCapacity());
2393 return to_space_.TotalCapacity();
2396 // Return the total amount of memory committed for new space.
2397 intptr_t CommittedMemory() {
2398 if (from_space_.is_committed()) return 2 * Capacity();
2399 return TotalCapacity();
2402 // Return the total amount of memory committed for new space.
2403 intptr_t MaximumCommittedMemory() {
2404 return to_space_.MaximumCommittedMemory() +
2405 from_space_.MaximumCommittedMemory();
2408 // Approximate amount of physical memory committed for this space.
2409 size_t CommittedPhysicalMemory();
2411 // Return the available bytes without growing.
2412 intptr_t Available() { return Capacity() - Size(); }
2414 // Return the maximum capacity of a semispace.
2415 int MaximumCapacity() {
2416 DCHECK(to_space_.MaximumTotalCapacity() ==
2417 from_space_.MaximumTotalCapacity());
2418 return to_space_.MaximumTotalCapacity();
2421 bool IsAtMaximumCapacity() { return TotalCapacity() == MaximumCapacity(); }
2423 // Returns the initial capacity of a semispace.
2424 int InitialTotalCapacity() {
2425 DCHECK(to_space_.InitialTotalCapacity() ==
2426 from_space_.InitialTotalCapacity());
2427 return to_space_.InitialTotalCapacity();
2430 // Return the address of the allocation pointer in the active semispace.
2432 DCHECK(to_space_.current_page()->ContainsLimit(allocation_info_.top()));
2433 return allocation_info_.top();
2436 void set_top(Address top) {
2437 DCHECK(to_space_.current_page()->ContainsLimit(top));
2438 allocation_info_.set_top(top);
2441 // Return the address of the allocation pointer limit in the active semispace.
2443 DCHECK(to_space_.current_page()->ContainsLimit(allocation_info_.limit()));
2444 return allocation_info_.limit();
2447 // Return the address of the first object in the active semispace.
2448 Address bottom() { return to_space_.space_start(); }
2450 // Get the age mark of the inactive semispace.
2451 Address age_mark() { return from_space_.age_mark(); }
2452 // Set the age mark in the active semispace.
2453 void set_age_mark(Address mark) { to_space_.set_age_mark(mark); }
2455 // The start address of the space and a bit mask. Anding an address in the
2456 // new space with the mask will result in the start address.
2457 Address start() { return start_; }
2458 uintptr_t mask() { return address_mask_; }
2460 INLINE(uint32_t AddressToMarkbitIndex(Address addr)) {
2461 DCHECK(Contains(addr));
2462 DCHECK(IsAligned(OffsetFrom(addr), kPointerSize) ||
2463 IsAligned(OffsetFrom(addr) - 1, kPointerSize));
2464 return static_cast<uint32_t>(addr - start_) >> kPointerSizeLog2;
2467 INLINE(Address MarkbitIndexToAddress(uint32_t index)) {
2468 return reinterpret_cast<Address>(index << kPointerSizeLog2);
2471 // The allocation top and limit address.
2472 Address* allocation_top_address() { return allocation_info_.top_address(); }
2474 // The allocation limit address.
2475 Address* allocation_limit_address() {
2476 return allocation_info_.limit_address();
2479 MUST_USE_RESULT INLINE(AllocationResult AllocateRaw(int size_in_bytes));
2481 // Reset the allocation pointer to the beginning of the active semispace.
2482 void ResetAllocationInfo();
2484 void UpdateInlineAllocationLimit(int size_in_bytes);
2485 void LowerInlineAllocationLimit(intptr_t step) {
2486 inline_allocation_limit_step_ = step;
2487 UpdateInlineAllocationLimit(0);
2488 top_on_previous_step_ = allocation_info_.top();
2491 // Get the extent of the inactive semispace (for use as a marking stack,
2492 // or to zap it). Notice: space-addresses are not necessarily on the
2493 // same page, so FromSpaceStart() might be above FromSpaceEnd().
2494 Address FromSpacePageLow() { return from_space_.page_low(); }
2495 Address FromSpacePageHigh() { return from_space_.page_high(); }
2496 Address FromSpaceStart() { return from_space_.space_start(); }
2497 Address FromSpaceEnd() { return from_space_.space_end(); }
2499 // Get the extent of the active semispace's pages' memory.
2500 Address ToSpaceStart() { return to_space_.space_start(); }
2501 Address ToSpaceEnd() { return to_space_.space_end(); }
2503 inline bool ToSpaceContains(Address address) {
2504 return to_space_.Contains(address);
2506 inline bool FromSpaceContains(Address address) {
2507 return from_space_.Contains(address);
2510 // True if the object is a heap object in the address range of the
2511 // respective semispace (not necessarily below the allocation pointer of the
2513 inline bool ToSpaceContains(Object* o) { return to_space_.Contains(o); }
2514 inline bool FromSpaceContains(Object* o) { return from_space_.Contains(o); }
2516 // Try to switch the active semispace to a new, empty, page.
2517 // Returns false if this isn't possible or reasonable (i.e., there
2518 // are no pages, or the current page is already empty), or true
2520 bool AddFreshPage();
2523 // Verify the active semispace.
2524 virtual void Verify();
2528 // Print the active semispace.
2529 virtual void Print() { to_space_.Print(); }
2532 // Iterates the active semispace to collect statistics.
2533 void CollectStatistics();
2534 // Reports previously collected statistics of the active semispace.
2535 void ReportStatistics();
2536 // Clears previously collected statistics.
2537 void ClearHistograms();
2539 // Record the allocation or promotion of a heap object. Note that we don't
2540 // record every single allocation, but only those that happen in the
2541 // to space during a scavenge GC.
2542 void RecordAllocation(HeapObject* obj);
2543 void RecordPromotion(HeapObject* obj);
2545 // Return whether the operation succeded.
2546 bool CommitFromSpaceIfNeeded() {
2547 if (from_space_.is_committed()) return true;
2548 return from_space_.Commit();
2551 bool UncommitFromSpace() {
2552 if (!from_space_.is_committed()) return true;
2553 return from_space_.Uncommit();
2556 inline intptr_t inline_allocation_limit_step() {
2557 return inline_allocation_limit_step_;
2560 SemiSpace* active_space() { return &to_space_; }
2563 // Update allocation info to match the current to-space page.
2564 void UpdateAllocationInfo();
2566 Address chunk_base_;
2567 uintptr_t chunk_size_;
2570 SemiSpace to_space_;
2571 SemiSpace from_space_;
2572 base::VirtualMemory reservation_;
2575 // Start address and bit mask for containment testing.
2577 uintptr_t address_mask_;
2578 uintptr_t object_mask_;
2579 uintptr_t object_expected_;
2581 // Allocation pointer and limit for normal allocation and allocation during
2582 // mark-compact collection.
2583 AllocationInfo allocation_info_;
2585 // When incremental marking is active we will set allocation_info_.limit
2586 // to be lower than actual limit and then will gradually increase it
2587 // in steps to guarantee that we do incremental marking steps even
2588 // when all allocation is performed from inlined generated code.
2589 intptr_t inline_allocation_limit_step_;
2591 Address top_on_previous_step_;
2593 HistogramInfo* allocated_histogram_;
2594 HistogramInfo* promoted_histogram_;
2596 MUST_USE_RESULT AllocationResult SlowAllocateRaw(int size_in_bytes);
2598 friend class SemiSpaceIterator;
2601 TRACK_MEMORY("NewSpace")
2605 // -----------------------------------------------------------------------------
2606 // Old object space (excluding map objects)
2608 class OldSpace : public PagedSpace {
2610 // Creates an old space object with a given maximum capacity.
2611 // The constructor does not allocate pages from OS.
2612 OldSpace(Heap* heap, intptr_t max_capacity, AllocationSpace id,
2613 Executability executable)
2614 : PagedSpace(heap, max_capacity, id, executable) {}
2617 TRACK_MEMORY("OldSpace")
2621 // For contiguous spaces, top should be in the space (or at the end) and limit
2622 // should be the end of the space.
2623 #define DCHECK_SEMISPACE_ALLOCATION_INFO(info, space) \
2624 SLOW_DCHECK((space).page_low() <= (info).top() && \
2625 (info).top() <= (space).page_high() && \
2626 (info).limit() <= (space).page_high())
2629 // -----------------------------------------------------------------------------
2630 // Old space for all map objects
2632 class MapSpace : public PagedSpace {
2634 // Creates a map space object with a maximum capacity.
2635 MapSpace(Heap* heap, intptr_t max_capacity, AllocationSpace id)
2636 : PagedSpace(heap, max_capacity, id, NOT_EXECUTABLE),
2637 max_map_space_pages_(kMaxMapPageIndex - 1) {}
2639 // Given an index, returns the page address.
2640 // TODO(1600): this limit is artifical just to keep code compilable
2641 static const int kMaxMapPageIndex = 1 << 16;
2643 virtual int RoundSizeDownToObjectAlignment(int size) {
2644 if (base::bits::IsPowerOfTwo32(Map::kSize)) {
2645 return RoundDown(size, Map::kSize);
2647 return (size / Map::kSize) * Map::kSize;
2652 virtual void VerifyObject(HeapObject* obj);
2655 static const int kMapsPerPage = Page::kMaxRegularHeapObjectSize / Map::kSize;
2657 // Do map space compaction if there is a page gap.
2658 int CompactionThreshold() {
2659 return kMapsPerPage * (max_map_space_pages_ - 1);
2662 const int max_map_space_pages_;
2665 TRACK_MEMORY("MapSpace")
2669 // -----------------------------------------------------------------------------
2670 // Old space for simple property cell objects
2672 class CellSpace : public PagedSpace {
2674 // Creates a property cell space object with a maximum capacity.
2675 CellSpace(Heap* heap, intptr_t max_capacity, AllocationSpace id)
2676 : PagedSpace(heap, max_capacity, id, NOT_EXECUTABLE) {}
2678 virtual int RoundSizeDownToObjectAlignment(int size) {
2679 if (base::bits::IsPowerOfTwo32(Cell::kSize)) {
2680 return RoundDown(size, Cell::kSize);
2682 return (size / Cell::kSize) * Cell::kSize;
2687 virtual void VerifyObject(HeapObject* obj);
2690 TRACK_MEMORY("CellSpace")
2694 // -----------------------------------------------------------------------------
2695 // Large objects ( > Page::kMaxHeapObjectSize ) are allocated and managed by
2696 // the large object space. A large object is allocated from OS heap with
2697 // extra padding bytes (Page::kPageSize + Page::kObjectStartOffset).
2698 // A large object always starts at Page::kObjectStartOffset to a page.
2699 // Large objects do not move during garbage collections.
2701 class LargeObjectSpace : public Space {
2703 LargeObjectSpace(Heap* heap, intptr_t max_capacity, AllocationSpace id);
2704 virtual ~LargeObjectSpace() {}
2706 // Initializes internal data structures.
2709 // Releases internal resources, frees objects in this space.
2712 static intptr_t ObjectSizeFor(intptr_t chunk_size) {
2713 if (chunk_size <= (Page::kPageSize + Page::kObjectStartOffset)) return 0;
2714 return chunk_size - Page::kPageSize - Page::kObjectStartOffset;
2717 // Shared implementation of AllocateRaw, AllocateRawCode and
2718 // AllocateRawFixedArray.
2719 MUST_USE_RESULT AllocationResult
2720 AllocateRaw(int object_size, Executability executable);
2722 bool CanAllocateSize(int size) { return Size() + size <= max_capacity_; }
2724 // Available bytes for objects in this space.
2725 inline intptr_t Available();
2727 virtual intptr_t Size() { return size_; }
2729 virtual intptr_t SizeOfObjects() { return objects_size_; }
2731 intptr_t MaximumCommittedMemory() { return maximum_committed_; }
2733 intptr_t CommittedMemory() { return Size(); }
2735 // Approximate amount of physical memory committed for this space.
2736 size_t CommittedPhysicalMemory();
2738 int PageCount() { return page_count_; }
2740 // Finds an object for a given address, returns a Smi if it is not found.
2741 // The function iterates through all objects in this space, may be slow.
2742 Object* FindObject(Address a);
2744 // Finds a large object page containing the given address, returns NULL
2745 // if such a page doesn't exist.
2746 LargePage* FindPage(Address a);
2748 // Frees unmarked objects.
2749 void FreeUnmarkedObjects();
2751 // Checks whether a heap object is in this space; O(1).
2752 bool Contains(HeapObject* obj);
2754 // Checks whether the space is empty.
2755 bool IsEmpty() { return first_page_ == NULL; }
2757 LargePage* first_page() { return first_page_; }
2760 virtual void Verify();
2764 virtual void Print();
2765 void ReportStatistics();
2766 void CollectCodeStatistics();
2768 // Checks whether an address is in the object area in this space. It
2769 // iterates all objects in the space. May be slow.
2770 bool SlowContains(Address addr) { return FindObject(addr)->IsHeapObject(); }
2773 intptr_t max_capacity_;
2774 intptr_t maximum_committed_;
2775 // The head of the linked list of large object chunks.
2776 LargePage* first_page_;
2777 intptr_t size_; // allocated bytes
2778 int page_count_; // number of chunks
2779 intptr_t objects_size_; // size of objects
2780 // Map MemoryChunk::kAlignment-aligned chunks to large pages covering them
2783 friend class LargeObjectIterator;
2786 TRACK_MEMORY("LargeObjectSpace")
2790 class LargeObjectIterator : public ObjectIterator {
2792 explicit LargeObjectIterator(LargeObjectSpace* space);
2793 LargeObjectIterator(LargeObjectSpace* space, HeapObjectCallback size_func);
2797 // implementation of ObjectIterator.
2798 virtual HeapObject* next_object() { return Next(); }
2801 LargePage* current_;
2802 HeapObjectCallback size_func_;
2806 // Iterates over the chunks (pages and large object pages) that can contain
2807 // pointers to new space.
2808 class PointerChunkIterator BASE_EMBEDDED {
2810 inline explicit PointerChunkIterator(Heap* heap);
2812 // Return NULL when the iterator is done.
2813 MemoryChunk* next() {
2815 case kOldPointerState: {
2816 if (old_pointer_iterator_.has_next()) {
2817 return old_pointer_iterator_.next();
2823 if (map_iterator_.has_next()) {
2824 return map_iterator_.next();
2826 state_ = kLargeObjectState;
2829 case kLargeObjectState: {
2830 HeapObject* heap_object;
2832 heap_object = lo_iterator_.Next();
2833 if (heap_object == NULL) {
2834 state_ = kFinishedState;
2837 // Fixed arrays are the only pointer-containing objects in large
2839 } while (!heap_object->IsFixedArray());
2840 MemoryChunk* answer = MemoryChunk::FromAddress(heap_object->address());
2843 case kFinishedState:
2854 enum State { kOldPointerState, kMapState, kLargeObjectState, kFinishedState };
2856 PageIterator old_pointer_iterator_;
2857 PageIterator map_iterator_;
2858 LargeObjectIterator lo_iterator_;
2863 struct CommentStatistic {
2864 const char* comment;
2872 // Must be small, since an iteration is used for lookup.
2873 static const int kMaxComments = 64;
2877 } // namespace v8::internal
2879 #endif // V8_HEAP_SPACES_H_