blob: 0ca8c398f4e795ec26f4d8013fbb485293189b5c [file] [log] [blame]
Ben Murdoch257744e2011-11-30 15:57:28 +00001// Copyright 2011 the V8 project authors. All rights reserved.
Steve Blocka7e24c12009-10-30 11:49:00 +00002// Redistribution and use in source and binary forms, with or without
3// modification, are permitted provided that the following conditions are
4// met:
5//
6// * Redistributions of source code must retain the above copyright
7// notice, this list of conditions and the following disclaimer.
8// * Redistributions in binary form must reproduce the above
9// copyright notice, this list of conditions and the following
10// disclaimer in the documentation and/or other materials provided
11// with the distribution.
12// * Neither the name of Google Inc. nor the names of its
13// contributors may be used to endorse or promote products derived
14// from this software without specific prior written permission.
15//
16// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
17// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
18// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
19// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
20// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
26// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27
28#ifndef V8_SPACES_H_
29#define V8_SPACES_H_
30
Ben Murdoch257744e2011-11-30 15:57:28 +000031#include "allocation.h"
32#include "list.h"
Steve Blocka7e24c12009-10-30 11:49:00 +000033#include "log.h"
34
35namespace v8 {
36namespace internal {
37
Steve Block44f0eee2011-05-26 01:26:41 +010038class Isolate;
39
Steve Blocka7e24c12009-10-30 11:49:00 +000040// -----------------------------------------------------------------------------
41// Heap structures:
42//
43// A JS heap consists of a young generation, an old generation, and a large
44// object space. The young generation is divided into two semispaces. A
45// scavenger implements Cheney's copying algorithm. The old generation is
46// separated into a map space and an old object space. The map space contains
47// all (and only) map objects, the rest of old objects go into the old space.
48// The old generation is collected by a mark-sweep-compact collector.
49//
50// The semispaces of the young generation are contiguous. The old and map
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +010051// spaces consists of a list of pages. A page has a page header and an object
Ben Murdoch592a9fc2012-03-05 11:04:45 +000052// area.
Steve Blocka7e24c12009-10-30 11:49:00 +000053//
54// There is a separate large object space for objects larger than
55// Page::kMaxHeapObjectSize, so that they do not have to move during
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +010056// collection. The large object space is paged. Pages in large object space
Ben Murdoch592a9fc2012-03-05 11:04:45 +000057// may be larger than the page size.
Steve Blocka7e24c12009-10-30 11:49:00 +000058//
Ben Murdoch592a9fc2012-03-05 11:04:45 +000059// A store-buffer based write barrier is used to keep track of intergenerational
60// references. See store-buffer.h.
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +010061//
Ben Murdoch592a9fc2012-03-05 11:04:45 +000062// During scavenges and mark-sweep collections we sometimes (after a store
63// buffer overflow) iterate intergenerational pointers without decoding heap
64// object maps so if the page belongs to old pointer space or large object
65// space it is essential to guarantee that the page does not contain any
66// garbage pointers to new space: every pointer aligned word which satisfies
67// the Heap::InNewSpace() predicate must be a pointer to a live heap object in
68// new space. Thus objects in old pointer and large object spaces should have a
69// special layout (e.g. no bare integer fields). This requirement does not
70// apply to map space which is iterated in a special fashion. However we still
71// require pointer fields of dead maps to be cleaned.
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +010072//
Ben Murdoch592a9fc2012-03-05 11:04:45 +000073// To enable lazy cleaning of old space pages we can mark chunks of the page
74// as being garbage. Garbage sections are marked with a special map. These
75// sections are skipped when scanning the page, even if we are otherwise
76// scanning without regard for object boundaries. Garbage sections are chained
77// together to form a free list after a GC. Garbage sections created outside
78// of GCs by object trunctation etc. may not be in the free list chain. Very
79// small free spaces are ignored, they need only be cleaned of bogus pointers
80// into new space.
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +010081//
Ben Murdoch592a9fc2012-03-05 11:04:45 +000082// Each page may have up to one special garbage section. The start of this
83// section is denoted by the top field in the space. The end of the section
84// is denoted by the limit field in the space. This special garbage section
85// is not marked with a free space map in the data. The point of this section
86// is to enable linear allocation without having to constantly update the byte
87// array every time the top field is updated and a new object is created. The
88// special garbage section is not in the chain of garbage sections.
89//
90// Since the top and limit fields are in the space, not the page, only one page
91// has a special garbage section, and if the top and limit are equal then there
92// is no special garbage section.
Steve Blocka7e24c12009-10-30 11:49:00 +000093
94// Some assertion macros used in the debugging mode.
95
Leon Clarkee46be812010-01-19 14:06:41 +000096#define ASSERT_PAGE_ALIGNED(address) \
Steve Blocka7e24c12009-10-30 11:49:00 +000097 ASSERT((OffsetFrom(address) & Page::kPageAlignmentMask) == 0)
98
Leon Clarkee46be812010-01-19 14:06:41 +000099#define ASSERT_OBJECT_ALIGNED(address) \
Steve Blocka7e24c12009-10-30 11:49:00 +0000100 ASSERT((OffsetFrom(address) & kObjectAlignmentMask) == 0)
101
Leon Clarkee46be812010-01-19 14:06:41 +0000102#define ASSERT_MAP_ALIGNED(address) \
103 ASSERT((OffsetFrom(address) & kMapAlignmentMask) == 0)
104
105#define ASSERT_OBJECT_SIZE(size) \
Ben Murdoch592a9fc2012-03-05 11:04:45 +0000106 ASSERT((0 < size) && (size <= Page::kMaxNonCodeHeapObjectSize))
Steve Blocka7e24c12009-10-30 11:49:00 +0000107
Leon Clarkee46be812010-01-19 14:06:41 +0000108#define ASSERT_PAGE_OFFSET(offset) \
109 ASSERT((Page::kObjectStartOffset <= offset) \
Steve Blocka7e24c12009-10-30 11:49:00 +0000110 && (offset <= Page::kPageSize))
111
Leon Clarkee46be812010-01-19 14:06:41 +0000112#define ASSERT_MAP_PAGE_INDEX(index) \
Steve Blocka7e24c12009-10-30 11:49:00 +0000113 ASSERT((0 <= index) && (index <= MapSpace::kMaxMapPageIndex))
114
115
116class PagedSpace;
117class MemoryAllocator;
118class AllocationInfo;
Ben Murdoch592a9fc2012-03-05 11:04:45 +0000119class Space;
120class FreeList;
121class MemoryChunk;
122
123class MarkBit {
124 public:
125 typedef uint32_t CellType;
126
127 inline MarkBit(CellType* cell, CellType mask, bool data_only)
128 : cell_(cell), mask_(mask), data_only_(data_only) { }
129
130 inline CellType* cell() { return cell_; }
131 inline CellType mask() { return mask_; }
132
133#ifdef DEBUG
134 bool operator==(const MarkBit& other) {
135 return cell_ == other.cell_ && mask_ == other.mask_;
136 }
137#endif
138
139 inline void Set() { *cell_ |= mask_; }
140 inline bool Get() { return (*cell_ & mask_) != 0; }
141 inline void Clear() { *cell_ &= ~mask_; }
142
143 inline bool data_only() { return data_only_; }
144
145 inline MarkBit Next() {
146 CellType new_mask = mask_ << 1;
147 if (new_mask == 0) {
148 return MarkBit(cell_ + 1, 1, data_only_);
149 } else {
150 return MarkBit(cell_, new_mask, data_only_);
151 }
152 }
153
154 private:
155 CellType* cell_;
156 CellType mask_;
157 // This boolean indicates that the object is in a data-only space with no
158 // pointers. This enables some optimizations when marking.
159 // It is expected that this field is inlined and turned into control flow
160 // at the place where the MarkBit object is created.
161 bool data_only_;
162};
163
164
165// Bitmap is a sequence of cells each containing fixed number of bits.
166class Bitmap {
167 public:
168 static const uint32_t kBitsPerCell = 32;
169 static const uint32_t kBitsPerCellLog2 = 5;
170 static const uint32_t kBitIndexMask = kBitsPerCell - 1;
171 static const uint32_t kBytesPerCell = kBitsPerCell / kBitsPerByte;
172 static const uint32_t kBytesPerCellLog2 = kBitsPerCellLog2 - kBitsPerByteLog2;
173
174 static const size_t kLength =
175 (1 << kPageSizeBits) >> (kPointerSizeLog2);
176
177 static const size_t kSize =
178 (1 << kPageSizeBits) >> (kPointerSizeLog2 + kBitsPerByteLog2);
179
180
181 static int CellsForLength(int length) {
182 return (length + kBitsPerCell - 1) >> kBitsPerCellLog2;
183 }
184
185 int CellsCount() {
186 return CellsForLength(kLength);
187 }
188
189 static int SizeFor(int cells_count) {
190 return sizeof(MarkBit::CellType) * cells_count;
191 }
192
193 INLINE(static uint32_t IndexToCell(uint32_t index)) {
194 return index >> kBitsPerCellLog2;
195 }
196
197 INLINE(static uint32_t CellToIndex(uint32_t index)) {
198 return index << kBitsPerCellLog2;
199 }
200
201 INLINE(static uint32_t CellAlignIndex(uint32_t index)) {
202 return (index + kBitIndexMask) & ~kBitIndexMask;
203 }
204
205 INLINE(MarkBit::CellType* cells()) {
206 return reinterpret_cast<MarkBit::CellType*>(this);
207 }
208
209 INLINE(Address address()) {
210 return reinterpret_cast<Address>(this);
211 }
212
213 INLINE(static Bitmap* FromAddress(Address addr)) {
214 return reinterpret_cast<Bitmap*>(addr);
215 }
216
217 inline MarkBit MarkBitFromIndex(uint32_t index, bool data_only = false) {
218 MarkBit::CellType mask = 1 << (index & kBitIndexMask);
219 MarkBit::CellType* cell = this->cells() + (index >> kBitsPerCellLog2);
220 return MarkBit(cell, mask, data_only);
221 }
222
223 static inline void Clear(MemoryChunk* chunk);
224
225 static void PrintWord(uint32_t word, uint32_t himask = 0) {
226 for (uint32_t mask = 1; mask != 0; mask <<= 1) {
227 if ((mask & himask) != 0) PrintF("[");
228 PrintF((mask & word) ? "1" : "0");
229 if ((mask & himask) != 0) PrintF("]");
230 }
231 }
232
233 class CellPrinter {
234 public:
235 CellPrinter() : seq_start(0), seq_type(0), seq_length(0) { }
236
237 void Print(uint32_t pos, uint32_t cell) {
238 if (cell == seq_type) {
239 seq_length++;
240 return;
241 }
242
243 Flush();
244
245 if (IsSeq(cell)) {
246 seq_start = pos;
247 seq_length = 0;
248 seq_type = cell;
249 return;
250 }
251
252 PrintF("%d: ", pos);
253 PrintWord(cell);
254 PrintF("\n");
255 }
256
257 void Flush() {
258 if (seq_length > 0) {
259 PrintF("%d: %dx%d\n",
260 seq_start,
261 seq_type == 0 ? 0 : 1,
262 seq_length * kBitsPerCell);
263 seq_length = 0;
264 }
265 }
266
267 static bool IsSeq(uint32_t cell) { return cell == 0 || cell == 0xFFFFFFFF; }
268
269 private:
270 uint32_t seq_start;
271 uint32_t seq_type;
272 uint32_t seq_length;
273 };
274
275 void Print() {
276 CellPrinter printer;
277 for (int i = 0; i < CellsCount(); i++) {
278 printer.Print(i, cells()[i]);
279 }
280 printer.Flush();
281 PrintF("\n");
282 }
283
284 bool IsClean() {
285 for (int i = 0; i < CellsCount(); i++) {
286 if (cells()[i] != 0) return false;
287 }
288 return true;
289 }
290};
291
292
293class SkipList;
294class SlotsBuffer;
295
296// MemoryChunk represents a memory region owned by a specific space.
297// It is divided into the header and the body. Chunk start is always
298// 1MB aligned. Start of the body is aligned so it can accomodate
299// any heap object.
300class MemoryChunk {
301 public:
302 // Only works if the pointer is in the first kPageSize of the MemoryChunk.
303 static MemoryChunk* FromAddress(Address a) {
304 return reinterpret_cast<MemoryChunk*>(OffsetFrom(a) & ~kAlignmentMask);
305 }
306
307 // Only works for addresses in pointer spaces, not data or code spaces.
308 static inline MemoryChunk* FromAnyPointerAddress(Address addr);
309
310 Address address() { return reinterpret_cast<Address>(this); }
311
312 bool is_valid() { return address() != NULL; }
313
314 MemoryChunk* next_chunk() const { return next_chunk_; }
315 MemoryChunk* prev_chunk() const { return prev_chunk_; }
316
317 void set_next_chunk(MemoryChunk* next) { next_chunk_ = next; }
318 void set_prev_chunk(MemoryChunk* prev) { prev_chunk_ = prev; }
319
320 Space* owner() const {
321 if ((reinterpret_cast<intptr_t>(owner_) & kFailureTagMask) ==
322 kFailureTag) {
323 return reinterpret_cast<Space*>(owner_ - kFailureTag);
324 } else {
325 return NULL;
326 }
327 }
328
329 void set_owner(Space* space) {
330 ASSERT((reinterpret_cast<intptr_t>(space) & kFailureTagMask) == 0);
331 owner_ = reinterpret_cast<Address>(space) + kFailureTag;
332 ASSERT((reinterpret_cast<intptr_t>(owner_) & kFailureTagMask) ==
333 kFailureTag);
334 }
335
336 VirtualMemory* reserved_memory() {
337 return &reservation_;
338 }
339
340 void InitializeReservedMemory() {
341 reservation_.Reset();
342 }
343
344 void set_reserved_memory(VirtualMemory* reservation) {
345 ASSERT_NOT_NULL(reservation);
346 reservation_.TakeControl(reservation);
347 }
348
349 bool scan_on_scavenge() { return IsFlagSet(SCAN_ON_SCAVENGE); }
350 void initialize_scan_on_scavenge(bool scan) {
351 if (scan) {
352 SetFlag(SCAN_ON_SCAVENGE);
353 } else {
354 ClearFlag(SCAN_ON_SCAVENGE);
355 }
356 }
357 inline void set_scan_on_scavenge(bool scan);
358
359 int store_buffer_counter() { return store_buffer_counter_; }
360 void set_store_buffer_counter(int counter) {
361 store_buffer_counter_ = counter;
362 }
363
364 bool Contains(Address addr) {
365 return addr >= area_start() && addr < area_end();
366 }
367
368 // Checks whether addr can be a limit of addresses in this page.
369 // It's a limit if it's in the page, or if it's just after the
370 // last byte of the page.
371 bool ContainsLimit(Address addr) {
372 return addr >= area_start() && addr <= area_end();
373 }
374
375 enum MemoryChunkFlags {
376 IS_EXECUTABLE,
377 ABOUT_TO_BE_FREED,
378 POINTERS_TO_HERE_ARE_INTERESTING,
379 POINTERS_FROM_HERE_ARE_INTERESTING,
380 SCAN_ON_SCAVENGE,
381 IN_FROM_SPACE, // Mutually exclusive with IN_TO_SPACE.
382 IN_TO_SPACE, // All pages in new space has one of these two set.
383 NEW_SPACE_BELOW_AGE_MARK,
384 CONTAINS_ONLY_DATA,
385 EVACUATION_CANDIDATE,
386 RESCAN_ON_EVACUATION,
387
388 // Pages swept precisely can be iterated, hitting only the live objects.
389 // Whereas those swept conservatively cannot be iterated over. Both flags
390 // indicate that marking bits have been cleared by the sweeper, otherwise
391 // marking bits are still intact.
392 WAS_SWEPT_PRECISELY,
393 WAS_SWEPT_CONSERVATIVELY,
394
395 // Last flag, keep at bottom.
396 NUM_MEMORY_CHUNK_FLAGS
397 };
398
399
400 static const int kPointersToHereAreInterestingMask =
401 1 << POINTERS_TO_HERE_ARE_INTERESTING;
402
403 static const int kPointersFromHereAreInterestingMask =
404 1 << POINTERS_FROM_HERE_ARE_INTERESTING;
405
406 static const int kEvacuationCandidateMask =
407 1 << EVACUATION_CANDIDATE;
408
409 static const int kSkipEvacuationSlotsRecordingMask =
410 (1 << EVACUATION_CANDIDATE) |
411 (1 << RESCAN_ON_EVACUATION) |
412 (1 << IN_FROM_SPACE) |
413 (1 << IN_TO_SPACE);
414
415
416 void SetFlag(int flag) {
417 flags_ |= static_cast<uintptr_t>(1) << flag;
418 }
419
420 void ClearFlag(int flag) {
421 flags_ &= ~(static_cast<uintptr_t>(1) << flag);
422 }
423
424 void SetFlagTo(int flag, bool value) {
425 if (value) {
426 SetFlag(flag);
427 } else {
428 ClearFlag(flag);
429 }
430 }
431
432 bool IsFlagSet(int flag) {
433 return (flags_ & (static_cast<uintptr_t>(1) << flag)) != 0;
434 }
435
436 // Set or clear multiple flags at a time. The flags in the mask
437 // are set to the value in "flags", the rest retain the current value
438 // in flags_.
439 void SetFlags(intptr_t flags, intptr_t mask) {
440 flags_ = (flags_ & ~mask) | (flags & mask);
441 }
442
443 // Return all current flags.
444 intptr_t GetFlags() { return flags_; }
445
446 // Manage live byte count (count of bytes known to be live,
447 // because they are marked black).
448 void ResetLiveBytes() {
449 if (FLAG_gc_verbose) {
450 PrintF("ResetLiveBytes:%p:%x->0\n",
451 static_cast<void*>(this), live_byte_count_);
452 }
453 live_byte_count_ = 0;
454 }
455 void IncrementLiveBytes(int by) {
456 if (FLAG_gc_verbose) {
457 printf("UpdateLiveBytes:%p:%x%c=%x->%x\n",
458 static_cast<void*>(this), live_byte_count_,
459 ((by < 0) ? '-' : '+'), ((by < 0) ? -by : by),
460 live_byte_count_ + by);
461 }
462 live_byte_count_ += by;
463 ASSERT_LE(static_cast<unsigned>(live_byte_count_), size_);
464 }
465 int LiveBytes() {
466 ASSERT(static_cast<unsigned>(live_byte_count_) <= size_);
467 return live_byte_count_;
468 }
469 static void IncrementLiveBytes(Address address, int by) {
470 MemoryChunk::FromAddress(address)->IncrementLiveBytes(by);
471 }
472
473 static const intptr_t kAlignment =
474 (static_cast<uintptr_t>(1) << kPageSizeBits);
475
476 static const intptr_t kAlignmentMask = kAlignment - 1;
477
478 static const intptr_t kSizeOffset = kPointerSize + kPointerSize;
479
480 static const intptr_t kLiveBytesOffset =
481 kSizeOffset + kPointerSize + kPointerSize + kPointerSize +
482 kPointerSize + kPointerSize +
483 kPointerSize + kPointerSize + kPointerSize + kIntSize;
484
485 static const size_t kSlotsBufferOffset = kLiveBytesOffset + kIntSize;
486
487 static const size_t kHeaderSize =
488 kSlotsBufferOffset + kPointerSize + kPointerSize;
489
490 static const int kBodyOffset =
491 CODE_POINTER_ALIGN(MAP_POINTER_ALIGN(kHeaderSize + Bitmap::kSize));
492
493 // The start offset of the object area in a page. Aligned to both maps and
494 // code alignment to be suitable for both. Also aligned to 32 words because
495 // the marking bitmap is arranged in 32 bit chunks.
496 static const int kObjectStartAlignment = 32 * kPointerSize;
497 static const int kObjectStartOffset = kBodyOffset - 1 +
498 (kObjectStartAlignment - (kBodyOffset - 1) % kObjectStartAlignment);
499
500 size_t size() const { return size_; }
501
502 void set_size(size_t size) {
503 size_ = size;
504 }
505
506 Executability executable() {
507 return IsFlagSet(IS_EXECUTABLE) ? EXECUTABLE : NOT_EXECUTABLE;
508 }
509
510 bool ContainsOnlyData() {
511 return IsFlagSet(CONTAINS_ONLY_DATA);
512 }
513
514 bool InNewSpace() {
515 return (flags_ & ((1 << IN_FROM_SPACE) | (1 << IN_TO_SPACE))) != 0;
516 }
517
518 bool InToSpace() {
519 return IsFlagSet(IN_TO_SPACE);
520 }
521
522 bool InFromSpace() {
523 return IsFlagSet(IN_FROM_SPACE);
524 }
525
526 // ---------------------------------------------------------------------
527 // Markbits support
528
529 inline Bitmap* markbits() {
530 return Bitmap::FromAddress(address() + kHeaderSize);
531 }
532
533 void PrintMarkbits() { markbits()->Print(); }
534
535 inline uint32_t AddressToMarkbitIndex(Address addr) {
536 return static_cast<uint32_t>(addr - this->address()) >> kPointerSizeLog2;
537 }
538
539 inline static uint32_t FastAddressToMarkbitIndex(Address addr) {
540 const intptr_t offset =
541 reinterpret_cast<intptr_t>(addr) & kAlignmentMask;
542
543 return static_cast<uint32_t>(offset) >> kPointerSizeLog2;
544 }
545
546 inline Address MarkbitIndexToAddress(uint32_t index) {
547 return this->address() + (index << kPointerSizeLog2);
548 }
549
550 void InsertAfter(MemoryChunk* other);
551 void Unlink();
552
553 inline Heap* heap() { return heap_; }
554
555 static const int kFlagsOffset = kPointerSize * 3;
556
557 bool IsEvacuationCandidate() { return IsFlagSet(EVACUATION_CANDIDATE); }
558
559 bool ShouldSkipEvacuationSlotRecording() {
560 return (flags_ & kSkipEvacuationSlotsRecordingMask) != 0;
561 }
562
563 inline SkipList* skip_list() {
564 return skip_list_;
565 }
566
567 inline void set_skip_list(SkipList* skip_list) {
568 skip_list_ = skip_list;
569 }
570
571 inline SlotsBuffer* slots_buffer() {
572 return slots_buffer_;
573 }
574
575 inline SlotsBuffer** slots_buffer_address() {
576 return &slots_buffer_;
577 }
578
579 void MarkEvacuationCandidate() {
580 ASSERT(slots_buffer_ == NULL);
581 SetFlag(EVACUATION_CANDIDATE);
582 }
583
584 void ClearEvacuationCandidate() {
585 ASSERT(slots_buffer_ == NULL);
586 ClearFlag(EVACUATION_CANDIDATE);
587 }
588
589 Address area_start() { return area_start_; }
590 Address area_end() { return area_end_; }
591 int area_size() {
592 return static_cast<int>(area_end() - area_start());
593 }
594
595 protected:
596 MemoryChunk* next_chunk_;
597 MemoryChunk* prev_chunk_;
598 size_t size_;
599 intptr_t flags_;
600
601 // Start and end of allocatable memory on this chunk.
602 Address area_start_;
603 Address area_end_;
604
605 // If the chunk needs to remember its memory reservation, it is stored here.
606 VirtualMemory reservation_;
607 // The identity of the owning space. This is tagged as a failure pointer, but
608 // no failure can be in an object, so this can be distinguished from any entry
609 // in a fixed array.
610 Address owner_;
611 Heap* heap_;
612 // Used by the store buffer to keep track of which pages to mark scan-on-
613 // scavenge.
614 int store_buffer_counter_;
615 // Count of bytes marked black on page.
616 int live_byte_count_;
617 SlotsBuffer* slots_buffer_;
618 SkipList* skip_list_;
619
620 static MemoryChunk* Initialize(Heap* heap,
621 Address base,
622 size_t size,
623 Address area_start,
624 Address area_end,
625 Executability executable,
626 Space* owner);
627
628 friend class MemoryAllocator;
629};
630
631STATIC_CHECK(sizeof(MemoryChunk) <= MemoryChunk::kHeaderSize);
Steve Blocka7e24c12009-10-30 11:49:00 +0000632
633// -----------------------------------------------------------------------------
Ben Murdoch592a9fc2012-03-05 11:04:45 +0000634// A page is a memory chunk of a size 1MB. Large object pages may be larger.
Steve Blocka7e24c12009-10-30 11:49:00 +0000635//
636// The only way to get a page pointer is by calling factory methods:
637// Page* p = Page::FromAddress(addr); or
638// Page* p = Page::FromAllocationTop(top);
Ben Murdoch592a9fc2012-03-05 11:04:45 +0000639class Page : public MemoryChunk {
Steve Blocka7e24c12009-10-30 11:49:00 +0000640 public:
641 // Returns the page containing a given address. The address ranges
642 // from [page_addr .. page_addr + kPageSize[
Ben Murdoch592a9fc2012-03-05 11:04:45 +0000643 // This only works if the object is in fact in a page. See also MemoryChunk::
644 // FromAddress() and FromAnyAddress().
Steve Blocka7e24c12009-10-30 11:49:00 +0000645 INLINE(static Page* FromAddress(Address a)) {
646 return reinterpret_cast<Page*>(OffsetFrom(a) & ~kPageAlignmentMask);
647 }
648
649 // Returns the page containing an allocation top. Because an allocation
650 // top address can be the upper bound of the page, we need to subtract
651 // it with kPointerSize first. The address ranges from
652 // [page_addr + kObjectStartOffset .. page_addr + kPageSize].
653 INLINE(static Page* FromAllocationTop(Address top)) {
654 Page* p = FromAddress(top - kPointerSize);
Steve Blocka7e24c12009-10-30 11:49:00 +0000655 return p;
656 }
657
Ben Murdoch592a9fc2012-03-05 11:04:45 +0000658 // Returns the next page in the chain of pages owned by a space.
Steve Blocka7e24c12009-10-30 11:49:00 +0000659 inline Page* next_page();
Ben Murdoch592a9fc2012-03-05 11:04:45 +0000660 inline Page* prev_page();
661 inline void set_next_page(Page* page);
662 inline void set_prev_page(Page* page);
Steve Blocka7e24c12009-10-30 11:49:00 +0000663
Steve Blocka7e24c12009-10-30 11:49:00 +0000664 // Checks whether an address is page aligned.
665 static bool IsAlignedToPageSize(Address a) {
666 return 0 == (OffsetFrom(a) & kPageAlignmentMask);
667 }
668
Steve Blocka7e24c12009-10-30 11:49:00 +0000669 // Returns the offset of a given address to this page.
670 INLINE(int Offset(Address a)) {
Steve Blockd0582a62009-12-15 09:54:21 +0000671 int offset = static_cast<int>(a - address());
Steve Blocka7e24c12009-10-30 11:49:00 +0000672 return offset;
673 }
674
675 // Returns the address for a given offset to the this page.
676 Address OffsetToAddress(int offset) {
677 ASSERT_PAGE_OFFSET(offset);
678 return address() + offset;
679 }
680
681 // ---------------------------------------------------------------------
Steve Blocka7e24c12009-10-30 11:49:00 +0000682
Steve Blocka7e24c12009-10-30 11:49:00 +0000683 // Page size in bytes. This must be a multiple of the OS page size.
684 static const int kPageSize = 1 << kPageSizeBits;
685
Ben Murdoch592a9fc2012-03-05 11:04:45 +0000686 // Object area size in bytes.
687 static const int kNonCodeObjectAreaSize = kPageSize - kObjectStartOffset;
688
689 // Maximum object size that fits in a page.
690 static const int kMaxNonCodeHeapObjectSize = kNonCodeObjectAreaSize;
691
Steve Blocka7e24c12009-10-30 11:49:00 +0000692 // Page size mask.
693 static const intptr_t kPageAlignmentMask = (1 << kPageSizeBits) - 1;
694
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +0100695 inline void ClearGCFields();
696
Ben Murdoch592a9fc2012-03-05 11:04:45 +0000697 static inline Page* Initialize(Heap* heap,
698 MemoryChunk* chunk,
699 Executability executable,
700 PagedSpace* owner);
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +0100701
Ben Murdoch592a9fc2012-03-05 11:04:45 +0000702 void InitializeAsAnchor(PagedSpace* owner);
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +0100703
Ben Murdoch592a9fc2012-03-05 11:04:45 +0000704 bool WasSweptPrecisely() { return IsFlagSet(WAS_SWEPT_PRECISELY); }
705 bool WasSweptConservatively() { return IsFlagSet(WAS_SWEPT_CONSERVATIVELY); }
706 bool WasSwept() { return WasSweptPrecisely() || WasSweptConservatively(); }
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +0100707
Ben Murdoch592a9fc2012-03-05 11:04:45 +0000708 void MarkSweptPrecisely() { SetFlag(WAS_SWEPT_PRECISELY); }
709 void MarkSweptConservatively() { SetFlag(WAS_SWEPT_CONSERVATIVELY); }
Steve Blocka7e24c12009-10-30 11:49:00 +0000710
Ben Murdoch592a9fc2012-03-05 11:04:45 +0000711 void ClearSweptPrecisely() { ClearFlag(WAS_SWEPT_PRECISELY); }
712 void ClearSweptConservatively() { ClearFlag(WAS_SWEPT_CONSERVATIVELY); }
Steve Blocka7e24c12009-10-30 11:49:00 +0000713
Ben Murdoch592a9fc2012-03-05 11:04:45 +0000714#ifdef DEBUG
715 void Print();
716#endif // DEBUG
Steve Blocka7e24c12009-10-30 11:49:00 +0000717
Ben Murdoch592a9fc2012-03-05 11:04:45 +0000718 friend class MemoryAllocator;
Steve Blocka7e24c12009-10-30 11:49:00 +0000719};
720
721
Ben Murdoch592a9fc2012-03-05 11:04:45 +0000722STATIC_CHECK(sizeof(Page) <= MemoryChunk::kHeaderSize);
723
724
725class LargePage : public MemoryChunk {
726 public:
727 HeapObject* GetObject() {
728 return HeapObject::FromAddress(area_start());
729 }
730
731 inline LargePage* next_page() const {
732 return static_cast<LargePage*>(next_chunk());
733 }
734
735 inline void set_next_page(LargePage* page) {
736 set_next_chunk(page);
737 }
738 private:
739 static inline LargePage* Initialize(Heap* heap, MemoryChunk* chunk);
740
741 friend class MemoryAllocator;
742};
743
744STATIC_CHECK(sizeof(LargePage) <= MemoryChunk::kHeaderSize);
745
Steve Blocka7e24c12009-10-30 11:49:00 +0000746// ----------------------------------------------------------------------------
747// Space is the abstract superclass for all allocation spaces.
748class Space : public Malloced {
749 public:
Steve Block44f0eee2011-05-26 01:26:41 +0100750 Space(Heap* heap, AllocationSpace id, Executability executable)
751 : heap_(heap), id_(id), executable_(executable) {}
Steve Blocka7e24c12009-10-30 11:49:00 +0000752
753 virtual ~Space() {}
754
Steve Block44f0eee2011-05-26 01:26:41 +0100755 Heap* heap() const { return heap_; }
756
Steve Blocka7e24c12009-10-30 11:49:00 +0000757 // Does the space need executable memory?
758 Executability executable() { return executable_; }
759
760 // Identity used in error reporting.
761 AllocationSpace identity() { return id_; }
762
Shimeng (Simon) Wang8a31eba2010-12-06 19:01:33 -0800763 // Returns allocated size.
Ben Murdochf87a2032010-10-22 12:50:53 +0100764 virtual intptr_t Size() = 0;
Steve Blocka7e24c12009-10-30 11:49:00 +0000765
Shimeng (Simon) Wang8a31eba2010-12-06 19:01:33 -0800766 // Returns size of objects. Can differ from the allocated size
767 // (e.g. see LargeObjectSpace).
768 virtual intptr_t SizeOfObjects() { return Size(); }
769
Ben Murdoch592a9fc2012-03-05 11:04:45 +0000770 virtual int RoundSizeDownToObjectAlignment(int size) {
771 if (id_ == CODE_SPACE) {
772 return RoundDown(size, kCodeAlignment);
773 } else {
774 return RoundDown(size, kPointerSize);
775 }
776 }
777
Steve Blocka7e24c12009-10-30 11:49:00 +0000778#ifdef DEBUG
779 virtual void Print() = 0;
780#endif
781
Leon Clarkee46be812010-01-19 14:06:41 +0000782 // After calling this we can allocate a certain number of bytes using only
783 // linear allocation (with a LinearAllocationScope and an AlwaysAllocateScope)
784 // without using freelists or causing a GC. This is used by partial
785 // snapshots. It returns true of space was reserved or false if a GC is
786 // needed. For paged spaces the space requested must include the space wasted
787 // at the end of each when allocating linearly.
788 virtual bool ReserveSpace(int bytes) = 0;
789
Steve Blocka7e24c12009-10-30 11:49:00 +0000790 private:
Steve Block44f0eee2011-05-26 01:26:41 +0100791 Heap* heap_;
Steve Blocka7e24c12009-10-30 11:49:00 +0000792 AllocationSpace id_;
793 Executability executable_;
794};
795
796
797// ----------------------------------------------------------------------------
798// All heap objects containing executable code (code objects) must be allocated
799// from a 2 GB range of memory, so that they can call each other using 32-bit
800// displacements. This happens automatically on 32-bit platforms, where 32-bit
801// displacements cover the entire 4GB virtual address space. On 64-bit
802// platforms, we support this using the CodeRange object, which reserves and
803// manages a range of virtual memory.
Steve Block44f0eee2011-05-26 01:26:41 +0100804class CodeRange {
Steve Blocka7e24c12009-10-30 11:49:00 +0000805 public:
Ben Murdoch69a99ed2011-11-30 16:03:39 +0000806 explicit CodeRange(Isolate* isolate);
807 ~CodeRange() { TearDown(); }
808
Steve Blocka7e24c12009-10-30 11:49:00 +0000809 // Reserves a range of virtual memory, but does not commit any of it.
810 // Can only be called once, at heap initialization time.
811 // Returns false on failure.
Steve Block44f0eee2011-05-26 01:26:41 +0100812 bool Setup(const size_t requested_size);
Steve Blocka7e24c12009-10-30 11:49:00 +0000813
814 // Frees the range of virtual memory, and frees the data structures used to
815 // manage it.
Steve Block44f0eee2011-05-26 01:26:41 +0100816 void TearDown();
Steve Blocka7e24c12009-10-30 11:49:00 +0000817
Ben Murdoch69a99ed2011-11-30 16:03:39 +0000818 bool exists() { return this != NULL && code_range_ != NULL; }
Steve Block44f0eee2011-05-26 01:26:41 +0100819 bool contains(Address address) {
Ben Murdoch69a99ed2011-11-30 16:03:39 +0000820 if (this == NULL || code_range_ == NULL) return false;
Steve Blocka7e24c12009-10-30 11:49:00 +0000821 Address start = static_cast<Address>(code_range_->address());
822 return start <= address && address < start + code_range_->size();
823 }
824
825 // Allocates a chunk of memory from the large-object portion of
826 // the code range. On platforms with no separate code range, should
827 // not be called.
Ben Murdoch592a9fc2012-03-05 11:04:45 +0000828 MUST_USE_RESULT Address AllocateRawMemory(const size_t requested,
829 size_t* allocated);
830 void FreeRawMemory(Address buf, size_t length);
Steve Blocka7e24c12009-10-30 11:49:00 +0000831
832 private:
Ben Murdoch69a99ed2011-11-30 16:03:39 +0000833 Isolate* isolate_;
Steve Block44f0eee2011-05-26 01:26:41 +0100834
Steve Blocka7e24c12009-10-30 11:49:00 +0000835 // The reserved range of virtual memory that all code objects are put in.
Steve Block44f0eee2011-05-26 01:26:41 +0100836 VirtualMemory* code_range_;
Steve Blocka7e24c12009-10-30 11:49:00 +0000837 // Plain old data class, just a struct plus a constructor.
838 class FreeBlock {
839 public:
840 FreeBlock(Address start_arg, size_t size_arg)
Ben Murdoch592a9fc2012-03-05 11:04:45 +0000841 : start(start_arg), size(size_arg) {
842 ASSERT(IsAddressAligned(start, MemoryChunk::kAlignment));
843 ASSERT(size >= static_cast<size_t>(Page::kPageSize));
844 }
Steve Blocka7e24c12009-10-30 11:49:00 +0000845 FreeBlock(void* start_arg, size_t size_arg)
Ben Murdoch592a9fc2012-03-05 11:04:45 +0000846 : start(static_cast<Address>(start_arg)), size(size_arg) {
847 ASSERT(IsAddressAligned(start, MemoryChunk::kAlignment));
848 ASSERT(size >= static_cast<size_t>(Page::kPageSize));
849 }
Steve Blocka7e24c12009-10-30 11:49:00 +0000850
851 Address start;
852 size_t size;
853 };
854
855 // Freed blocks of memory are added to the free list. When the allocation
856 // list is exhausted, the free list is sorted and merged to make the new
857 // allocation list.
Steve Block44f0eee2011-05-26 01:26:41 +0100858 List<FreeBlock> free_list_;
Steve Blocka7e24c12009-10-30 11:49:00 +0000859 // Memory is allocated from the free blocks on the allocation list.
860 // The block at current_allocation_block_index_ is the current block.
Steve Block44f0eee2011-05-26 01:26:41 +0100861 List<FreeBlock> allocation_list_;
862 int current_allocation_block_index_;
Steve Blocka7e24c12009-10-30 11:49:00 +0000863
864 // Finds a block on the allocation list that contains at least the
865 // requested amount of memory. If none is found, sorts and merges
866 // the existing free memory blocks, and searches again.
867 // If none can be found, terminates V8 with FatalProcessOutOfMemory.
Steve Block44f0eee2011-05-26 01:26:41 +0100868 void GetNextAllocationBlock(size_t requested);
Steve Blocka7e24c12009-10-30 11:49:00 +0000869 // Compares the start addresses of two free blocks.
870 static int CompareFreeBlockAddress(const FreeBlock* left,
871 const FreeBlock* right);
Steve Block44f0eee2011-05-26 01:26:41 +0100872
Steve Block44f0eee2011-05-26 01:26:41 +0100873 DISALLOW_COPY_AND_ASSIGN(CodeRange);
Steve Blocka7e24c12009-10-30 11:49:00 +0000874};
875
876
Ben Murdoch592a9fc2012-03-05 11:04:45 +0000877class SkipList {
878 public:
879 SkipList() {
880 Clear();
881 }
882
883 void Clear() {
884 for (int idx = 0; idx < kSize; idx++) {
885 starts_[idx] = reinterpret_cast<Address>(-1);
886 }
887 }
888
889 Address StartFor(Address addr) {
890 return starts_[RegionNumber(addr)];
891 }
892
893 void AddObject(Address addr, int size) {
894 int start_region = RegionNumber(addr);
895 int end_region = RegionNumber(addr + size - kPointerSize);
896 for (int idx = start_region; idx <= end_region; idx++) {
897 if (starts_[idx] > addr) starts_[idx] = addr;
898 }
899 }
900
901 static inline int RegionNumber(Address addr) {
902 return (OffsetFrom(addr) & Page::kPageAlignmentMask) >> kRegionSizeLog2;
903 }
904
905 static void Update(Address addr, int size) {
906 Page* page = Page::FromAddress(addr);
907 SkipList* list = page->skip_list();
908 if (list == NULL) {
909 list = new SkipList();
910 page->set_skip_list(list);
911 }
912
913 list->AddObject(addr, size);
914 }
915
916 private:
917 static const int kRegionSizeLog2 = 13;
918 static const int kRegionSize = 1 << kRegionSizeLog2;
919 static const int kSize = Page::kPageSize / kRegionSize;
920
921 STATIC_ASSERT(Page::kPageSize % kRegionSize == 0);
922
923 Address starts_[kSize];
924};
925
926
Steve Blocka7e24c12009-10-30 11:49:00 +0000927// ----------------------------------------------------------------------------
928// A space acquires chunks of memory from the operating system. The memory
Ben Murdoch592a9fc2012-03-05 11:04:45 +0000929// allocator allocated and deallocates pages for the paged heap spaces and large
930// pages for large object space.
Steve Blocka7e24c12009-10-30 11:49:00 +0000931//
Ben Murdoch592a9fc2012-03-05 11:04:45 +0000932// Each space has to manage it's own pages.
Steve Blocka7e24c12009-10-30 11:49:00 +0000933//
Steve Block44f0eee2011-05-26 01:26:41 +0100934class MemoryAllocator {
Steve Blocka7e24c12009-10-30 11:49:00 +0000935 public:
Ben Murdoch69a99ed2011-11-30 16:03:39 +0000936 explicit MemoryAllocator(Isolate* isolate);
937
Steve Blocka7e24c12009-10-30 11:49:00 +0000938 // Initializes its internal bookkeeping structures.
Russell Brenner90bac252010-11-18 13:33:46 -0800939 // Max capacity of the total space and executable memory limit.
Steve Block44f0eee2011-05-26 01:26:41 +0100940 bool Setup(intptr_t max_capacity, intptr_t capacity_executable);
Steve Blocka7e24c12009-10-30 11:49:00 +0000941
Steve Block44f0eee2011-05-26 01:26:41 +0100942 void TearDown();
Steve Blocka7e24c12009-10-30 11:49:00 +0000943
Ben Murdoch592a9fc2012-03-05 11:04:45 +0000944 Page* AllocatePage(PagedSpace* owner, Executability executable);
Steve Blocka7e24c12009-10-30 11:49:00 +0000945
Ben Murdoch592a9fc2012-03-05 11:04:45 +0000946 LargePage* AllocateLargePage(intptr_t object_size,
947 Executability executable,
948 Space* owner);
Steve Blocka7e24c12009-10-30 11:49:00 +0000949
Ben Murdoch592a9fc2012-03-05 11:04:45 +0000950 void Free(MemoryChunk* chunk);
Steve Blocka7e24c12009-10-30 11:49:00 +0000951
952 // Returns the maximum available bytes of heaps.
Steve Block44f0eee2011-05-26 01:26:41 +0100953 intptr_t Available() { return capacity_ < size_ ? 0 : capacity_ - size_; }
Steve Blocka7e24c12009-10-30 11:49:00 +0000954
955 // Returns allocated spaces in bytes.
Steve Block44f0eee2011-05-26 01:26:41 +0100956 intptr_t Size() { return size_; }
Steve Blocka7e24c12009-10-30 11:49:00 +0000957
Russell Brenner90bac252010-11-18 13:33:46 -0800958 // Returns the maximum available executable bytes of heaps.
Steve Block44f0eee2011-05-26 01:26:41 +0100959 intptr_t AvailableExecutable() {
Russell Brenner90bac252010-11-18 13:33:46 -0800960 if (capacity_executable_ < size_executable_) return 0;
961 return capacity_executable_ - size_executable_;
962 }
963
Steve Block791712a2010-08-27 10:21:07 +0100964 // Returns allocated executable spaces in bytes.
Steve Block44f0eee2011-05-26 01:26:41 +0100965 intptr_t SizeExecutable() { return size_executable_; }
Steve Block791712a2010-08-27 10:21:07 +0100966
Steve Blocka7e24c12009-10-30 11:49:00 +0000967 // Returns maximum available bytes that the old space can have.
Steve Block44f0eee2011-05-26 01:26:41 +0100968 intptr_t MaxAvailable() {
Ben Murdoch592a9fc2012-03-05 11:04:45 +0000969 return (Available() / Page::kPageSize) * Page::kMaxNonCodeHeapObjectSize;
Steve Blocka7e24c12009-10-30 11:49:00 +0000970 }
971
Steve Blocka7e24c12009-10-30 11:49:00 +0000972#ifdef DEBUG
973 // Reports statistic info of the space.
Steve Block44f0eee2011-05-26 01:26:41 +0100974 void ReportStatistics();
Steve Blocka7e24c12009-10-30 11:49:00 +0000975#endif
976
Ben Murdoch592a9fc2012-03-05 11:04:45 +0000977 MemoryChunk* AllocateChunk(intptr_t body_size,
978 Executability executable,
979 Space* space);
980
981 Address ReserveAlignedMemory(size_t requested,
982 size_t alignment,
983 VirtualMemory* controller);
984 Address AllocateAlignedMemory(size_t requested,
985 size_t alignment,
986 Executability executable,
987 VirtualMemory* controller);
988
989 void FreeMemory(VirtualMemory* reservation, Executability executable);
990 void FreeMemory(Address addr, size_t size, Executability executable);
991
992 // Commit a contiguous block of memory from the initial chunk. Assumes that
993 // the address is not NULL, the size is greater than zero, and that the
994 // block is contained in the initial chunk. Returns true if it succeeded
995 // and false otherwise.
996 bool CommitBlock(Address start, size_t size, Executability executable);
997
998 // Uncommit a contiguous block of memory [start..(start+size)[.
999 // start is not NULL, the size is greater than zero, and the
1000 // block is contained in the initial chunk. Returns true if it succeeded
1001 // and false otherwise.
1002 bool UncommitBlock(Address start, size_t size);
1003
1004 // Zaps a contiguous block of memory [start..(start+size)[ thus
1005 // filling it up with a recognizable non-NULL bit pattern.
1006 void ZapBlock(Address start, size_t size);
1007
1008 void PerformAllocationCallback(ObjectSpace space,
1009 AllocationAction action,
1010 size_t size);
1011
1012 void AddMemoryAllocationCallback(MemoryAllocationCallback callback,
1013 ObjectSpace space,
1014 AllocationAction action);
1015
1016 void RemoveMemoryAllocationCallback(
1017 MemoryAllocationCallback callback);
1018
1019 bool MemoryAllocationCallbackRegistered(
1020 MemoryAllocationCallback callback);
1021
1022 static int CodePageGuardStartOffset();
1023
1024 static int CodePageGuardSize();
1025
1026 static int CodePageAreaStartOffset();
1027
1028 static int CodePageAreaEndOffset();
1029
1030 static int CodePageAreaSize() {
1031 return CodePageAreaEndOffset() - CodePageAreaStartOffset();
1032 }
1033
1034 static bool CommitCodePage(VirtualMemory* vm, Address start, size_t size);
Steve Blocka7e24c12009-10-30 11:49:00 +00001035
1036 private:
Ben Murdoch69a99ed2011-11-30 16:03:39 +00001037 Isolate* isolate_;
1038
Steve Blocka7e24c12009-10-30 11:49:00 +00001039 // Maximum space size in bytes.
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001040 size_t capacity_;
Russell Brenner90bac252010-11-18 13:33:46 -08001041 // Maximum subset of capacity_ that can be executable
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001042 size_t capacity_executable_;
Ben Murdochb0fe1622011-05-05 13:52:32 +01001043
Steve Blocka7e24c12009-10-30 11:49:00 +00001044 // Allocated space size in bytes.
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001045 size_t size_;
Steve Block791712a2010-08-27 10:21:07 +01001046 // Allocated executable space size in bytes.
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001047 size_t size_executable_;
Steve Blocka7e24c12009-10-30 11:49:00 +00001048
Iain Merrick9ac36c92010-09-13 15:29:50 +01001049 struct MemoryAllocationCallbackRegistration {
1050 MemoryAllocationCallbackRegistration(MemoryAllocationCallback callback,
1051 ObjectSpace space,
1052 AllocationAction action)
1053 : callback(callback), space(space), action(action) {
1054 }
1055 MemoryAllocationCallback callback;
1056 ObjectSpace space;
1057 AllocationAction action;
1058 };
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001059
Iain Merrick9ac36c92010-09-13 15:29:50 +01001060 // A List of callback that are triggered when memory is allocated or free'd
Steve Block44f0eee2011-05-26 01:26:41 +01001061 List<MemoryAllocationCallbackRegistration>
Iain Merrick9ac36c92010-09-13 15:29:50 +01001062 memory_allocation_callbacks_;
1063
Steve Blocka7e24c12009-10-30 11:49:00 +00001064 // Initializes pages in a chunk. Returns the first page address.
1065 // This function and GetChunkId() are provided for the mark-compact
1066 // collector to rebuild page headers in the from space, which is
1067 // used as a marking stack and its page headers are destroyed.
Steve Block44f0eee2011-05-26 01:26:41 +01001068 Page* InitializePagesInChunk(int chunk_id, int pages_in_chunk,
1069 PagedSpace* owner);
Steve Block6ded16b2010-05-10 14:33:55 +01001070
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001071 DISALLOW_IMPLICIT_CONSTRUCTORS(MemoryAllocator);
Steve Blocka7e24c12009-10-30 11:49:00 +00001072};
1073
1074
1075// -----------------------------------------------------------------------------
1076// Interface for heap object iterator to be implemented by all object space
1077// object iterators.
1078//
Leon Clarked91b9f72010-01-27 17:25:45 +00001079// NOTE: The space specific object iterators also implements the own next()
1080// method which is used to avoid using virtual functions
Steve Blocka7e24c12009-10-30 11:49:00 +00001081// iterating a specific space.
1082
1083class ObjectIterator : public Malloced {
1084 public:
1085 virtual ~ObjectIterator() { }
1086
Steve Blocka7e24c12009-10-30 11:49:00 +00001087 virtual HeapObject* next_object() = 0;
1088};
1089
1090
1091// -----------------------------------------------------------------------------
1092// Heap object iterator in new/old/map spaces.
1093//
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001094// A HeapObjectIterator iterates objects from the bottom of the given space
1095// to its top or from the bottom of the given page to its top.
Steve Blocka7e24c12009-10-30 11:49:00 +00001096//
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001097// If objects are allocated in the page during iteration the iterator may
1098// or may not iterate over those objects. The caller must create a new
1099// iterator in order to be sure to visit these new objects.
Steve Blocka7e24c12009-10-30 11:49:00 +00001100class HeapObjectIterator: public ObjectIterator {
1101 public:
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001102 // Creates a new object iterator in a given space.
Steve Blocka7e24c12009-10-30 11:49:00 +00001103 // If the size function is not given, the iterator calls the default
1104 // Object::Size().
1105 explicit HeapObjectIterator(PagedSpace* space);
1106 HeapObjectIterator(PagedSpace* space, HeapObjectCallback size_func);
Kristian Monsen80d68ea2010-09-08 11:05:35 +01001107 HeapObjectIterator(Page* page, HeapObjectCallback size_func);
Steve Blocka7e24c12009-10-30 11:49:00 +00001108
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001109 // Advance to the next object, skipping free spaces and other fillers and
1110 // skipping the special garbage section of which there is one per space.
1111 // Returns NULL when the iteration has ended.
1112 inline HeapObject* Next() {
1113 do {
1114 HeapObject* next_obj = FromCurrentPage();
1115 if (next_obj != NULL) return next_obj;
1116 } while (AdvanceToNextPage());
1117 return NULL;
Leon Clarked91b9f72010-01-27 17:25:45 +00001118 }
Steve Blocka7e24c12009-10-30 11:49:00 +00001119
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001120 virtual HeapObject* next_object() {
1121 return Next();
1122 }
Steve Blocka7e24c12009-10-30 11:49:00 +00001123
1124 private:
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001125 enum PageMode { kOnePageOnly, kAllPagesInSpace };
Steve Blocka7e24c12009-10-30 11:49:00 +00001126
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001127 Address cur_addr_; // Current iteration point.
1128 Address cur_end_; // End iteration point.
1129 HeapObjectCallback size_func_; // Size function or NULL.
1130 PagedSpace* space_;
1131 PageMode page_mode_;
Leon Clarked91b9f72010-01-27 17:25:45 +00001132
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001133 // Fast (inlined) path of next().
1134 inline HeapObject* FromCurrentPage();
Leon Clarked91b9f72010-01-27 17:25:45 +00001135
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001136 // Slow path of next(), goes into the next page. Returns false if the
1137 // iteration has ended.
1138 bool AdvanceToNextPage();
Steve Blocka7e24c12009-10-30 11:49:00 +00001139
1140 // Initializes fields.
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001141 inline void Initialize(PagedSpace* owner,
1142 Address start,
1143 Address end,
1144 PageMode mode,
1145 HeapObjectCallback size_func);
Steve Blocka7e24c12009-10-30 11:49:00 +00001146};
1147
1148
1149// -----------------------------------------------------------------------------
1150// A PageIterator iterates the pages in a paged space.
Steve Blocka7e24c12009-10-30 11:49:00 +00001151
1152class PageIterator BASE_EMBEDDED {
1153 public:
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001154 explicit inline PageIterator(PagedSpace* space);
Steve Blocka7e24c12009-10-30 11:49:00 +00001155
1156 inline bool has_next();
1157 inline Page* next();
1158
1159 private:
1160 PagedSpace* space_;
1161 Page* prev_page_; // Previous page returned.
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001162 // Next page that will be returned. Cached here so that we can use this
1163 // iterator for operations that deallocate pages.
1164 Page* next_page_;
Steve Blocka7e24c12009-10-30 11:49:00 +00001165};
1166
1167
1168// -----------------------------------------------------------------------------
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001169// A space has a circular list of pages. The next page can be accessed via
1170// Page::next_page() call.
Steve Blocka7e24c12009-10-30 11:49:00 +00001171
1172// An abstraction of allocation and relocation pointers in a page-structured
1173// space.
1174class AllocationInfo {
1175 public:
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001176 AllocationInfo() : top(NULL), limit(NULL) {
1177 }
1178
1179 Address top; // Current allocation top.
1180 Address limit; // Current allocation limit.
Steve Blocka7e24c12009-10-30 11:49:00 +00001181
1182#ifdef DEBUG
1183 bool VerifyPagedAllocation() {
1184 return (Page::FromAllocationTop(top) == Page::FromAllocationTop(limit))
1185 && (top <= limit);
1186 }
1187#endif
1188};
1189
1190
1191// An abstraction of the accounting statistics of a page-structured space.
1192// The 'capacity' of a space is the number of object-area bytes (ie, not
1193// including page bookkeeping structures) currently in the space. The 'size'
1194// of a space is the number of allocated bytes, the 'waste' in the space is
1195// the number of bytes that are not allocated and not available to
1196// allocation without reorganizing the space via a GC (eg, small blocks due
1197// to internal fragmentation, top of page areas in map space), and the bytes
1198// 'available' is the number of unallocated bytes that are not waste. The
1199// capacity is the sum of size, waste, and available.
1200//
1201// The stats are only set by functions that ensure they stay balanced. These
1202// functions increase or decrease one of the non-capacity stats in
1203// conjunction with capacity, or else they always balance increases and
1204// decreases to the non-capacity stats.
1205class AllocationStats BASE_EMBEDDED {
1206 public:
1207 AllocationStats() { Clear(); }
1208
1209 // Zero out all the allocation statistics (ie, no capacity).
1210 void Clear() {
1211 capacity_ = 0;
Steve Blocka7e24c12009-10-30 11:49:00 +00001212 size_ = 0;
1213 waste_ = 0;
1214 }
1215
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001216 void ClearSizeWaste() {
1217 size_ = capacity_;
1218 waste_ = 0;
1219 }
1220
Steve Blocka7e24c12009-10-30 11:49:00 +00001221 // Reset the allocation statistics (ie, available = capacity with no
1222 // wasted or allocated bytes).
1223 void Reset() {
Steve Blocka7e24c12009-10-30 11:49:00 +00001224 size_ = 0;
1225 waste_ = 0;
1226 }
1227
1228 // Accessors for the allocation statistics.
Ben Murdochf87a2032010-10-22 12:50:53 +01001229 intptr_t Capacity() { return capacity_; }
Ben Murdochf87a2032010-10-22 12:50:53 +01001230 intptr_t Size() { return size_; }
1231 intptr_t Waste() { return waste_; }
Steve Blocka7e24c12009-10-30 11:49:00 +00001232
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001233 // Grow the space by adding available bytes. They are initially marked as
1234 // being in use (part of the size), but will normally be immediately freed,
1235 // putting them on the free list and removing them from size_.
Steve Blocka7e24c12009-10-30 11:49:00 +00001236 void ExpandSpace(int size_in_bytes) {
1237 capacity_ += size_in_bytes;
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001238 size_ += size_in_bytes;
1239 ASSERT(size_ >= 0);
Steve Blocka7e24c12009-10-30 11:49:00 +00001240 }
1241
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001242 // Shrink the space by removing available bytes. Since shrinking is done
1243 // during sweeping, bytes have been marked as being in use (part of the size)
1244 // and are hereby freed.
Steve Blocka7e24c12009-10-30 11:49:00 +00001245 void ShrinkSpace(int size_in_bytes) {
1246 capacity_ -= size_in_bytes;
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001247 size_ -= size_in_bytes;
1248 ASSERT(size_ >= 0);
Steve Blocka7e24c12009-10-30 11:49:00 +00001249 }
1250
1251 // Allocate from available bytes (available -> size).
Ben Murdochf87a2032010-10-22 12:50:53 +01001252 void AllocateBytes(intptr_t size_in_bytes) {
Steve Blocka7e24c12009-10-30 11:49:00 +00001253 size_ += size_in_bytes;
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001254 ASSERT(size_ >= 0);
Steve Blocka7e24c12009-10-30 11:49:00 +00001255 }
1256
1257 // Free allocated bytes, making them available (size -> available).
Ben Murdochf87a2032010-10-22 12:50:53 +01001258 void DeallocateBytes(intptr_t size_in_bytes) {
Steve Blocka7e24c12009-10-30 11:49:00 +00001259 size_ -= size_in_bytes;
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001260 ASSERT(size_ >= 0);
Steve Blocka7e24c12009-10-30 11:49:00 +00001261 }
1262
1263 // Waste free bytes (available -> waste).
1264 void WasteBytes(int size_in_bytes) {
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001265 size_ -= size_in_bytes;
Steve Blocka7e24c12009-10-30 11:49:00 +00001266 waste_ += size_in_bytes;
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001267 ASSERT(size_ >= 0);
Steve Blocka7e24c12009-10-30 11:49:00 +00001268 }
1269
1270 private:
Ben Murdochf87a2032010-10-22 12:50:53 +01001271 intptr_t capacity_;
Ben Murdochf87a2032010-10-22 12:50:53 +01001272 intptr_t size_;
1273 intptr_t waste_;
Steve Blocka7e24c12009-10-30 11:49:00 +00001274};
1275
1276
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001277// -----------------------------------------------------------------------------
1278// Free lists for old object spaces
1279//
1280// Free-list nodes are free blocks in the heap. They look like heap objects
1281// (free-list node pointers have the heap object tag, and they have a map like
1282// a heap object). They have a size and a next pointer. The next pointer is
1283// the raw address of the next free list node (or NULL).
1284class FreeListNode: public HeapObject {
1285 public:
1286 // Obtain a free-list node from a raw address. This is not a cast because
1287 // it does not check nor require that the first word at the address is a map
1288 // pointer.
1289 static FreeListNode* FromAddress(Address address) {
1290 return reinterpret_cast<FreeListNode*>(HeapObject::FromAddress(address));
1291 }
1292
1293 static inline bool IsFreeListNode(HeapObject* object);
1294
1295 // Set the size in bytes, which can be read with HeapObject::Size(). This
1296 // function also writes a map to the first word of the block so that it
1297 // looks like a heap object to the garbage collector and heap iteration
1298 // functions.
1299 void set_size(Heap* heap, int size_in_bytes);
1300
1301 // Accessors for the next field.
1302 inline FreeListNode* next();
1303 inline FreeListNode** next_address();
1304 inline void set_next(FreeListNode* next);
1305
1306 inline void Zap();
1307
1308 private:
1309 static const int kNextOffset = POINTER_SIZE_ALIGN(FreeSpace::kHeaderSize);
1310
1311 DISALLOW_IMPLICIT_CONSTRUCTORS(FreeListNode);
1312};
1313
1314
1315// The free list for the old space. The free list is organized in such a way
1316// as to encourage objects allocated around the same time to be near each
1317// other. The normal way to allocate is intended to be by bumping a 'top'
1318// pointer until it hits a 'limit' pointer. When the limit is hit we need to
1319// find a new space to allocate from. This is done with the free list, which
1320// is divided up into rough categories to cut down on waste. Having finer
1321// categories would scatter allocation more.
1322
1323// The old space free list is organized in categories.
1324// 1-31 words: Such small free areas are discarded for efficiency reasons.
1325// They can be reclaimed by the compactor. However the distance between top
1326// and limit may be this small.
1327// 32-255 words: There is a list of spaces this large. It is used for top and
1328// limit when the object we need to allocate is 1-31 words in size. These
1329// spaces are called small.
1330// 256-2047 words: There is a list of spaces this large. It is used for top and
1331// limit when the object we need to allocate is 32-255 words in size. These
1332// spaces are called medium.
1333// 1048-16383 words: There is a list of spaces this large. It is used for top
1334// and limit when the object we need to allocate is 256-2047 words in size.
1335// These spaces are call large.
1336// At least 16384 words. This list is for objects of 2048 words or larger.
1337// Empty pages are added to this list. These spaces are called huge.
1338class FreeList BASE_EMBEDDED {
1339 public:
1340 explicit FreeList(PagedSpace* owner);
1341
1342 // Clear the free list.
1343 void Reset();
1344
1345 // Return the number of bytes available on the free list.
1346 intptr_t available() { return available_; }
1347
1348 // Place a node on the free list. The block of size 'size_in_bytes'
1349 // starting at 'start' is placed on the free list. The return value is the
1350 // number of bytes that have been lost due to internal fragmentation by
1351 // freeing the block. Bookkeeping information will be written to the block,
1352 // ie, its contents will be destroyed. The start address should be word
1353 // aligned, and the size should be a non-zero multiple of the word size.
1354 int Free(Address start, int size_in_bytes);
1355
1356 // Allocate a block of size 'size_in_bytes' from the free list. The block
1357 // is unitialized. A failure is returned if no block is available. The
1358 // number of bytes lost to fragmentation is returned in the output parameter
1359 // 'wasted_bytes'. The size should be a non-zero multiple of the word size.
1360 MUST_USE_RESULT HeapObject* Allocate(int size_in_bytes);
1361
1362#ifdef DEBUG
1363 void Zap();
1364 static intptr_t SumFreeList(FreeListNode* node);
1365 static int FreeListLength(FreeListNode* cur);
1366 intptr_t SumFreeLists();
1367 bool IsVeryLong();
1368#endif
1369
1370 struct SizeStats {
1371 intptr_t Total() {
1372 return small_size_ + medium_size_ + large_size_ + huge_size_;
1373 }
1374
1375 intptr_t small_size_;
1376 intptr_t medium_size_;
1377 intptr_t large_size_;
1378 intptr_t huge_size_;
1379 };
1380
1381 void CountFreeListItems(Page* p, SizeStats* sizes);
1382
1383 intptr_t EvictFreeListItems(Page* p);
1384
1385 private:
1386 // The size range of blocks, in bytes.
1387 static const int kMinBlockSize = 3 * kPointerSize;
1388 static const int kMaxBlockSize = Page::kMaxNonCodeHeapObjectSize;
1389
1390 FreeListNode* PickNodeFromList(FreeListNode** list, int* node_size);
1391
1392 FreeListNode* FindNodeFor(int size_in_bytes, int* node_size);
1393
1394 PagedSpace* owner_;
1395 Heap* heap_;
1396
1397 // Total available bytes in all blocks on this free list.
1398 int available_;
1399
1400 static const int kSmallListMin = 0x20 * kPointerSize;
1401 static const int kSmallListMax = 0xff * kPointerSize;
1402 static const int kMediumListMax = 0x7ff * kPointerSize;
1403 static const int kLargeListMax = 0x3fff * kPointerSize;
1404 static const int kSmallAllocationMax = kSmallListMin - kPointerSize;
1405 static const int kMediumAllocationMax = kSmallListMax;
1406 static const int kLargeAllocationMax = kMediumListMax;
1407 FreeListNode* small_list_;
1408 FreeListNode* medium_list_;
1409 FreeListNode* large_list_;
1410 FreeListNode* huge_list_;
1411
1412 DISALLOW_IMPLICIT_CONSTRUCTORS(FreeList);
1413};
1414
1415
Steve Blocka7e24c12009-10-30 11:49:00 +00001416class PagedSpace : public Space {
1417 public:
1418 // Creates a space with a maximum capacity, and an id.
Steve Block44f0eee2011-05-26 01:26:41 +01001419 PagedSpace(Heap* heap,
1420 intptr_t max_capacity,
Ben Murdochf87a2032010-10-22 12:50:53 +01001421 AllocationSpace id,
1422 Executability executable);
Steve Blocka7e24c12009-10-30 11:49:00 +00001423
1424 virtual ~PagedSpace() {}
1425
1426 // Set up the space using the given address range of virtual memory (from
1427 // the memory allocator's initial chunk) if possible. If the block of
1428 // addresses is not big enough to contain a single page-aligned page, a
1429 // fresh chunk will be allocated.
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001430 bool Setup();
Steve Blocka7e24c12009-10-30 11:49:00 +00001431
1432 // Returns true if the space has been successfully set up and not
1433 // subsequently torn down.
1434 bool HasBeenSetup();
1435
1436 // Cleans up the space, frees all pages in this space except those belonging
1437 // to the initial chunk, uncommits addresses in the initial chunk.
1438 void TearDown();
1439
1440 // Checks whether an object/address is in this space.
1441 inline bool Contains(Address a);
1442 bool Contains(HeapObject* o) { return Contains(o->address()); }
1443
1444 // Given an address occupied by a live object, return that object if it is
1445 // in this space, or Failure::Exception() if it is not. The implementation
1446 // iterates over objects in the page containing the address, the cost is
1447 // linear in the number of objects in the page. It may be slow.
John Reck59135872010-11-02 12:39:01 -07001448 MUST_USE_RESULT MaybeObject* FindObject(Address addr);
Steve Blocka7e24c12009-10-30 11:49:00 +00001449
Steve Blocka7e24c12009-10-30 11:49:00 +00001450 // Prepares for a mark-compact GC.
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001451 virtual void PrepareForMarkCompact();
Steve Blocka7e24c12009-10-30 11:49:00 +00001452
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001453 // Current capacity without growing (Size() + Available()).
Ben Murdochf87a2032010-10-22 12:50:53 +01001454 intptr_t Capacity() { return accounting_stats_.Capacity(); }
Steve Blocka7e24c12009-10-30 11:49:00 +00001455
Steve Block3ce2e202009-11-05 08:53:23 +00001456 // Total amount of memory committed for this space. For paged
1457 // spaces this equals the capacity.
Ben Murdochf87a2032010-10-22 12:50:53 +01001458 intptr_t CommittedMemory() { return Capacity(); }
Steve Block3ce2e202009-11-05 08:53:23 +00001459
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001460 // Sets the capacity, the available space and the wasted space to zero.
1461 // The stats are rebuilt during sweeping by adding each page to the
1462 // capacity and the size when it is encountered. As free spaces are
1463 // discovered during the sweeping they are subtracted from the size and added
1464 // to the available and wasted totals.
1465 void ClearStats() {
1466 accounting_stats_.ClearSizeWaste();
1467 }
Steve Blocka7e24c12009-10-30 11:49:00 +00001468
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001469 // Available bytes without growing. These are the bytes on the free list.
1470 // The bytes in the linear allocation area are not included in this total
1471 // because updating the stats would slow down allocation. New pages are
1472 // immediately added to the free list so they show up here.
1473 intptr_t Available() { return free_list_.available(); }
1474
1475 // Allocated bytes in this space. Garbage bytes that were not found due to
1476 // lazy sweeping are counted as being allocated! The bytes in the current
1477 // linear allocation area (between top and limit) are also counted here.
Ben Murdochf87a2032010-10-22 12:50:53 +01001478 virtual intptr_t Size() { return accounting_stats_.Size(); }
Steve Blocka7e24c12009-10-30 11:49:00 +00001479
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001480 // As size, but the bytes in the current linear allocation area are not
1481 // included.
1482 virtual intptr_t SizeOfObjects() { return Size() - (limit() - top()); }
Steve Blocka7e24c12009-10-30 11:49:00 +00001483
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001484 // Wasted bytes in this space. These are just the bytes that were thrown away
1485 // due to being too small to use for allocation. They do not include the
1486 // free bytes that were not found at all due to lazy sweeping.
1487 virtual intptr_t Waste() { return accounting_stats_.Waste(); }
Steve Blocka7e24c12009-10-30 11:49:00 +00001488
1489 // Returns the allocation pointer in this space.
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001490 Address top() {
1491 return allocation_info_.top;
1492 }
1493 Address limit() { return allocation_info_.limit; }
Steve Blocka7e24c12009-10-30 11:49:00 +00001494
1495 // Allocate the requested number of bytes in the space if possible, return a
1496 // failure object if not.
John Reck59135872010-11-02 12:39:01 -07001497 MUST_USE_RESULT inline MaybeObject* AllocateRaw(int size_in_bytes);
Steve Blocka7e24c12009-10-30 11:49:00 +00001498
Leon Clarkee46be812010-01-19 14:06:41 +00001499 virtual bool ReserveSpace(int bytes);
1500
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001501 // Give a block of memory to the space's free list. It might be added to
1502 // the free list or accounted as waste.
1503 // If add_to_freelist is false then just accounting stats are updated and
1504 // no attempt to add area to free list is made.
1505 int Free(Address start, int size_in_bytes) {
1506 int wasted = free_list_.Free(start, size_in_bytes);
1507 accounting_stats_.DeallocateBytes(size_in_bytes - wasted);
1508 return size_in_bytes - wasted;
1509 }
Kristian Monsen80d68ea2010-09-08 11:05:35 +01001510
Steve Block6ded16b2010-05-10 14:33:55 +01001511 // Set space allocation info.
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001512 void SetTop(Address top, Address limit) {
1513 ASSERT(top == limit ||
1514 Page::FromAddress(top) == Page::FromAddress(limit - 1));
Steve Block6ded16b2010-05-10 14:33:55 +01001515 allocation_info_.top = top;
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001516 allocation_info_.limit = limit;
Steve Block6ded16b2010-05-10 14:33:55 +01001517 }
1518
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001519 void Allocate(int bytes) {
1520 accounting_stats_.AllocateBytes(bytes);
Steve Blocka7e24c12009-10-30 11:49:00 +00001521 }
1522
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001523 void IncreaseCapacity(int size) {
1524 accounting_stats_.ExpandSpace(size);
1525 }
Steve Blocka7e24c12009-10-30 11:49:00 +00001526
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001527 // Releases an unused page and shrinks the space.
1528 void ReleasePage(Page* page);
Steve Blocka7e24c12009-10-30 11:49:00 +00001529
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001530 // Releases all of the unused pages.
1531 void ReleaseAllUnusedPages();
Steve Blocka7e24c12009-10-30 11:49:00 +00001532
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001533 // The dummy page that anchors the linked list of pages.
1534 Page* anchor() { return &anchor_; }
Steve Blocka7e24c12009-10-30 11:49:00 +00001535
Steve Blocka7e24c12009-10-30 11:49:00 +00001536#ifdef DEBUG
1537 // Print meta info and objects in this space.
1538 virtual void Print();
1539
1540 // Verify integrity of this space.
1541 virtual void Verify(ObjectVisitor* visitor);
1542
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001543 // Reports statistics for the space
1544 void ReportStatistics();
1545
Steve Blocka7e24c12009-10-30 11:49:00 +00001546 // Overridden by subclasses to verify space-specific object
1547 // properties (e.g., only maps or free-list nodes are in map space).
1548 virtual void VerifyObject(HeapObject* obj) {}
1549
1550 // Report code object related statistics
1551 void CollectCodeStatistics();
1552 static void ReportCodeStatistics();
1553 static void ResetCodeStatistics();
1554#endif
1555
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001556 bool was_swept_conservatively() { return was_swept_conservatively_; }
1557 void set_was_swept_conservatively(bool b) { was_swept_conservatively_ = b; }
Steve Block6ded16b2010-05-10 14:33:55 +01001558
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001559 // Evacuation candidates are swept by evacuator. Needs to return a valid
1560 // result before _and_ after evacuation has finished.
1561 static bool ShouldBeSweptLazily(Page* p) {
1562 return !p->IsEvacuationCandidate() &&
1563 !p->IsFlagSet(Page::RESCAN_ON_EVACUATION) &&
1564 !p->WasSweptPrecisely();
1565 }
1566
1567 void SetPagesToSweep(Page* first) {
1568 if (first == &anchor_) first = NULL;
1569 first_unswept_page_ = first;
1570 }
1571
1572 bool AdvanceSweeper(intptr_t bytes_to_sweep);
1573
1574 bool IsSweepingComplete() {
1575 return !first_unswept_page_->is_valid();
1576 }
1577
1578 Page* FirstPage() { return anchor_.next_page(); }
1579 Page* LastPage() { return anchor_.prev_page(); }
1580
1581 // Returns zero for pages that have so little fragmentation that it is not
1582 // worth defragmenting them. Otherwise a positive integer that gives an
1583 // estimate of fragmentation on an arbitrary scale.
1584 int Fragmentation(Page* p) {
1585 FreeList::SizeStats sizes;
1586 free_list_.CountFreeListItems(p, &sizes);
1587
1588 intptr_t ratio;
1589 intptr_t ratio_threshold;
1590 if (identity() == CODE_SPACE) {
1591 ratio = (sizes.medium_size_ * 10 + sizes.large_size_ * 2) * 100 /
1592 AreaSize();
1593 ratio_threshold = 10;
1594 } else {
1595 ratio = (sizes.small_size_ * 5 + sizes.medium_size_) * 100 /
1596 AreaSize();
1597 ratio_threshold = 15;
1598 }
1599
1600 if (FLAG_trace_fragmentation) {
1601 PrintF("%p [%d]: %d (%.2f%%) %d (%.2f%%) %d (%.2f%%) %d (%.2f%%) %s\n",
1602 reinterpret_cast<void*>(p),
1603 identity(),
1604 static_cast<int>(sizes.small_size_),
1605 static_cast<double>(sizes.small_size_ * 100) /
1606 AreaSize(),
1607 static_cast<int>(sizes.medium_size_),
1608 static_cast<double>(sizes.medium_size_ * 100) /
1609 AreaSize(),
1610 static_cast<int>(sizes.large_size_),
1611 static_cast<double>(sizes.large_size_ * 100) /
1612 AreaSize(),
1613 static_cast<int>(sizes.huge_size_),
1614 static_cast<double>(sizes.huge_size_ * 100) /
1615 AreaSize(),
1616 (ratio > ratio_threshold) ? "[fragmented]" : "");
1617 }
1618
1619 if (FLAG_always_compact && sizes.Total() != AreaSize()) {
1620 return 1;
1621 }
1622 if (ratio <= ratio_threshold) return 0; // Not fragmented.
1623
1624 return static_cast<int>(ratio - ratio_threshold);
1625 }
1626
1627 void EvictEvacuationCandidatesFromFreeLists();
1628
1629 bool CanExpand();
1630
1631 // Returns the number of total pages in this space.
1632 int CountTotalPages();
1633
1634 // Return size of allocatable area on a page in this space.
1635 inline int AreaSize() {
1636 return area_size_;
1637 }
Kristian Monsen80d68ea2010-09-08 11:05:35 +01001638
Steve Blocka7e24c12009-10-30 11:49:00 +00001639 protected:
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001640 int area_size_;
1641
Steve Blocka7e24c12009-10-30 11:49:00 +00001642 // Maximum capacity of this space.
Ben Murdochf87a2032010-10-22 12:50:53 +01001643 intptr_t max_capacity_;
Steve Blocka7e24c12009-10-30 11:49:00 +00001644
1645 // Accounting information for this space.
1646 AllocationStats accounting_stats_;
1647
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001648 // The dummy page that anchors the double linked list of pages.
1649 Page anchor_;
Steve Blocka7e24c12009-10-30 11:49:00 +00001650
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001651 // The space's free list.
1652 FreeList free_list_;
Steve Block6ded16b2010-05-10 14:33:55 +01001653
Steve Blocka7e24c12009-10-30 11:49:00 +00001654 // Normal allocation information.
1655 AllocationInfo allocation_info_;
1656
Steve Blocka7e24c12009-10-30 11:49:00 +00001657 // Bytes of each page that cannot be allocated. Possibly non-zero
1658 // for pages in spaces with only fixed-size objects. Always zero
1659 // for pages in spaces with variable sized objects (those pages are
1660 // padded with free-list nodes).
1661 int page_extra_;
1662
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001663 bool was_swept_conservatively_;
Steve Blocka7e24c12009-10-30 11:49:00 +00001664
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001665 Page* first_unswept_page_;
Leon Clarked91b9f72010-01-27 17:25:45 +00001666
Steve Blocka7e24c12009-10-30 11:49:00 +00001667 // Expands the space by allocating a fixed number of pages. Returns false if
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001668 // it cannot allocate requested number of pages from OS.
1669 bool Expand();
Steve Blocka7e24c12009-10-30 11:49:00 +00001670
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001671 // Generic fast case allocation function that tries linear allocation at the
1672 // address denoted by top in allocation_info_.
1673 inline HeapObject* AllocateLinearly(int size_in_bytes);
Steve Blocka7e24c12009-10-30 11:49:00 +00001674
1675 // Slow path of AllocateRaw. This function is space-dependent.
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001676 MUST_USE_RESULT virtual HeapObject* SlowAllocateRaw(int size_in_bytes);
Steve Blocka7e24c12009-10-30 11:49:00 +00001677
Steve Blocka7e24c12009-10-30 11:49:00 +00001678 friend class PageIterator;
1679};
1680
1681
Steve Blocka7e24c12009-10-30 11:49:00 +00001682class NumberAndSizeInfo BASE_EMBEDDED {
1683 public:
1684 NumberAndSizeInfo() : number_(0), bytes_(0) {}
1685
1686 int number() const { return number_; }
1687 void increment_number(int num) { number_ += num; }
1688
1689 int bytes() const { return bytes_; }
1690 void increment_bytes(int size) { bytes_ += size; }
1691
1692 void clear() {
1693 number_ = 0;
1694 bytes_ = 0;
1695 }
1696
1697 private:
1698 int number_;
1699 int bytes_;
1700};
1701
1702
1703// HistogramInfo class for recording a single "bar" of a histogram. This
Ben Murdoch3fb3ca82011-12-02 17:19:32 +00001704// class is used for collecting statistics to print to the log file.
Steve Blocka7e24c12009-10-30 11:49:00 +00001705class HistogramInfo: public NumberAndSizeInfo {
1706 public:
1707 HistogramInfo() : NumberAndSizeInfo() {}
1708
1709 const char* name() { return name_; }
1710 void set_name(const char* name) { name_ = name; }
1711
1712 private:
1713 const char* name_;
1714};
Steve Blocka7e24c12009-10-30 11:49:00 +00001715
1716
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001717enum SemiSpaceId {
1718 kFromSpace = 0,
1719 kToSpace = 1
1720};
1721
1722
1723class SemiSpace;
1724
1725
1726class NewSpacePage : public MemoryChunk {
1727 public:
1728 // GC related flags copied from from-space to to-space when
1729 // flipping semispaces.
1730 static const intptr_t kCopyOnFlipFlagsMask =
1731 (1 << MemoryChunk::POINTERS_TO_HERE_ARE_INTERESTING) |
1732 (1 << MemoryChunk::POINTERS_FROM_HERE_ARE_INTERESTING) |
1733 (1 << MemoryChunk::SCAN_ON_SCAVENGE);
1734
1735 static const int kAreaSize = Page::kNonCodeObjectAreaSize;
1736
1737 inline NewSpacePage* next_page() const {
1738 return static_cast<NewSpacePage*>(next_chunk());
1739 }
1740
1741 inline void set_next_page(NewSpacePage* page) {
1742 set_next_chunk(page);
1743 }
1744
1745 inline NewSpacePage* prev_page() const {
1746 return static_cast<NewSpacePage*>(prev_chunk());
1747 }
1748
1749 inline void set_prev_page(NewSpacePage* page) {
1750 set_prev_chunk(page);
1751 }
1752
1753 SemiSpace* semi_space() {
1754 return reinterpret_cast<SemiSpace*>(owner());
1755 }
1756
1757 bool is_anchor() { return !this->InNewSpace(); }
1758
1759 static bool IsAtStart(Address addr) {
1760 return (reinterpret_cast<intptr_t>(addr) & Page::kPageAlignmentMask)
1761 == kObjectStartOffset;
1762 }
1763
1764 static bool IsAtEnd(Address addr) {
1765 return (reinterpret_cast<intptr_t>(addr) & Page::kPageAlignmentMask) == 0;
1766 }
1767
1768 Address address() {
1769 return reinterpret_cast<Address>(this);
1770 }
1771
1772 // Finds the NewSpacePage containg the given address.
1773 static inline NewSpacePage* FromAddress(Address address_in_page) {
1774 Address page_start =
1775 reinterpret_cast<Address>(reinterpret_cast<uintptr_t>(address_in_page) &
1776 ~Page::kPageAlignmentMask);
1777 NewSpacePage* page = reinterpret_cast<NewSpacePage*>(page_start);
1778 return page;
1779 }
1780
1781 // Find the page for a limit address. A limit address is either an address
1782 // inside a page, or the address right after the last byte of a page.
1783 static inline NewSpacePage* FromLimit(Address address_limit) {
1784 return NewSpacePage::FromAddress(address_limit - 1);
1785 }
1786
1787 private:
1788 // Create a NewSpacePage object that is only used as anchor
1789 // for the doubly-linked list of real pages.
1790 explicit NewSpacePage(SemiSpace* owner) {
1791 InitializeAsAnchor(owner);
1792 }
1793
1794 static NewSpacePage* Initialize(Heap* heap,
1795 Address start,
1796 SemiSpace* semi_space);
1797
1798 // Intialize a fake NewSpacePage used as sentinel at the ends
1799 // of a doubly-linked list of real NewSpacePages.
1800 // Only uses the prev/next links, and sets flags to not be in new-space.
1801 void InitializeAsAnchor(SemiSpace* owner);
1802
1803 friend class SemiSpace;
1804 friend class SemiSpaceIterator;
1805};
1806
1807
Steve Blocka7e24c12009-10-30 11:49:00 +00001808// -----------------------------------------------------------------------------
1809// SemiSpace in young generation
1810//
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001811// A semispace is a contiguous chunk of memory holding page-like memory
1812// chunks. The mark-compact collector uses the memory of the first page in
1813// the from space as a marking stack when tracing live objects.
Steve Blocka7e24c12009-10-30 11:49:00 +00001814
1815class SemiSpace : public Space {
1816 public:
1817 // Constructor.
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001818 SemiSpace(Heap* heap, SemiSpaceId semispace)
1819 : Space(heap, NEW_SPACE, NOT_EXECUTABLE),
1820 start_(NULL),
1821 age_mark_(NULL),
1822 id_(semispace),
1823 anchor_(this),
1824 current_page_(NULL) { }
Steve Blocka7e24c12009-10-30 11:49:00 +00001825
1826 // Sets up the semispace using the given chunk.
1827 bool Setup(Address start, int initial_capacity, int maximum_capacity);
1828
1829 // Tear down the space. Heap memory was not allocated by the space, so it
1830 // is not deallocated here.
1831 void TearDown();
1832
1833 // True if the space has been set up but not torn down.
1834 bool HasBeenSetup() { return start_ != NULL; }
1835
Steve Blocka7e24c12009-10-30 11:49:00 +00001836 // Grow the semispace to the new capacity. The new capacity
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001837 // requested must be larger than the current capacity and less than
1838 // the maximum capacity.
Steve Blocka7e24c12009-10-30 11:49:00 +00001839 bool GrowTo(int new_capacity);
1840
1841 // Shrinks the semispace to the new capacity. The new capacity
1842 // requested must be more than the amount of used memory in the
1843 // semispace and less than the current capacity.
1844 bool ShrinkTo(int new_capacity);
1845
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001846 // Returns the start address of the first page of the space.
1847 Address space_start() {
1848 ASSERT(anchor_.next_page() != &anchor_);
1849 return anchor_.next_page()->area_start();
1850 }
1851
1852 // Returns the start address of the current page of the space.
1853 Address page_low() {
1854 return current_page_->area_start();
1855 }
1856
Steve Blocka7e24c12009-10-30 11:49:00 +00001857 // Returns one past the end address of the space.
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001858 Address space_end() {
1859 return anchor_.prev_page()->area_end();
1860 }
1861
1862 // Returns one past the end address of the current page of the space.
1863 Address page_high() {
1864 return current_page_->area_end();
1865 }
1866
1867 bool AdvancePage() {
1868 NewSpacePage* next_page = current_page_->next_page();
1869 if (next_page == anchor()) return false;
1870 current_page_ = next_page;
1871 return true;
1872 }
1873
1874 // Resets the space to using the first page.
1875 void Reset();
Steve Blocka7e24c12009-10-30 11:49:00 +00001876
1877 // Age mark accessors.
1878 Address age_mark() { return age_mark_; }
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001879 void set_age_mark(Address mark);
Steve Blocka7e24c12009-10-30 11:49:00 +00001880
1881 // True if the address is in the address range of this semispace (not
1882 // necessarily below the allocation pointer).
1883 bool Contains(Address a) {
1884 return (reinterpret_cast<uintptr_t>(a) & address_mask_)
1885 == reinterpret_cast<uintptr_t>(start_);
1886 }
1887
1888 // True if the object is a heap object in the address range of this
1889 // semispace (not necessarily below the allocation pointer).
1890 bool Contains(Object* o) {
1891 return (reinterpret_cast<uintptr_t>(o) & object_mask_) == object_expected_;
1892 }
1893
Leon Clarkee46be812010-01-19 14:06:41 +00001894 // If we don't have these here then SemiSpace will be abstract. However
1895 // they should never be called.
Ben Murdochf87a2032010-10-22 12:50:53 +01001896 virtual intptr_t Size() {
Steve Blocka7e24c12009-10-30 11:49:00 +00001897 UNREACHABLE();
1898 return 0;
1899 }
1900
Leon Clarkee46be812010-01-19 14:06:41 +00001901 virtual bool ReserveSpace(int bytes) {
1902 UNREACHABLE();
1903 return false;
1904 }
1905
Steve Blocka7e24c12009-10-30 11:49:00 +00001906 bool is_committed() { return committed_; }
1907 bool Commit();
1908 bool Uncommit();
1909
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001910 NewSpacePage* first_page() { return anchor_.next_page(); }
1911 NewSpacePage* current_page() { return current_page_; }
1912
Steve Blocka7e24c12009-10-30 11:49:00 +00001913#ifdef DEBUG
1914 virtual void Print();
1915 virtual void Verify();
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001916 // Validate a range of of addresses in a SemiSpace.
1917 // The "from" address must be on a page prior to the "to" address,
1918 // in the linked page order, or it must be earlier on the same page.
1919 static void AssertValidRange(Address from, Address to);
1920#else
1921 // Do nothing.
1922 inline static void AssertValidRange(Address from, Address to) {}
Steve Blocka7e24c12009-10-30 11:49:00 +00001923#endif
1924
1925 // Returns the current capacity of the semi space.
1926 int Capacity() { return capacity_; }
1927
1928 // Returns the maximum capacity of the semi space.
1929 int MaximumCapacity() { return maximum_capacity_; }
1930
1931 // Returns the initial capacity of the semi space.
1932 int InitialCapacity() { return initial_capacity_; }
1933
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001934 SemiSpaceId id() { return id_; }
1935
1936 static void Swap(SemiSpace* from, SemiSpace* to);
1937
Steve Blocka7e24c12009-10-30 11:49:00 +00001938 private:
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001939 // Flips the semispace between being from-space and to-space.
1940 // Copies the flags into the masked positions on all pages in the space.
1941 void FlipPages(intptr_t flags, intptr_t flag_mask);
1942
1943 NewSpacePage* anchor() { return &anchor_; }
1944
Steve Blocka7e24c12009-10-30 11:49:00 +00001945 // The current and maximum capacity of the space.
1946 int capacity_;
1947 int maximum_capacity_;
1948 int initial_capacity_;
1949
1950 // The start address of the space.
1951 Address start_;
1952 // Used to govern object promotion during mark-compact collection.
1953 Address age_mark_;
1954
1955 // Masks and comparison values to test for containment in this semispace.
1956 uintptr_t address_mask_;
1957 uintptr_t object_mask_;
1958 uintptr_t object_expected_;
1959
1960 bool committed_;
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001961 SemiSpaceId id_;
Steve Blocka7e24c12009-10-30 11:49:00 +00001962
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001963 NewSpacePage anchor_;
1964 NewSpacePage* current_page_;
1965
1966 friend class SemiSpaceIterator;
1967 friend class NewSpacePageIterator;
Steve Blocka7e24c12009-10-30 11:49:00 +00001968 public:
1969 TRACK_MEMORY("SemiSpace")
1970};
1971
1972
1973// A SemiSpaceIterator is an ObjectIterator that iterates over the active
1974// semispace of the heap's new space. It iterates over the objects in the
1975// semispace from a given start address (defaulting to the bottom of the
1976// semispace) to the top of the semispace. New objects allocated after the
1977// iterator is created are not iterated.
1978class SemiSpaceIterator : public ObjectIterator {
1979 public:
1980 // Create an iterator over the objects in the given space. If no start
1981 // address is given, the iterator starts from the bottom of the space. If
1982 // no size function is given, the iterator calls Object::Size().
Steve Blocka7e24c12009-10-30 11:49:00 +00001983
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001984 // Iterate over all of allocated to-space.
1985 explicit SemiSpaceIterator(NewSpace* space);
1986 // Iterate over all of allocated to-space, with a custome size function.
1987 SemiSpaceIterator(NewSpace* space, HeapObjectCallback size_func);
1988 // Iterate over part of allocated to-space, from start to the end
1989 // of allocation.
1990 SemiSpaceIterator(NewSpace* space, Address start);
1991 // Iterate from one address to another in the same semi-space.
1992 SemiSpaceIterator(Address from, Address to);
1993
1994 HeapObject* Next() {
Leon Clarked91b9f72010-01-27 17:25:45 +00001995 if (current_ == limit_) return NULL;
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001996 if (NewSpacePage::IsAtEnd(current_)) {
1997 NewSpacePage* page = NewSpacePage::FromLimit(current_);
1998 page = page->next_page();
1999 ASSERT(!page->is_anchor());
2000 current_ = page->area_start();
2001 if (current_ == limit_) return NULL;
2002 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002003
2004 HeapObject* object = HeapObject::FromAddress(current_);
2005 int size = (size_func_ == NULL) ? object->Size() : size_func_(object);
2006
2007 current_ += size;
2008 return object;
2009 }
2010
2011 // Implementation of the ObjectIterator functions.
Ben Murdoch592a9fc2012-03-05 11:04:45 +00002012 virtual HeapObject* next_object() { return Next(); }
Steve Blocka7e24c12009-10-30 11:49:00 +00002013
2014 private:
Ben Murdoch592a9fc2012-03-05 11:04:45 +00002015 void Initialize(Address start,
2016 Address end,
Steve Blocka7e24c12009-10-30 11:49:00 +00002017 HeapObjectCallback size_func);
2018
Steve Blocka7e24c12009-10-30 11:49:00 +00002019 // The current iteration point.
2020 Address current_;
2021 // The end of iteration.
2022 Address limit_;
2023 // The callback function.
2024 HeapObjectCallback size_func_;
2025};
2026
2027
2028// -----------------------------------------------------------------------------
Ben Murdoch592a9fc2012-03-05 11:04:45 +00002029// A PageIterator iterates the pages in a semi-space.
2030class NewSpacePageIterator BASE_EMBEDDED {
2031 public:
2032 // Make an iterator that runs over all pages in to-space.
2033 explicit inline NewSpacePageIterator(NewSpace* space);
2034
2035 // Make an iterator that runs over all pages in the given semispace,
2036 // even those not used in allocation.
2037 explicit inline NewSpacePageIterator(SemiSpace* space);
2038
2039 // Make iterator that iterates from the page containing start
2040 // to the page that contains limit in the same semispace.
2041 inline NewSpacePageIterator(Address start, Address limit);
2042
2043 inline bool has_next();
2044 inline NewSpacePage* next();
2045
2046 private:
2047 NewSpacePage* prev_page_; // Previous page returned.
2048 // Next page that will be returned. Cached here so that we can use this
2049 // iterator for operations that deallocate pages.
2050 NewSpacePage* next_page_;
2051 // Last page returned.
2052 NewSpacePage* last_page_;
2053};
2054
2055
2056// -----------------------------------------------------------------------------
Steve Blocka7e24c12009-10-30 11:49:00 +00002057// The young generation space.
2058//
2059// The new space consists of a contiguous pair of semispaces. It simply
2060// forwards most functions to the appropriate semispace.
2061
2062class NewSpace : public Space {
2063 public:
2064 // Constructor.
Steve Block44f0eee2011-05-26 01:26:41 +01002065 explicit NewSpace(Heap* heap)
2066 : Space(heap, NEW_SPACE, NOT_EXECUTABLE),
Ben Murdoch592a9fc2012-03-05 11:04:45 +00002067 to_space_(heap, kToSpace),
2068 from_space_(heap, kFromSpace),
2069 reservation_(),
2070 inline_allocation_limit_step_(0) {}
Steve Blocka7e24c12009-10-30 11:49:00 +00002071
2072 // Sets up the new space using the given chunk.
Ben Murdoch592a9fc2012-03-05 11:04:45 +00002073 bool Setup(int reserved_semispace_size_, int max_semispace_size);
Steve Blocka7e24c12009-10-30 11:49:00 +00002074
2075 // Tears down the space. Heap memory was not allocated by the space, so it
2076 // is not deallocated here.
2077 void TearDown();
2078
2079 // True if the space has been set up but not torn down.
2080 bool HasBeenSetup() {
2081 return to_space_.HasBeenSetup() && from_space_.HasBeenSetup();
2082 }
2083
2084 // Flip the pair of spaces.
2085 void Flip();
2086
2087 // Grow the capacity of the semispaces. Assumes that they are not at
2088 // their maximum capacity.
2089 void Grow();
2090
2091 // Shrink the capacity of the semispaces.
2092 void Shrink();
2093
2094 // True if the address or object lies in the address range of either
2095 // semispace (not necessarily below the allocation pointer).
2096 bool Contains(Address a) {
2097 return (reinterpret_cast<uintptr_t>(a) & address_mask_)
2098 == reinterpret_cast<uintptr_t>(start_);
2099 }
Ben Murdoch592a9fc2012-03-05 11:04:45 +00002100
Steve Blocka7e24c12009-10-30 11:49:00 +00002101 bool Contains(Object* o) {
Ben Murdoch592a9fc2012-03-05 11:04:45 +00002102 Address a = reinterpret_cast<Address>(o);
2103 return (reinterpret_cast<uintptr_t>(a) & object_mask_) == object_expected_;
Steve Blocka7e24c12009-10-30 11:49:00 +00002104 }
2105
2106 // Return the allocated bytes in the active semispace.
Ben Murdoch592a9fc2012-03-05 11:04:45 +00002107 virtual intptr_t Size() {
2108 return pages_used_ * NewSpacePage::kAreaSize +
2109 static_cast<int>(top() - to_space_.page_low());
2110 }
2111
Ben Murdochf87a2032010-10-22 12:50:53 +01002112 // The same, but returning an int. We have to have the one that returns
2113 // intptr_t because it is inherited, but if we know we are dealing with the
2114 // new space, which can't get as big as the other spaces then this is useful:
2115 int SizeAsInt() { return static_cast<int>(Size()); }
Steve Block3ce2e202009-11-05 08:53:23 +00002116
Steve Blocka7e24c12009-10-30 11:49:00 +00002117 // Return the current capacity of a semispace.
Ben Murdoch592a9fc2012-03-05 11:04:45 +00002118 intptr_t EffectiveCapacity() {
2119 SLOW_ASSERT(to_space_.Capacity() == from_space_.Capacity());
2120 return (to_space_.Capacity() / Page::kPageSize) * NewSpacePage::kAreaSize;
2121 }
2122
2123 // Return the current capacity of a semispace.
Ben Murdochf87a2032010-10-22 12:50:53 +01002124 intptr_t Capacity() {
Steve Blocka7e24c12009-10-30 11:49:00 +00002125 ASSERT(to_space_.Capacity() == from_space_.Capacity());
2126 return to_space_.Capacity();
2127 }
Steve Block3ce2e202009-11-05 08:53:23 +00002128
2129 // Return the total amount of memory committed for new space.
Ben Murdochf87a2032010-10-22 12:50:53 +01002130 intptr_t CommittedMemory() {
Steve Block3ce2e202009-11-05 08:53:23 +00002131 if (from_space_.is_committed()) return 2 * Capacity();
2132 return Capacity();
2133 }
2134
Ben Murdoch592a9fc2012-03-05 11:04:45 +00002135 // Return the available bytes without growing.
2136 intptr_t Available() {
2137 return Capacity() - Size();
2138 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002139
2140 // Return the maximum capacity of a semispace.
2141 int MaximumCapacity() {
2142 ASSERT(to_space_.MaximumCapacity() == from_space_.MaximumCapacity());
2143 return to_space_.MaximumCapacity();
2144 }
2145
2146 // Returns the initial capacity of a semispace.
2147 int InitialCapacity() {
2148 ASSERT(to_space_.InitialCapacity() == from_space_.InitialCapacity());
2149 return to_space_.InitialCapacity();
2150 }
2151
2152 // Return the address of the allocation pointer in the active semispace.
Ben Murdoch592a9fc2012-03-05 11:04:45 +00002153 Address top() {
2154 ASSERT(to_space_.current_page()->ContainsLimit(allocation_info_.top));
2155 return allocation_info_.top;
2156 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002157 // Return the address of the first object in the active semispace.
Ben Murdoch592a9fc2012-03-05 11:04:45 +00002158 Address bottom() { return to_space_.space_start(); }
Steve Blocka7e24c12009-10-30 11:49:00 +00002159
2160 // Get the age mark of the inactive semispace.
2161 Address age_mark() { return from_space_.age_mark(); }
2162 // Set the age mark in the active semispace.
2163 void set_age_mark(Address mark) { to_space_.set_age_mark(mark); }
2164
2165 // The start address of the space and a bit mask. Anding an address in the
2166 // new space with the mask will result in the start address.
2167 Address start() { return start_; }
2168 uintptr_t mask() { return address_mask_; }
2169
Ben Murdoch592a9fc2012-03-05 11:04:45 +00002170 INLINE(uint32_t AddressToMarkbitIndex(Address addr)) {
2171 ASSERT(Contains(addr));
2172 ASSERT(IsAligned(OffsetFrom(addr), kPointerSize) ||
2173 IsAligned(OffsetFrom(addr) - 1, kPointerSize));
2174 return static_cast<uint32_t>(addr - start_) >> kPointerSizeLog2;
2175 }
2176
2177 INLINE(Address MarkbitIndexToAddress(uint32_t index)) {
2178 return reinterpret_cast<Address>(index << kPointerSizeLog2);
2179 }
2180
Steve Blocka7e24c12009-10-30 11:49:00 +00002181 // The allocation top and limit addresses.
2182 Address* allocation_top_address() { return &allocation_info_.top; }
2183 Address* allocation_limit_address() { return &allocation_info_.limit; }
2184
Ben Murdoch592a9fc2012-03-05 11:04:45 +00002185 MUST_USE_RESULT INLINE(MaybeObject* AllocateRaw(int size_in_bytes));
Steve Blocka7e24c12009-10-30 11:49:00 +00002186
2187 // Reset the allocation pointer to the beginning of the active semispace.
2188 void ResetAllocationInfo();
Steve Blocka7e24c12009-10-30 11:49:00 +00002189
Ben Murdoch592a9fc2012-03-05 11:04:45 +00002190 void LowerInlineAllocationLimit(intptr_t step) {
2191 inline_allocation_limit_step_ = step;
2192 if (step == 0) {
2193 allocation_info_.limit = to_space_.page_high();
2194 } else {
2195 allocation_info_.limit = Min(
2196 allocation_info_.top + inline_allocation_limit_step_,
2197 allocation_info_.limit);
2198 }
2199 top_on_previous_step_ = allocation_info_.top;
Steve Blocka7e24c12009-10-30 11:49:00 +00002200 }
Ben Murdoch592a9fc2012-03-05 11:04:45 +00002201
2202 // Get the extent of the inactive semispace (for use as a marking stack,
2203 // or to zap it). Notice: space-addresses are not necessarily on the
2204 // same page, so FromSpaceStart() might be above FromSpaceEnd().
2205 Address FromSpacePageLow() { return from_space_.page_low(); }
2206 Address FromSpacePageHigh() { return from_space_.page_high(); }
2207 Address FromSpaceStart() { return from_space_.space_start(); }
2208 Address FromSpaceEnd() { return from_space_.space_end(); }
2209
2210 // Get the extent of the active semispace's pages' memory.
2211 Address ToSpaceStart() { return to_space_.space_start(); }
2212 Address ToSpaceEnd() { return to_space_.space_end(); }
2213
2214 inline bool ToSpaceContains(Address address) {
2215 return to_space_.Contains(address);
2216 }
2217 inline bool FromSpaceContains(Address address) {
2218 return from_space_.Contains(address);
Steve Blocka7e24c12009-10-30 11:49:00 +00002219 }
2220
2221 // True if the object is a heap object in the address range of the
2222 // respective semispace (not necessarily below the allocation pointer of the
2223 // semispace).
Ben Murdoch592a9fc2012-03-05 11:04:45 +00002224 inline bool ToSpaceContains(Object* o) { return to_space_.Contains(o); }
2225 inline bool FromSpaceContains(Object* o) { return from_space_.Contains(o); }
Steve Blocka7e24c12009-10-30 11:49:00 +00002226
Ben Murdoch592a9fc2012-03-05 11:04:45 +00002227 // Try to switch the active semispace to a new, empty, page.
2228 // Returns false if this isn't possible or reasonable (i.e., there
2229 // are no pages, or the current page is already empty), or true
2230 // if successful.
2231 bool AddFreshPage();
Steve Blocka7e24c12009-10-30 11:49:00 +00002232
Leon Clarkee46be812010-01-19 14:06:41 +00002233 virtual bool ReserveSpace(int bytes);
2234
Ben Murdochb0fe1622011-05-05 13:52:32 +01002235 // Resizes a sequential string which must be the most recent thing that was
2236 // allocated in new space.
2237 template <typename StringType>
2238 inline void ShrinkStringAtAllocationBoundary(String* string, int len);
2239
Steve Blocka7e24c12009-10-30 11:49:00 +00002240#ifdef DEBUG
2241 // Verify the active semispace.
2242 virtual void Verify();
2243 // Print the active semispace.
2244 virtual void Print() { to_space_.Print(); }
2245#endif
2246
Steve Blocka7e24c12009-10-30 11:49:00 +00002247 // Iterates the active semispace to collect statistics.
2248 void CollectStatistics();
2249 // Reports previously collected statistics of the active semispace.
2250 void ReportStatistics();
2251 // Clears previously collected statistics.
2252 void ClearHistograms();
2253
2254 // Record the allocation or promotion of a heap object. Note that we don't
2255 // record every single allocation, but only those that happen in the
2256 // to space during a scavenge GC.
2257 void RecordAllocation(HeapObject* obj);
2258 void RecordPromotion(HeapObject* obj);
Steve Blocka7e24c12009-10-30 11:49:00 +00002259
2260 // Return whether the operation succeded.
2261 bool CommitFromSpaceIfNeeded() {
2262 if (from_space_.is_committed()) return true;
2263 return from_space_.Commit();
2264 }
2265
2266 bool UncommitFromSpace() {
2267 if (!from_space_.is_committed()) return true;
2268 return from_space_.Uncommit();
2269 }
2270
Ben Murdoch592a9fc2012-03-05 11:04:45 +00002271 inline intptr_t inline_allocation_limit_step() {
2272 return inline_allocation_limit_step_;
2273 }
2274
2275 SemiSpace* active_space() { return &to_space_; }
2276
Steve Blocka7e24c12009-10-30 11:49:00 +00002277 private:
Ben Murdoch592a9fc2012-03-05 11:04:45 +00002278 // Update allocation info to match the current to-space page.
2279 void UpdateAllocationInfo();
2280
2281 Address chunk_base_;
2282 uintptr_t chunk_size_;
2283
Steve Blocka7e24c12009-10-30 11:49:00 +00002284 // The semispaces.
2285 SemiSpace to_space_;
2286 SemiSpace from_space_;
Ben Murdoch592a9fc2012-03-05 11:04:45 +00002287 VirtualMemory reservation_;
2288 int pages_used_;
Steve Blocka7e24c12009-10-30 11:49:00 +00002289
2290 // Start address and bit mask for containment testing.
2291 Address start_;
2292 uintptr_t address_mask_;
2293 uintptr_t object_mask_;
2294 uintptr_t object_expected_;
2295
2296 // Allocation pointer and limit for normal allocation and allocation during
2297 // mark-compact collection.
2298 AllocationInfo allocation_info_;
Ben Murdoch592a9fc2012-03-05 11:04:45 +00002299
2300 // When incremental marking is active we will set allocation_info_.limit
2301 // to be lower than actual limit and then will gradually increase it
2302 // in steps to guarantee that we do incremental marking steps even
2303 // when all allocation is performed from inlined generated code.
2304 intptr_t inline_allocation_limit_step_;
2305
2306 Address top_on_previous_step_;
Steve Blocka7e24c12009-10-30 11:49:00 +00002307
Steve Blocka7e24c12009-10-30 11:49:00 +00002308 HistogramInfo* allocated_histogram_;
2309 HistogramInfo* promoted_histogram_;
Steve Blocka7e24c12009-10-30 11:49:00 +00002310
Ben Murdoch592a9fc2012-03-05 11:04:45 +00002311 MUST_USE_RESULT MaybeObject* SlowAllocateRaw(int size_in_bytes);
Steve Blocka7e24c12009-10-30 11:49:00 +00002312
2313 friend class SemiSpaceIterator;
2314
2315 public:
2316 TRACK_MEMORY("NewSpace")
2317};
2318
2319
2320// -----------------------------------------------------------------------------
Steve Blocka7e24c12009-10-30 11:49:00 +00002321// Old object space (excluding map objects)
2322
2323class OldSpace : public PagedSpace {
2324 public:
2325 // Creates an old space object with a given maximum capacity.
2326 // The constructor does not allocate pages from OS.
Steve Block44f0eee2011-05-26 01:26:41 +01002327 OldSpace(Heap* heap,
2328 intptr_t max_capacity,
2329 AllocationSpace id,
2330 Executability executable)
Ben Murdoch592a9fc2012-03-05 11:04:45 +00002331 : PagedSpace(heap, max_capacity, id, executable) {
Steve Blocka7e24c12009-10-30 11:49:00 +00002332 page_extra_ = 0;
2333 }
2334
Steve Block6ded16b2010-05-10 14:33:55 +01002335 // The limit of allocation for a page in this space.
2336 virtual Address PageAllocationLimit(Page* page) {
Ben Murdoch592a9fc2012-03-05 11:04:45 +00002337 return page->area_end();
Steve Blocka7e24c12009-10-30 11:49:00 +00002338 }
2339
Steve Blocka7e24c12009-10-30 11:49:00 +00002340 public:
2341 TRACK_MEMORY("OldSpace")
2342};
2343
2344
Ben Murdoch592a9fc2012-03-05 11:04:45 +00002345// For contiguous spaces, top should be in the space (or at the end) and limit
2346// should be the end of the space.
2347#define ASSERT_SEMISPACE_ALLOCATION_INFO(info, space) \
2348 SLOW_ASSERT((space).page_low() <= (info).top \
2349 && (info).top <= (space).page_high() \
2350 && (info).limit <= (space).page_high())
2351
2352
Steve Blocka7e24c12009-10-30 11:49:00 +00002353// -----------------------------------------------------------------------------
2354// Old space for objects of a fixed size
2355
2356class FixedSpace : public PagedSpace {
2357 public:
Steve Block44f0eee2011-05-26 01:26:41 +01002358 FixedSpace(Heap* heap,
2359 intptr_t max_capacity,
Steve Blocka7e24c12009-10-30 11:49:00 +00002360 AllocationSpace id,
2361 int object_size_in_bytes,
2362 const char* name)
Steve Block44f0eee2011-05-26 01:26:41 +01002363 : PagedSpace(heap, max_capacity, id, NOT_EXECUTABLE),
Steve Blocka7e24c12009-10-30 11:49:00 +00002364 object_size_in_bytes_(object_size_in_bytes),
Ben Murdoch592a9fc2012-03-05 11:04:45 +00002365 name_(name) {
2366 page_extra_ = Page::kNonCodeObjectAreaSize % object_size_in_bytes;
Steve Blocka7e24c12009-10-30 11:49:00 +00002367 }
2368
Steve Block6ded16b2010-05-10 14:33:55 +01002369 // The limit of allocation for a page in this space.
2370 virtual Address PageAllocationLimit(Page* page) {
Ben Murdoch592a9fc2012-03-05 11:04:45 +00002371 return page->area_end() - page_extra_;
Steve Blocka7e24c12009-10-30 11:49:00 +00002372 }
2373
2374 int object_size_in_bytes() { return object_size_in_bytes_; }
2375
Steve Blocka7e24c12009-10-30 11:49:00 +00002376 // Prepares for a mark-compact GC.
Ben Murdoch592a9fc2012-03-05 11:04:45 +00002377 virtual void PrepareForMarkCompact();
Steve Blocka7e24c12009-10-30 11:49:00 +00002378
2379 protected:
Leon Clarkee46be812010-01-19 14:06:41 +00002380 void ResetFreeList() {
2381 free_list_.Reset();
2382 }
2383
Steve Blocka7e24c12009-10-30 11:49:00 +00002384 private:
2385 // The size of objects in this space.
2386 int object_size_in_bytes_;
2387
2388 // The name of this space.
2389 const char* name_;
Steve Blocka7e24c12009-10-30 11:49:00 +00002390};
2391
2392
2393// -----------------------------------------------------------------------------
2394// Old space for all map objects
2395
2396class MapSpace : public FixedSpace {
2397 public:
2398 // Creates a map space object with a maximum capacity.
Steve Block44f0eee2011-05-26 01:26:41 +01002399 MapSpace(Heap* heap,
2400 intptr_t max_capacity,
2401 int max_map_space_pages,
2402 AllocationSpace id)
2403 : FixedSpace(heap, max_capacity, id, Map::kSize, "map"),
Leon Clarked91b9f72010-01-27 17:25:45 +00002404 max_map_space_pages_(max_map_space_pages) {
Leon Clarked91b9f72010-01-27 17:25:45 +00002405 }
Steve Blocka7e24c12009-10-30 11:49:00 +00002406
Steve Blocka7e24c12009-10-30 11:49:00 +00002407 // Given an index, returns the page address.
Ben Murdoch592a9fc2012-03-05 11:04:45 +00002408 // TODO(1600): this limit is artifical just to keep code compilable
2409 static const int kMaxMapPageIndex = 1 << 16;
Steve Blocka7e24c12009-10-30 11:49:00 +00002410
Ben Murdoch592a9fc2012-03-05 11:04:45 +00002411 virtual int RoundSizeDownToObjectAlignment(int size) {
2412 if (IsPowerOf2(Map::kSize)) {
2413 return RoundDown(size, Map::kSize);
2414 } else {
2415 return (size / Map::kSize) * Map::kSize;
Leon Clarkee46be812010-01-19 14:06:41 +00002416 }
Leon Clarkee46be812010-01-19 14:06:41 +00002417 }
2418
Steve Blocka7e24c12009-10-30 11:49:00 +00002419 protected:
2420#ifdef DEBUG
2421 virtual void VerifyObject(HeapObject* obj);
2422#endif
2423
2424 private:
Ben Murdoch592a9fc2012-03-05 11:04:45 +00002425 static const int kMapsPerPage = Page::kNonCodeObjectAreaSize / Map::kSize;
Leon Clarkee46be812010-01-19 14:06:41 +00002426
2427 // Do map space compaction if there is a page gap.
Leon Clarked91b9f72010-01-27 17:25:45 +00002428 int CompactionThreshold() {
2429 return kMapsPerPage * (max_map_space_pages_ - 1);
2430 }
2431
2432 const int max_map_space_pages_;
Leon Clarkee46be812010-01-19 14:06:41 +00002433
Steve Blocka7e24c12009-10-30 11:49:00 +00002434 public:
2435 TRACK_MEMORY("MapSpace")
2436};
2437
2438
2439// -----------------------------------------------------------------------------
2440// Old space for all global object property cell objects
2441
2442class CellSpace : public FixedSpace {
2443 public:
2444 // Creates a property cell space object with a maximum capacity.
Steve Block44f0eee2011-05-26 01:26:41 +01002445 CellSpace(Heap* heap, intptr_t max_capacity, AllocationSpace id)
2446 : FixedSpace(heap, max_capacity, id, JSGlobalPropertyCell::kSize, "cell")
2447 {}
Steve Blocka7e24c12009-10-30 11:49:00 +00002448
Ben Murdoch592a9fc2012-03-05 11:04:45 +00002449 virtual int RoundSizeDownToObjectAlignment(int size) {
2450 if (IsPowerOf2(JSGlobalPropertyCell::kSize)) {
2451 return RoundDown(size, JSGlobalPropertyCell::kSize);
2452 } else {
2453 return (size / JSGlobalPropertyCell::kSize) * JSGlobalPropertyCell::kSize;
2454 }
2455 }
2456
Steve Blocka7e24c12009-10-30 11:49:00 +00002457 protected:
2458#ifdef DEBUG
2459 virtual void VerifyObject(HeapObject* obj);
2460#endif
2461
2462 public:
2463 TRACK_MEMORY("CellSpace")
2464};
2465
2466
2467// -----------------------------------------------------------------------------
2468// Large objects ( > Page::kMaxHeapObjectSize ) are allocated and managed by
2469// the large object space. A large object is allocated from OS heap with
2470// extra padding bytes (Page::kPageSize + Page::kObjectStartOffset).
2471// A large object always starts at Page::kObjectStartOffset to a page.
2472// Large objects do not move during garbage collections.
2473
Steve Blocka7e24c12009-10-30 11:49:00 +00002474class LargeObjectSpace : public Space {
2475 public:
Ben Murdoch592a9fc2012-03-05 11:04:45 +00002476 LargeObjectSpace(Heap* heap, intptr_t max_capacity, AllocationSpace id);
Steve Blocka7e24c12009-10-30 11:49:00 +00002477 virtual ~LargeObjectSpace() {}
2478
2479 // Initializes internal data structures.
2480 bool Setup();
2481
2482 // Releases internal resources, frees objects in this space.
2483 void TearDown();
2484
Ben Murdoch592a9fc2012-03-05 11:04:45 +00002485 static intptr_t ObjectSizeFor(intptr_t chunk_size) {
2486 if (chunk_size <= (Page::kPageSize + Page::kObjectStartOffset)) return 0;
2487 return chunk_size - Page::kPageSize - Page::kObjectStartOffset;
2488 }
2489
2490 // Shared implementation of AllocateRaw, AllocateRawCode and
2491 // AllocateRawFixedArray.
2492 MUST_USE_RESULT MaybeObject* AllocateRaw(int object_size,
2493 Executability executable);
Steve Blocka7e24c12009-10-30 11:49:00 +00002494
Ben Murdoch7f4d5bd2010-06-15 11:15:29 +01002495 // Available bytes for objects in this space.
Steve Block44f0eee2011-05-26 01:26:41 +01002496 inline intptr_t Available();
Steve Blocka7e24c12009-10-30 11:49:00 +00002497
Ben Murdochf87a2032010-10-22 12:50:53 +01002498 virtual intptr_t Size() {
Steve Blocka7e24c12009-10-30 11:49:00 +00002499 return size_;
2500 }
2501
Shimeng (Simon) Wang8a31eba2010-12-06 19:01:33 -08002502 virtual intptr_t SizeOfObjects() {
2503 return objects_size_;
2504 }
2505
Steve Blocka7e24c12009-10-30 11:49:00 +00002506 int PageCount() {
2507 return page_count_;
2508 }
2509
2510 // Finds an object for a given address, returns Failure::Exception()
2511 // if it is not found. The function iterates through all objects in this
2512 // space, may be slow.
John Reck59135872010-11-02 12:39:01 -07002513 MaybeObject* FindObject(Address a);
Steve Blocka7e24c12009-10-30 11:49:00 +00002514
Kristian Monsen80d68ea2010-09-08 11:05:35 +01002515 // Finds a large object page containing the given pc, returns NULL
2516 // if such a page doesn't exist.
Ben Murdoch592a9fc2012-03-05 11:04:45 +00002517 LargePage* FindPageContainingPc(Address pc);
Steve Blocka7e24c12009-10-30 11:49:00 +00002518
2519 // Frees unmarked objects.
2520 void FreeUnmarkedObjects();
2521
2522 // Checks whether a heap object is in this space; O(1).
2523 bool Contains(HeapObject* obj);
2524
2525 // Checks whether the space is empty.
Ben Murdoch592a9fc2012-03-05 11:04:45 +00002526 bool IsEmpty() { return first_page_ == NULL; }
Steve Blocka7e24c12009-10-30 11:49:00 +00002527
Leon Clarkee46be812010-01-19 14:06:41 +00002528 // See the comments for ReserveSpace in the Space class. This has to be
2529 // called after ReserveSpace has been called on the paged spaces, since they
2530 // may use some memory, leaving less for large objects.
2531 virtual bool ReserveSpace(int bytes);
2532
Ben Murdoch592a9fc2012-03-05 11:04:45 +00002533 LargePage* first_page() { return first_page_; }
2534
Steve Blocka7e24c12009-10-30 11:49:00 +00002535#ifdef DEBUG
2536 virtual void Verify();
2537 virtual void Print();
2538 void ReportStatistics();
2539 void CollectCodeStatistics();
Steve Blocka7e24c12009-10-30 11:49:00 +00002540#endif
2541 // Checks whether an address is in the object area in this space. It
2542 // iterates all objects in the space. May be slow.
2543 bool SlowContains(Address addr) { return !FindObject(addr)->IsFailure(); }
2544
2545 private:
Ben Murdoch592a9fc2012-03-05 11:04:45 +00002546 intptr_t max_capacity_;
Steve Blocka7e24c12009-10-30 11:49:00 +00002547 // The head of the linked list of large object chunks.
Ben Murdoch592a9fc2012-03-05 11:04:45 +00002548 LargePage* first_page_;
Ben Murdochf87a2032010-10-22 12:50:53 +01002549 intptr_t size_; // allocated bytes
Steve Blocka7e24c12009-10-30 11:49:00 +00002550 int page_count_; // number of chunks
Shimeng (Simon) Wang8a31eba2010-12-06 19:01:33 -08002551 intptr_t objects_size_; // size of objects
Steve Blocka7e24c12009-10-30 11:49:00 +00002552
Steve Blocka7e24c12009-10-30 11:49:00 +00002553 friend class LargeObjectIterator;
2554
2555 public:
2556 TRACK_MEMORY("LargeObjectSpace")
2557};
2558
2559
2560class LargeObjectIterator: public ObjectIterator {
2561 public:
2562 explicit LargeObjectIterator(LargeObjectSpace* space);
2563 LargeObjectIterator(LargeObjectSpace* space, HeapObjectCallback size_func);
2564
Ben Murdoch592a9fc2012-03-05 11:04:45 +00002565 HeapObject* Next();
Steve Blocka7e24c12009-10-30 11:49:00 +00002566
2567 // implementation of ObjectIterator.
Ben Murdoch592a9fc2012-03-05 11:04:45 +00002568 virtual HeapObject* next_object() { return Next(); }
Steve Blocka7e24c12009-10-30 11:49:00 +00002569
2570 private:
Ben Murdoch592a9fc2012-03-05 11:04:45 +00002571 LargePage* current_;
Steve Blocka7e24c12009-10-30 11:49:00 +00002572 HeapObjectCallback size_func_;
2573};
2574
2575
Ben Murdoch592a9fc2012-03-05 11:04:45 +00002576// Iterates over the chunks (pages and large object pages) that can contain
2577// pointers to new space.
2578class PointerChunkIterator BASE_EMBEDDED {
2579 public:
2580 inline explicit PointerChunkIterator(Heap* heap);
2581
2582 // Return NULL when the iterator is done.
2583 MemoryChunk* next() {
2584 switch (state_) {
2585 case kOldPointerState: {
2586 if (old_pointer_iterator_.has_next()) {
2587 return old_pointer_iterator_.next();
2588 }
2589 state_ = kMapState;
2590 // Fall through.
2591 }
2592 case kMapState: {
2593 if (map_iterator_.has_next()) {
2594 return map_iterator_.next();
2595 }
2596 state_ = kLargeObjectState;
2597 // Fall through.
2598 }
2599 case kLargeObjectState: {
2600 HeapObject* heap_object;
2601 do {
2602 heap_object = lo_iterator_.Next();
2603 if (heap_object == NULL) {
2604 state_ = kFinishedState;
2605 return NULL;
2606 }
2607 // Fixed arrays are the only pointer-containing objects in large
2608 // object space.
2609 } while (!heap_object->IsFixedArray());
2610 MemoryChunk* answer = MemoryChunk::FromAddress(heap_object->address());
2611 return answer;
2612 }
2613 case kFinishedState:
2614 return NULL;
2615 default:
2616 break;
2617 }
2618 UNREACHABLE();
2619 return NULL;
2620 }
2621
2622
2623 private:
2624 enum State {
2625 kOldPointerState,
2626 kMapState,
2627 kLargeObjectState,
2628 kFinishedState
2629 };
2630 State state_;
2631 PageIterator old_pointer_iterator_;
2632 PageIterator map_iterator_;
2633 LargeObjectIterator lo_iterator_;
2634};
2635
2636
Steve Block44f0eee2011-05-26 01:26:41 +01002637#ifdef DEBUG
2638struct CommentStatistic {
2639 const char* comment;
2640 int size;
2641 int count;
2642 void Clear() {
2643 comment = NULL;
2644 size = 0;
2645 count = 0;
2646 }
2647 // Must be small, since an iteration is used for lookup.
2648 static const int kMaxComments = 64;
2649};
2650#endif
2651
2652
Steve Blocka7e24c12009-10-30 11:49:00 +00002653} } // namespace v8::internal
2654
2655#endif // V8_SPACES_H_