2eae02953cbf2e41f0015bb766f57a814e0cba33
[platform/upstream/nodejs.git] / deps / v8 / src / heap / spaces.h
1 // Copyright 2011 the V8 project authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #ifndef V8_HEAP_SPACES_H_
6 #define V8_HEAP_SPACES_H_
7
8 #include "src/allocation.h"
9 #include "src/base/atomicops.h"
10 #include "src/base/bits.h"
11 #include "src/base/platform/mutex.h"
12 #include "src/hashmap.h"
13 #include "src/list.h"
14 #include "src/log.h"
15 #include "src/utils.h"
16
17 namespace v8 {
18 namespace internal {
19
20 class Isolate;
21
22 // -----------------------------------------------------------------------------
23 // Heap structures:
24 //
25 // A JS heap consists of a young generation, an old generation, and a large
26 // object space. The young generation is divided into two semispaces. A
27 // scavenger implements Cheney's copying algorithm. The old generation is
28 // separated into a map space and an old object space. The map space contains
29 // all (and only) map objects, the rest of old objects go into the old space.
30 // The old generation is collected by a mark-sweep-compact collector.
31 //
32 // The semispaces of the young generation are contiguous.  The old and map
33 // spaces consists of a list of pages. A page has a page header and an object
34 // area.
35 //
36 // There is a separate large object space for objects larger than
37 // Page::kMaxHeapObjectSize, so that they do not have to move during
38 // collection. The large object space is paged. Pages in large object space
39 // may be larger than the page size.
40 //
41 // A store-buffer based write barrier is used to keep track of intergenerational
42 // references.  See heap/store-buffer.h.
43 //
44 // During scavenges and mark-sweep collections we sometimes (after a store
45 // buffer overflow) iterate intergenerational pointers without decoding heap
46 // object maps so if the page belongs to old pointer space or large object
47 // space it is essential to guarantee that the page does not contain any
48 // garbage pointers to new space: every pointer aligned word which satisfies
49 // the Heap::InNewSpace() predicate must be a pointer to a live heap object in
50 // new space. Thus objects in old pointer and large object spaces should have a
51 // special layout (e.g. no bare integer fields). This requirement does not
52 // apply to map space which is iterated in a special fashion. However we still
53 // require pointer fields of dead maps to be cleaned.
54 //
55 // To enable lazy cleaning of old space pages we can mark chunks of the page
56 // as being garbage.  Garbage sections are marked with a special map.  These
57 // sections are skipped when scanning the page, even if we are otherwise
58 // scanning without regard for object boundaries.  Garbage sections are chained
59 // together to form a free list after a GC.  Garbage sections created outside
60 // of GCs by object trunctation etc. may not be in the free list chain.  Very
61 // small free spaces are ignored, they need only be cleaned of bogus pointers
62 // into new space.
63 //
64 // Each page may have up to one special garbage section.  The start of this
65 // section is denoted by the top field in the space.  The end of the section
66 // is denoted by the limit field in the space.  This special garbage section
67 // is not marked with a free space map in the data.  The point of this section
68 // is to enable linear allocation without having to constantly update the byte
69 // array every time the top field is updated and a new object is created.  The
70 // special garbage section is not in the chain of garbage sections.
71 //
72 // Since the top and limit fields are in the space, not the page, only one page
73 // has a special garbage section, and if the top and limit are equal then there
74 // is no special garbage section.
75
76 // Some assertion macros used in the debugging mode.
77
78 #define DCHECK_PAGE_ALIGNED(address) \
79   DCHECK((OffsetFrom(address) & Page::kPageAlignmentMask) == 0)
80
81 #define DCHECK_OBJECT_ALIGNED(address) \
82   DCHECK((OffsetFrom(address) & kObjectAlignmentMask) == 0)
83
84 #define DCHECK_OBJECT_SIZE(size) \
85   DCHECK((0 < size) && (size <= Page::kMaxRegularHeapObjectSize))
86
87 #define DCHECK_PAGE_OFFSET(offset) \
88   DCHECK((Page::kObjectStartOffset <= offset) && (offset <= Page::kPageSize))
89
90 #define DCHECK_MAP_PAGE_INDEX(index) \
91   DCHECK((0 <= index) && (index <= MapSpace::kMaxMapPageIndex))
92
93
94 class PagedSpace;
95 class MemoryAllocator;
96 class AllocationInfo;
97 class Space;
98 class FreeList;
99 class MemoryChunk;
100
101 class MarkBit {
102  public:
103   typedef uint32_t CellType;
104
105   inline MarkBit(CellType* cell, CellType mask, bool data_only)
106       : cell_(cell), mask_(mask), data_only_(data_only) {}
107
108   inline CellType* cell() { return cell_; }
109   inline CellType mask() { return mask_; }
110
111 #ifdef DEBUG
112   bool operator==(const MarkBit& other) {
113     return cell_ == other.cell_ && mask_ == other.mask_;
114   }
115 #endif
116
117   inline void Set() { *cell_ |= mask_; }
118   inline bool Get() { return (*cell_ & mask_) != 0; }
119   inline void Clear() { *cell_ &= ~mask_; }
120
121   inline bool data_only() { return data_only_; }
122
123   inline MarkBit Next() {
124     CellType new_mask = mask_ << 1;
125     if (new_mask == 0) {
126       return MarkBit(cell_ + 1, 1, data_only_);
127     } else {
128       return MarkBit(cell_, new_mask, data_only_);
129     }
130   }
131
132  private:
133   CellType* cell_;
134   CellType mask_;
135   // This boolean indicates that the object is in a data-only space with no
136   // pointers.  This enables some optimizations when marking.
137   // It is expected that this field is inlined and turned into control flow
138   // at the place where the MarkBit object is created.
139   bool data_only_;
140 };
141
142
143 // Bitmap is a sequence of cells each containing fixed number of bits.
144 class Bitmap {
145  public:
146   static const uint32_t kBitsPerCell = 32;
147   static const uint32_t kBitsPerCellLog2 = 5;
148   static const uint32_t kBitIndexMask = kBitsPerCell - 1;
149   static const uint32_t kBytesPerCell = kBitsPerCell / kBitsPerByte;
150   static const uint32_t kBytesPerCellLog2 = kBitsPerCellLog2 - kBitsPerByteLog2;
151
152   static const size_t kLength = (1 << kPageSizeBits) >> (kPointerSizeLog2);
153
154   static const size_t kSize =
155       (1 << kPageSizeBits) >> (kPointerSizeLog2 + kBitsPerByteLog2);
156
157
158   static int CellsForLength(int length) {
159     return (length + kBitsPerCell - 1) >> kBitsPerCellLog2;
160   }
161
162   int CellsCount() { return CellsForLength(kLength); }
163
164   static int SizeFor(int cells_count) {
165     return sizeof(MarkBit::CellType) * cells_count;
166   }
167
168   INLINE(static uint32_t IndexToCell(uint32_t index)) {
169     return index >> kBitsPerCellLog2;
170   }
171
172   INLINE(static uint32_t CellToIndex(uint32_t index)) {
173     return index << kBitsPerCellLog2;
174   }
175
176   INLINE(static uint32_t CellAlignIndex(uint32_t index)) {
177     return (index + kBitIndexMask) & ~kBitIndexMask;
178   }
179
180   INLINE(MarkBit::CellType* cells()) {
181     return reinterpret_cast<MarkBit::CellType*>(this);
182   }
183
184   INLINE(Address address()) { return reinterpret_cast<Address>(this); }
185
186   INLINE(static Bitmap* FromAddress(Address addr)) {
187     return reinterpret_cast<Bitmap*>(addr);
188   }
189
190   inline MarkBit MarkBitFromIndex(uint32_t index, bool data_only = false) {
191     MarkBit::CellType mask = 1 << (index & kBitIndexMask);
192     MarkBit::CellType* cell = this->cells() + (index >> kBitsPerCellLog2);
193     return MarkBit(cell, mask, data_only);
194   }
195
196   static inline void Clear(MemoryChunk* chunk);
197
198   static void PrintWord(uint32_t word, uint32_t himask = 0) {
199     for (uint32_t mask = 1; mask != 0; mask <<= 1) {
200       if ((mask & himask) != 0) PrintF("[");
201       PrintF((mask & word) ? "1" : "0");
202       if ((mask & himask) != 0) PrintF("]");
203     }
204   }
205
206   class CellPrinter {
207    public:
208     CellPrinter() : seq_start(0), seq_type(0), seq_length(0) {}
209
210     void Print(uint32_t pos, uint32_t cell) {
211       if (cell == seq_type) {
212         seq_length++;
213         return;
214       }
215
216       Flush();
217
218       if (IsSeq(cell)) {
219         seq_start = pos;
220         seq_length = 0;
221         seq_type = cell;
222         return;
223       }
224
225       PrintF("%d: ", pos);
226       PrintWord(cell);
227       PrintF("\n");
228     }
229
230     void Flush() {
231       if (seq_length > 0) {
232         PrintF("%d: %dx%d\n", seq_start, seq_type == 0 ? 0 : 1,
233                seq_length * kBitsPerCell);
234         seq_length = 0;
235       }
236     }
237
238     static bool IsSeq(uint32_t cell) { return cell == 0 || cell == 0xFFFFFFFF; }
239
240    private:
241     uint32_t seq_start;
242     uint32_t seq_type;
243     uint32_t seq_length;
244   };
245
246   void Print() {
247     CellPrinter printer;
248     for (int i = 0; i < CellsCount(); i++) {
249       printer.Print(i, cells()[i]);
250     }
251     printer.Flush();
252     PrintF("\n");
253   }
254
255   bool IsClean() {
256     for (int i = 0; i < CellsCount(); i++) {
257       if (cells()[i] != 0) {
258         return false;
259       }
260     }
261     return true;
262   }
263 };
264
265
266 class SkipList;
267 class SlotsBuffer;
268
269 // MemoryChunk represents a memory region owned by a specific space.
270 // It is divided into the header and the body. Chunk start is always
271 // 1MB aligned. Start of the body is aligned so it can accommodate
272 // any heap object.
273 class MemoryChunk {
274  public:
275   // Only works if the pointer is in the first kPageSize of the MemoryChunk.
276   static MemoryChunk* FromAddress(Address a) {
277     return reinterpret_cast<MemoryChunk*>(OffsetFrom(a) & ~kAlignmentMask);
278   }
279   static const MemoryChunk* FromAddress(const byte* a) {
280     return reinterpret_cast<const MemoryChunk*>(OffsetFrom(a) &
281                                                 ~kAlignmentMask);
282   }
283
284   // Only works for addresses in pointer spaces, not data or code spaces.
285   static inline MemoryChunk* FromAnyPointerAddress(Heap* heap, Address addr);
286
287   Address address() { return reinterpret_cast<Address>(this); }
288
289   bool is_valid() { return address() != NULL; }
290
291   MemoryChunk* next_chunk() const {
292     return reinterpret_cast<MemoryChunk*>(base::Acquire_Load(&next_chunk_));
293   }
294
295   MemoryChunk* prev_chunk() const {
296     return reinterpret_cast<MemoryChunk*>(base::Acquire_Load(&prev_chunk_));
297   }
298
299   void set_next_chunk(MemoryChunk* next) {
300     base::Release_Store(&next_chunk_, reinterpret_cast<base::AtomicWord>(next));
301   }
302
303   void set_prev_chunk(MemoryChunk* prev) {
304     base::Release_Store(&prev_chunk_, reinterpret_cast<base::AtomicWord>(prev));
305   }
306
307   Space* owner() const {
308     if ((reinterpret_cast<intptr_t>(owner_) & kPageHeaderTagMask) ==
309         kPageHeaderTag) {
310       return reinterpret_cast<Space*>(reinterpret_cast<intptr_t>(owner_) -
311                                       kPageHeaderTag);
312     } else {
313       return NULL;
314     }
315   }
316
317   void set_owner(Space* space) {
318     DCHECK((reinterpret_cast<intptr_t>(space) & kPageHeaderTagMask) == 0);
319     owner_ = reinterpret_cast<Address>(space) + kPageHeaderTag;
320     DCHECK((reinterpret_cast<intptr_t>(owner_) & kPageHeaderTagMask) ==
321            kPageHeaderTag);
322   }
323
324   base::VirtualMemory* reserved_memory() { return &reservation_; }
325
326   void InitializeReservedMemory() { reservation_.Reset(); }
327
328   void set_reserved_memory(base::VirtualMemory* reservation) {
329     DCHECK_NOT_NULL(reservation);
330     reservation_.TakeControl(reservation);
331   }
332
333   bool scan_on_scavenge() { return IsFlagSet(SCAN_ON_SCAVENGE); }
334   void initialize_scan_on_scavenge(bool scan) {
335     if (scan) {
336       SetFlag(SCAN_ON_SCAVENGE);
337     } else {
338       ClearFlag(SCAN_ON_SCAVENGE);
339     }
340   }
341   inline void set_scan_on_scavenge(bool scan);
342
343   int store_buffer_counter() { return store_buffer_counter_; }
344   void set_store_buffer_counter(int counter) {
345     store_buffer_counter_ = counter;
346   }
347
348   bool Contains(Address addr) {
349     return addr >= area_start() && addr < area_end();
350   }
351
352   // Checks whether addr can be a limit of addresses in this page.
353   // It's a limit if it's in the page, or if it's just after the
354   // last byte of the page.
355   bool ContainsLimit(Address addr) {
356     return addr >= area_start() && addr <= area_end();
357   }
358
359   // Every n write barrier invocations we go to runtime even though
360   // we could have handled it in generated code.  This lets us check
361   // whether we have hit the limit and should do some more marking.
362   static const int kWriteBarrierCounterGranularity = 500;
363
364   enum MemoryChunkFlags {
365     IS_EXECUTABLE,
366     ABOUT_TO_BE_FREED,
367     POINTERS_TO_HERE_ARE_INTERESTING,
368     POINTERS_FROM_HERE_ARE_INTERESTING,
369     SCAN_ON_SCAVENGE,
370     IN_FROM_SPACE,  // Mutually exclusive with IN_TO_SPACE.
371     IN_TO_SPACE,    // All pages in new space has one of these two set.
372     NEW_SPACE_BELOW_AGE_MARK,
373     CONTAINS_ONLY_DATA,
374     EVACUATION_CANDIDATE,
375     RESCAN_ON_EVACUATION,
376     NEVER_EVACUATE,  // May contain immortal immutables.
377
378     // WAS_SWEPT indicates that marking bits have been cleared by the sweeper,
379     // otherwise marking bits are still intact.
380     WAS_SWEPT,
381
382     // Large objects can have a progress bar in their page header. These object
383     // are scanned in increments and will be kept black while being scanned.
384     // Even if the mutator writes to them they will be kept black and a white
385     // to grey transition is performed in the value.
386     HAS_PROGRESS_BAR,
387
388     // Last flag, keep at bottom.
389     NUM_MEMORY_CHUNK_FLAGS
390   };
391
392
393   static const int kPointersToHereAreInterestingMask =
394       1 << POINTERS_TO_HERE_ARE_INTERESTING;
395
396   static const int kPointersFromHereAreInterestingMask =
397       1 << POINTERS_FROM_HERE_ARE_INTERESTING;
398
399   static const int kEvacuationCandidateMask = 1 << EVACUATION_CANDIDATE;
400
401   static const int kSkipEvacuationSlotsRecordingMask =
402       (1 << EVACUATION_CANDIDATE) | (1 << RESCAN_ON_EVACUATION) |
403       (1 << IN_FROM_SPACE) | (1 << IN_TO_SPACE);
404
405
406   void SetFlag(int flag) { flags_ |= static_cast<uintptr_t>(1) << flag; }
407
408   void ClearFlag(int flag) { flags_ &= ~(static_cast<uintptr_t>(1) << flag); }
409
410   void SetFlagTo(int flag, bool value) {
411     if (value) {
412       SetFlag(flag);
413     } else {
414       ClearFlag(flag);
415     }
416   }
417
418   bool IsFlagSet(int flag) {
419     return (flags_ & (static_cast<uintptr_t>(1) << flag)) != 0;
420   }
421
422   // Set or clear multiple flags at a time. The flags in the mask
423   // are set to the value in "flags", the rest retain the current value
424   // in flags_.
425   void SetFlags(intptr_t flags, intptr_t mask) {
426     flags_ = (flags_ & ~mask) | (flags & mask);
427   }
428
429   // Return all current flags.
430   intptr_t GetFlags() { return flags_; }
431
432
433   // SWEEPING_DONE - The page state when sweeping is complete or sweeping must
434   // not be performed on that page.
435   // SWEEPING_FINALIZE - A sweeper thread is done sweeping this page and will
436   // not touch the page memory anymore.
437   // SWEEPING_IN_PROGRESS - This page is currently swept by a sweeper thread.
438   // SWEEPING_PENDING - This page is ready for parallel sweeping.
439   enum ParallelSweepingState {
440     SWEEPING_DONE,
441     SWEEPING_FINALIZE,
442     SWEEPING_IN_PROGRESS,
443     SWEEPING_PENDING
444   };
445
446   ParallelSweepingState parallel_sweeping() {
447     return static_cast<ParallelSweepingState>(
448         base::Acquire_Load(&parallel_sweeping_));
449   }
450
451   void set_parallel_sweeping(ParallelSweepingState state) {
452     base::Release_Store(&parallel_sweeping_, state);
453   }
454
455   bool TryParallelSweeping() {
456     return base::Acquire_CompareAndSwap(&parallel_sweeping_, SWEEPING_PENDING,
457                                         SWEEPING_IN_PROGRESS) ==
458            SWEEPING_PENDING;
459   }
460
461   bool SweepingCompleted() { return parallel_sweeping() <= SWEEPING_FINALIZE; }
462
463   // Manage live byte count (count of bytes known to be live,
464   // because they are marked black).
465   void ResetLiveBytes() {
466     if (FLAG_gc_verbose) {
467       PrintF("ResetLiveBytes:%p:%x->0\n", static_cast<void*>(this),
468              live_byte_count_);
469     }
470     live_byte_count_ = 0;
471   }
472   void IncrementLiveBytes(int by) {
473     if (FLAG_gc_verbose) {
474       printf("UpdateLiveBytes:%p:%x%c=%x->%x\n", static_cast<void*>(this),
475              live_byte_count_, ((by < 0) ? '-' : '+'), ((by < 0) ? -by : by),
476              live_byte_count_ + by);
477     }
478     live_byte_count_ += by;
479     DCHECK_LE(static_cast<unsigned>(live_byte_count_), size_);
480   }
481   int LiveBytes() {
482     DCHECK(static_cast<unsigned>(live_byte_count_) <= size_);
483     return live_byte_count_;
484   }
485
486   int write_barrier_counter() {
487     return static_cast<int>(write_barrier_counter_);
488   }
489
490   void set_write_barrier_counter(int counter) {
491     write_barrier_counter_ = counter;
492   }
493
494   int progress_bar() {
495     DCHECK(IsFlagSet(HAS_PROGRESS_BAR));
496     return progress_bar_;
497   }
498
499   void set_progress_bar(int progress_bar) {
500     DCHECK(IsFlagSet(HAS_PROGRESS_BAR));
501     progress_bar_ = progress_bar;
502   }
503
504   void ResetProgressBar() {
505     if (IsFlagSet(MemoryChunk::HAS_PROGRESS_BAR)) {
506       set_progress_bar(0);
507       ClearFlag(MemoryChunk::HAS_PROGRESS_BAR);
508     }
509   }
510
511   bool IsLeftOfProgressBar(Object** slot) {
512     Address slot_address = reinterpret_cast<Address>(slot);
513     DCHECK(slot_address > this->address());
514     return (slot_address - (this->address() + kObjectStartOffset)) <
515            progress_bar();
516   }
517
518   static void IncrementLiveBytesFromGC(Address address, int by) {
519     MemoryChunk::FromAddress(address)->IncrementLiveBytes(by);
520   }
521
522   static void IncrementLiveBytesFromMutator(Address address, int by);
523
524   static const intptr_t kAlignment =
525       (static_cast<uintptr_t>(1) << kPageSizeBits);
526
527   static const intptr_t kAlignmentMask = kAlignment - 1;
528
529   static const intptr_t kSizeOffset = 0;
530
531   static const intptr_t kLiveBytesOffset =
532       kSizeOffset + kPointerSize + kPointerSize + kPointerSize + kPointerSize +
533       kPointerSize + kPointerSize + kPointerSize + kPointerSize + kIntSize;
534
535   static const size_t kSlotsBufferOffset = kLiveBytesOffset + kIntSize;
536
537   static const size_t kWriteBarrierCounterOffset =
538       kSlotsBufferOffset + kPointerSize + kPointerSize;
539
540   static const size_t kHeaderSize =
541       kWriteBarrierCounterOffset + kPointerSize + kIntSize + kIntSize +
542       kPointerSize + 5 * kPointerSize + kPointerSize + kPointerSize;
543
544   static const int kBodyOffset =
545       CODE_POINTER_ALIGN(kHeaderSize + Bitmap::kSize);
546
547   // The start offset of the object area in a page. Aligned to both maps and
548   // code alignment to be suitable for both.  Also aligned to 32 words because
549   // the marking bitmap is arranged in 32 bit chunks.
550   static const int kObjectStartAlignment = 32 * kPointerSize;
551   static const int kObjectStartOffset =
552       kBodyOffset - 1 +
553       (kObjectStartAlignment - (kBodyOffset - 1) % kObjectStartAlignment);
554
555   size_t size() const { return size_; }
556
557   void set_size(size_t size) { size_ = size; }
558
559   void SetArea(Address area_start, Address area_end) {
560     area_start_ = area_start;
561     area_end_ = area_end;
562   }
563
564   Executability executable() {
565     return IsFlagSet(IS_EXECUTABLE) ? EXECUTABLE : NOT_EXECUTABLE;
566   }
567
568   bool ContainsOnlyData() { return IsFlagSet(CONTAINS_ONLY_DATA); }
569
570   bool InNewSpace() {
571     return (flags_ & ((1 << IN_FROM_SPACE) | (1 << IN_TO_SPACE))) != 0;
572   }
573
574   bool InToSpace() { return IsFlagSet(IN_TO_SPACE); }
575
576   bool InFromSpace() { return IsFlagSet(IN_FROM_SPACE); }
577
578   // ---------------------------------------------------------------------
579   // Markbits support
580
581   inline Bitmap* markbits() {
582     return Bitmap::FromAddress(address() + kHeaderSize);
583   }
584
585   void PrintMarkbits() { markbits()->Print(); }
586
587   inline uint32_t AddressToMarkbitIndex(Address addr) {
588     return static_cast<uint32_t>(addr - this->address()) >> kPointerSizeLog2;
589   }
590
591   inline static uint32_t FastAddressToMarkbitIndex(Address addr) {
592     const intptr_t offset = reinterpret_cast<intptr_t>(addr) & kAlignmentMask;
593
594     return static_cast<uint32_t>(offset) >> kPointerSizeLog2;
595   }
596
597   inline Address MarkbitIndexToAddress(uint32_t index) {
598     return this->address() + (index << kPointerSizeLog2);
599   }
600
601   void InsertAfter(MemoryChunk* other);
602   void Unlink();
603
604   inline Heap* heap() const { return heap_; }
605
606   static const int kFlagsOffset = kPointerSize;
607
608   bool NeverEvacuate() { return IsFlagSet(NEVER_EVACUATE); }
609
610   void MarkNeverEvacuate() { SetFlag(NEVER_EVACUATE); }
611
612   bool IsEvacuationCandidate() {
613     DCHECK(!(IsFlagSet(NEVER_EVACUATE) && IsFlagSet(EVACUATION_CANDIDATE)));
614     return IsFlagSet(EVACUATION_CANDIDATE);
615   }
616
617   bool ShouldSkipEvacuationSlotRecording() {
618     return (flags_ & kSkipEvacuationSlotsRecordingMask) != 0;
619   }
620
621   inline SkipList* skip_list() { return skip_list_; }
622
623   inline void set_skip_list(SkipList* skip_list) { skip_list_ = skip_list; }
624
625   inline SlotsBuffer* slots_buffer() { return slots_buffer_; }
626
627   inline SlotsBuffer** slots_buffer_address() { return &slots_buffer_; }
628
629   void MarkEvacuationCandidate() {
630     DCHECK(!IsFlagSet(NEVER_EVACUATE));
631     DCHECK(slots_buffer_ == NULL);
632     SetFlag(EVACUATION_CANDIDATE);
633   }
634
635   void ClearEvacuationCandidate() {
636     DCHECK(slots_buffer_ == NULL);
637     ClearFlag(EVACUATION_CANDIDATE);
638   }
639
640   Address area_start() { return area_start_; }
641   Address area_end() { return area_end_; }
642   int area_size() { return static_cast<int>(area_end() - area_start()); }
643   bool CommitArea(size_t requested);
644
645   // Approximate amount of physical memory committed for this chunk.
646   size_t CommittedPhysicalMemory() { return high_water_mark_; }
647
648   static inline void UpdateHighWaterMark(Address mark);
649
650  protected:
651   size_t size_;
652   intptr_t flags_;
653
654   // Start and end of allocatable memory on this chunk.
655   Address area_start_;
656   Address area_end_;
657
658   // If the chunk needs to remember its memory reservation, it is stored here.
659   base::VirtualMemory reservation_;
660   // The identity of the owning space.  This is tagged as a failure pointer, but
661   // no failure can be in an object, so this can be distinguished from any entry
662   // in a fixed array.
663   Address owner_;
664   Heap* heap_;
665   // Used by the store buffer to keep track of which pages to mark scan-on-
666   // scavenge.
667   int store_buffer_counter_;
668   // Count of bytes marked black on page.
669   int live_byte_count_;
670   SlotsBuffer* slots_buffer_;
671   SkipList* skip_list_;
672   intptr_t write_barrier_counter_;
673   // Used by the incremental marker to keep track of the scanning progress in
674   // large objects that have a progress bar and are scanned in increments.
675   int progress_bar_;
676   // Assuming the initial allocation on a page is sequential,
677   // count highest number of bytes ever allocated on the page.
678   int high_water_mark_;
679
680   base::AtomicWord parallel_sweeping_;
681
682   // PagedSpace free-list statistics.
683   intptr_t available_in_small_free_list_;
684   intptr_t available_in_medium_free_list_;
685   intptr_t available_in_large_free_list_;
686   intptr_t available_in_huge_free_list_;
687   intptr_t non_available_small_blocks_;
688
689   static MemoryChunk* Initialize(Heap* heap, Address base, size_t size,
690                                  Address area_start, Address area_end,
691                                  Executability executable, Space* owner);
692
693  private:
694   // next_chunk_ holds a pointer of type MemoryChunk
695   base::AtomicWord next_chunk_;
696   // prev_chunk_ holds a pointer of type MemoryChunk
697   base::AtomicWord prev_chunk_;
698
699   friend class MemoryAllocator;
700 };
701
702
703 STATIC_ASSERT(sizeof(MemoryChunk) <= MemoryChunk::kHeaderSize);
704
705
706 // -----------------------------------------------------------------------------
707 // A page is a memory chunk of a size 1MB. Large object pages may be larger.
708 //
709 // The only way to get a page pointer is by calling factory methods:
710 //   Page* p = Page::FromAddress(addr); or
711 //   Page* p = Page::FromAllocationTop(top);
712 class Page : public MemoryChunk {
713  public:
714   // Returns the page containing a given address. The address ranges
715   // from [page_addr .. page_addr + kPageSize[
716   // This only works if the object is in fact in a page.  See also MemoryChunk::
717   // FromAddress() and FromAnyAddress().
718   INLINE(static Page* FromAddress(Address a)) {
719     return reinterpret_cast<Page*>(OffsetFrom(a) & ~kPageAlignmentMask);
720   }
721
722   // Returns the page containing an allocation top. Because an allocation
723   // top address can be the upper bound of the page, we need to subtract
724   // it with kPointerSize first. The address ranges from
725   // [page_addr + kObjectStartOffset .. page_addr + kPageSize].
726   INLINE(static Page* FromAllocationTop(Address top)) {
727     Page* p = FromAddress(top - kPointerSize);
728     return p;
729   }
730
731   // Returns the next page in the chain of pages owned by a space.
732   inline Page* next_page();
733   inline Page* prev_page();
734   inline void set_next_page(Page* page);
735   inline void set_prev_page(Page* page);
736
737   // Checks whether an address is page aligned.
738   static bool IsAlignedToPageSize(Address a) {
739     return 0 == (OffsetFrom(a) & kPageAlignmentMask);
740   }
741
742   // Returns the offset of a given address to this page.
743   INLINE(int Offset(Address a)) {
744     int offset = static_cast<int>(a - address());
745     return offset;
746   }
747
748   // Returns the address for a given offset to the this page.
749   Address OffsetToAddress(int offset) {
750     DCHECK_PAGE_OFFSET(offset);
751     return address() + offset;
752   }
753
754   // ---------------------------------------------------------------------
755
756   // Page size in bytes.  This must be a multiple of the OS page size.
757   static const int kPageSize = 1 << kPageSizeBits;
758
759   // Maximum object size that fits in a page. Objects larger than that size
760   // are allocated in large object space and are never moved in memory. This
761   // also applies to new space allocation, since objects are never migrated
762   // from new space to large object space.  Takes double alignment into account.
763   static const int kMaxRegularHeapObjectSize = kPageSize - kObjectStartOffset;
764
765   // Page size mask.
766   static const intptr_t kPageAlignmentMask = (1 << kPageSizeBits) - 1;
767
768   inline void ClearGCFields();
769
770   static inline Page* Initialize(Heap* heap, MemoryChunk* chunk,
771                                  Executability executable, PagedSpace* owner);
772
773   void InitializeAsAnchor(PagedSpace* owner);
774
775   bool WasSwept() { return IsFlagSet(WAS_SWEPT); }
776   void SetWasSwept() { SetFlag(WAS_SWEPT); }
777   void ClearWasSwept() { ClearFlag(WAS_SWEPT); }
778
779   void ResetFreeListStatistics();
780
781 #define FRAGMENTATION_STATS_ACCESSORS(type, name) \
782   type name() { return name##_; }                 \
783   void set_##name(type name) { name##_ = name; }  \
784   void add_##name(type name) { name##_ += name; }
785
786   FRAGMENTATION_STATS_ACCESSORS(intptr_t, non_available_small_blocks)
787   FRAGMENTATION_STATS_ACCESSORS(intptr_t, available_in_small_free_list)
788   FRAGMENTATION_STATS_ACCESSORS(intptr_t, available_in_medium_free_list)
789   FRAGMENTATION_STATS_ACCESSORS(intptr_t, available_in_large_free_list)
790   FRAGMENTATION_STATS_ACCESSORS(intptr_t, available_in_huge_free_list)
791
792 #undef FRAGMENTATION_STATS_ACCESSORS
793
794 #ifdef DEBUG
795   void Print();
796 #endif  // DEBUG
797
798   friend class MemoryAllocator;
799 };
800
801
802 STATIC_ASSERT(sizeof(Page) <= MemoryChunk::kHeaderSize);
803
804
805 class LargePage : public MemoryChunk {
806  public:
807   HeapObject* GetObject() { return HeapObject::FromAddress(area_start()); }
808
809   inline LargePage* next_page() const {
810     return static_cast<LargePage*>(next_chunk());
811   }
812
813   inline void set_next_page(LargePage* page) { set_next_chunk(page); }
814
815  private:
816   static inline LargePage* Initialize(Heap* heap, MemoryChunk* chunk);
817
818   friend class MemoryAllocator;
819 };
820
821 STATIC_ASSERT(sizeof(LargePage) <= MemoryChunk::kHeaderSize);
822
823 // ----------------------------------------------------------------------------
824 // Space is the abstract superclass for all allocation spaces.
825 class Space : public Malloced {
826  public:
827   Space(Heap* heap, AllocationSpace id, Executability executable)
828       : heap_(heap), id_(id), executable_(executable) {}
829
830   virtual ~Space() {}
831
832   Heap* heap() const { return heap_; }
833
834   // Does the space need executable memory?
835   Executability executable() { return executable_; }
836
837   // Identity used in error reporting.
838   AllocationSpace identity() { return id_; }
839
840   // Returns allocated size.
841   virtual intptr_t Size() = 0;
842
843   // Returns size of objects. Can differ from the allocated size
844   // (e.g. see LargeObjectSpace).
845   virtual intptr_t SizeOfObjects() { return Size(); }
846
847   virtual int RoundSizeDownToObjectAlignment(int size) {
848     if (id_ == CODE_SPACE) {
849       return RoundDown(size, kCodeAlignment);
850     } else {
851       return RoundDown(size, kPointerSize);
852     }
853   }
854
855 #ifdef DEBUG
856   virtual void Print() = 0;
857 #endif
858
859  private:
860   Heap* heap_;
861   AllocationSpace id_;
862   Executability executable_;
863 };
864
865
866 // ----------------------------------------------------------------------------
867 // All heap objects containing executable code (code objects) must be allocated
868 // from a 2 GB range of memory, so that they can call each other using 32-bit
869 // displacements.  This happens automatically on 32-bit platforms, where 32-bit
870 // displacements cover the entire 4GB virtual address space.  On 64-bit
871 // platforms, we support this using the CodeRange object, which reserves and
872 // manages a range of virtual memory.
873 class CodeRange {
874  public:
875   explicit CodeRange(Isolate* isolate);
876   ~CodeRange() { TearDown(); }
877
878   // Reserves a range of virtual memory, but does not commit any of it.
879   // Can only be called once, at heap initialization time.
880   // Returns false on failure.
881   bool SetUp(size_t requested_size);
882
883   // Frees the range of virtual memory, and frees the data structures used to
884   // manage it.
885   void TearDown();
886
887   bool valid() { return code_range_ != NULL; }
888   Address start() {
889     DCHECK(valid());
890     return static_cast<Address>(code_range_->address());
891   }
892   size_t size() {
893     DCHECK(valid());
894     return code_range_->size();
895   }
896   bool contains(Address address) {
897     if (!valid()) return false;
898     Address start = static_cast<Address>(code_range_->address());
899     return start <= address && address < start + code_range_->size();
900   }
901
902   // Allocates a chunk of memory from the large-object portion of
903   // the code range.  On platforms with no separate code range, should
904   // not be called.
905   MUST_USE_RESULT Address AllocateRawMemory(const size_t requested_size,
906                                             const size_t commit_size,
907                                             size_t* allocated);
908   bool CommitRawMemory(Address start, size_t length);
909   bool UncommitRawMemory(Address start, size_t length);
910   void FreeRawMemory(Address buf, size_t length);
911
912   void ReserveEmergencyBlock();
913   void ReleaseEmergencyBlock();
914
915  private:
916   Isolate* isolate_;
917
918   // The reserved range of virtual memory that all code objects are put in.
919   base::VirtualMemory* code_range_;
920   // Plain old data class, just a struct plus a constructor.
921   class FreeBlock {
922    public:
923     FreeBlock() : start(0), size(0) {}
924     FreeBlock(Address start_arg, size_t size_arg)
925         : start(start_arg), size(size_arg) {
926       DCHECK(IsAddressAligned(start, MemoryChunk::kAlignment));
927       DCHECK(size >= static_cast<size_t>(Page::kPageSize));
928     }
929     FreeBlock(void* start_arg, size_t size_arg)
930         : start(static_cast<Address>(start_arg)), size(size_arg) {
931       DCHECK(IsAddressAligned(start, MemoryChunk::kAlignment));
932       DCHECK(size >= static_cast<size_t>(Page::kPageSize));
933     }
934
935     Address start;
936     size_t size;
937   };
938
939   // Freed blocks of memory are added to the free list.  When the allocation
940   // list is exhausted, the free list is sorted and merged to make the new
941   // allocation list.
942   List<FreeBlock> free_list_;
943   // Memory is allocated from the free blocks on the allocation list.
944   // The block at current_allocation_block_index_ is the current block.
945   List<FreeBlock> allocation_list_;
946   int current_allocation_block_index_;
947
948   // Emergency block guarantees that we can always allocate a page for
949   // evacuation candidates when code space is compacted. Emergency block is
950   // reserved immediately after GC and is released immedietely before
951   // allocating a page for evacuation.
952   FreeBlock emergency_block_;
953
954   // Finds a block on the allocation list that contains at least the
955   // requested amount of memory.  If none is found, sorts and merges
956   // the existing free memory blocks, and searches again.
957   // If none can be found, returns false.
958   bool GetNextAllocationBlock(size_t requested);
959   // Compares the start addresses of two free blocks.
960   static int CompareFreeBlockAddress(const FreeBlock* left,
961                                      const FreeBlock* right);
962   bool ReserveBlock(const size_t requested_size, FreeBlock* block);
963   void ReleaseBlock(const FreeBlock* block);
964
965   DISALLOW_COPY_AND_ASSIGN(CodeRange);
966 };
967
968
969 class SkipList {
970  public:
971   SkipList() { Clear(); }
972
973   void Clear() {
974     for (int idx = 0; idx < kSize; idx++) {
975       starts_[idx] = reinterpret_cast<Address>(-1);
976     }
977   }
978
979   Address StartFor(Address addr) { return starts_[RegionNumber(addr)]; }
980
981   void AddObject(Address addr, int size) {
982     int start_region = RegionNumber(addr);
983     int end_region = RegionNumber(addr + size - kPointerSize);
984     for (int idx = start_region; idx <= end_region; idx++) {
985       if (starts_[idx] > addr) starts_[idx] = addr;
986     }
987   }
988
989   static inline int RegionNumber(Address addr) {
990     return (OffsetFrom(addr) & Page::kPageAlignmentMask) >> kRegionSizeLog2;
991   }
992
993   static void Update(Address addr, int size) {
994     Page* page = Page::FromAddress(addr);
995     SkipList* list = page->skip_list();
996     if (list == NULL) {
997       list = new SkipList();
998       page->set_skip_list(list);
999     }
1000
1001     list->AddObject(addr, size);
1002   }
1003
1004  private:
1005   static const int kRegionSizeLog2 = 13;
1006   static const int kRegionSize = 1 << kRegionSizeLog2;
1007   static const int kSize = Page::kPageSize / kRegionSize;
1008
1009   STATIC_ASSERT(Page::kPageSize % kRegionSize == 0);
1010
1011   Address starts_[kSize];
1012 };
1013
1014
1015 // ----------------------------------------------------------------------------
1016 // A space acquires chunks of memory from the operating system. The memory
1017 // allocator allocated and deallocates pages for the paged heap spaces and large
1018 // pages for large object space.
1019 //
1020 // Each space has to manage it's own pages.
1021 //
1022 class MemoryAllocator {
1023  public:
1024   explicit MemoryAllocator(Isolate* isolate);
1025
1026   // Initializes its internal bookkeeping structures.
1027   // Max capacity of the total space and executable memory limit.
1028   bool SetUp(intptr_t max_capacity, intptr_t capacity_executable);
1029
1030   void TearDown();
1031
1032   Page* AllocatePage(intptr_t size, PagedSpace* owner,
1033                      Executability executable);
1034
1035   LargePage* AllocateLargePage(intptr_t object_size, Space* owner,
1036                                Executability executable);
1037
1038   void Free(MemoryChunk* chunk);
1039
1040   // Returns the maximum available bytes of heaps.
1041   intptr_t Available() { return capacity_ < size_ ? 0 : capacity_ - size_; }
1042
1043   // Returns allocated spaces in bytes.
1044   intptr_t Size() { return size_; }
1045
1046   // Returns the maximum available executable bytes of heaps.
1047   intptr_t AvailableExecutable() {
1048     if (capacity_executable_ < size_executable_) return 0;
1049     return capacity_executable_ - size_executable_;
1050   }
1051
1052   // Returns allocated executable spaces in bytes.
1053   intptr_t SizeExecutable() { return size_executable_; }
1054
1055   // Returns maximum available bytes that the old space can have.
1056   intptr_t MaxAvailable() {
1057     return (Available() / Page::kPageSize) * Page::kMaxRegularHeapObjectSize;
1058   }
1059
1060   // Returns an indication of whether a pointer is in a space that has
1061   // been allocated by this MemoryAllocator.
1062   V8_INLINE bool IsOutsideAllocatedSpace(const void* address) const {
1063     return address < lowest_ever_allocated_ ||
1064            address >= highest_ever_allocated_;
1065   }
1066
1067 #ifdef DEBUG
1068   // Reports statistic info of the space.
1069   void ReportStatistics();
1070 #endif
1071
1072   // Returns a MemoryChunk in which the memory region from commit_area_size to
1073   // reserve_area_size of the chunk area is reserved but not committed, it
1074   // could be committed later by calling MemoryChunk::CommitArea.
1075   MemoryChunk* AllocateChunk(intptr_t reserve_area_size,
1076                              intptr_t commit_area_size,
1077                              Executability executable, Space* space);
1078
1079   Address ReserveAlignedMemory(size_t requested, size_t alignment,
1080                                base::VirtualMemory* controller);
1081   Address AllocateAlignedMemory(size_t reserve_size, size_t commit_size,
1082                                 size_t alignment, Executability executable,
1083                                 base::VirtualMemory* controller);
1084
1085   bool CommitMemory(Address addr, size_t size, Executability executable);
1086
1087   void FreeMemory(base::VirtualMemory* reservation, Executability executable);
1088   void FreeMemory(Address addr, size_t size, Executability executable);
1089
1090   // Commit a contiguous block of memory from the initial chunk.  Assumes that
1091   // the address is not NULL, the size is greater than zero, and that the
1092   // block is contained in the initial chunk.  Returns true if it succeeded
1093   // and false otherwise.
1094   bool CommitBlock(Address start, size_t size, Executability executable);
1095
1096   // Uncommit a contiguous block of memory [start..(start+size)[.
1097   // start is not NULL, the size is greater than zero, and the
1098   // block is contained in the initial chunk.  Returns true if it succeeded
1099   // and false otherwise.
1100   bool UncommitBlock(Address start, size_t size);
1101
1102   // Zaps a contiguous block of memory [start..(start+size)[ thus
1103   // filling it up with a recognizable non-NULL bit pattern.
1104   void ZapBlock(Address start, size_t size);
1105
1106   void PerformAllocationCallback(ObjectSpace space, AllocationAction action,
1107                                  size_t size);
1108
1109   void AddMemoryAllocationCallback(MemoryAllocationCallback callback,
1110                                    ObjectSpace space, AllocationAction action);
1111
1112   void RemoveMemoryAllocationCallback(MemoryAllocationCallback callback);
1113
1114   bool MemoryAllocationCallbackRegistered(MemoryAllocationCallback callback);
1115
1116   static int CodePageGuardStartOffset();
1117
1118   static int CodePageGuardSize();
1119
1120   static int CodePageAreaStartOffset();
1121
1122   static int CodePageAreaEndOffset();
1123
1124   static int CodePageAreaSize() {
1125     return CodePageAreaEndOffset() - CodePageAreaStartOffset();
1126   }
1127
1128   static int PageAreaSize(AllocationSpace space) {
1129     DCHECK_NE(LO_SPACE, space);
1130     return (space == CODE_SPACE) ? CodePageAreaSize()
1131                                  : Page::kMaxRegularHeapObjectSize;
1132   }
1133
1134   MUST_USE_RESULT bool CommitExecutableMemory(base::VirtualMemory* vm,
1135                                               Address start, size_t commit_size,
1136                                               size_t reserved_size);
1137
1138  private:
1139   Isolate* isolate_;
1140
1141   // Maximum space size in bytes.
1142   size_t capacity_;
1143   // Maximum subset of capacity_ that can be executable
1144   size_t capacity_executable_;
1145
1146   // Allocated space size in bytes.
1147   size_t size_;
1148   // Allocated executable space size in bytes.
1149   size_t size_executable_;
1150
1151   // We keep the lowest and highest addresses allocated as a quick way
1152   // of determining that pointers are outside the heap. The estimate is
1153   // conservative, i.e. not all addrsses in 'allocated' space are allocated
1154   // to our heap. The range is [lowest, highest[, inclusive on the low end
1155   // and exclusive on the high end.
1156   void* lowest_ever_allocated_;
1157   void* highest_ever_allocated_;
1158
1159   struct MemoryAllocationCallbackRegistration {
1160     MemoryAllocationCallbackRegistration(MemoryAllocationCallback callback,
1161                                          ObjectSpace space,
1162                                          AllocationAction action)
1163         : callback(callback), space(space), action(action) {}
1164     MemoryAllocationCallback callback;
1165     ObjectSpace space;
1166     AllocationAction action;
1167   };
1168
1169   // A List of callback that are triggered when memory is allocated or free'd
1170   List<MemoryAllocationCallbackRegistration> memory_allocation_callbacks_;
1171
1172   // Initializes pages in a chunk. Returns the first page address.
1173   // This function and GetChunkId() are provided for the mark-compact
1174   // collector to rebuild page headers in the from space, which is
1175   // used as a marking stack and its page headers are destroyed.
1176   Page* InitializePagesInChunk(int chunk_id, int pages_in_chunk,
1177                                PagedSpace* owner);
1178
1179   void UpdateAllocatedSpaceLimits(void* low, void* high) {
1180     lowest_ever_allocated_ = Min(lowest_ever_allocated_, low);
1181     highest_ever_allocated_ = Max(highest_ever_allocated_, high);
1182   }
1183
1184   DISALLOW_IMPLICIT_CONSTRUCTORS(MemoryAllocator);
1185 };
1186
1187
1188 // -----------------------------------------------------------------------------
1189 // Interface for heap object iterator to be implemented by all object space
1190 // object iterators.
1191 //
1192 // NOTE: The space specific object iterators also implements the own next()
1193 //       method which is used to avoid using virtual functions
1194 //       iterating a specific space.
1195
1196 class ObjectIterator : public Malloced {
1197  public:
1198   virtual ~ObjectIterator() {}
1199
1200   virtual HeapObject* next_object() = 0;
1201 };
1202
1203
1204 // -----------------------------------------------------------------------------
1205 // Heap object iterator in new/old/map spaces.
1206 //
1207 // A HeapObjectIterator iterates objects from the bottom of the given space
1208 // to its top or from the bottom of the given page to its top.
1209 //
1210 // If objects are allocated in the page during iteration the iterator may
1211 // or may not iterate over those objects.  The caller must create a new
1212 // iterator in order to be sure to visit these new objects.
1213 class HeapObjectIterator : public ObjectIterator {
1214  public:
1215   // Creates a new object iterator in a given space.
1216   // If the size function is not given, the iterator calls the default
1217   // Object::Size().
1218   explicit HeapObjectIterator(PagedSpace* space);
1219   HeapObjectIterator(PagedSpace* space, HeapObjectCallback size_func);
1220   HeapObjectIterator(Page* page, HeapObjectCallback size_func);
1221
1222   // Advance to the next object, skipping free spaces and other fillers and
1223   // skipping the special garbage section of which there is one per space.
1224   // Returns NULL when the iteration has ended.
1225   inline HeapObject* Next() {
1226     do {
1227       HeapObject* next_obj = FromCurrentPage();
1228       if (next_obj != NULL) return next_obj;
1229     } while (AdvanceToNextPage());
1230     return NULL;
1231   }
1232
1233   virtual HeapObject* next_object() { return Next(); }
1234
1235  private:
1236   enum PageMode { kOnePageOnly, kAllPagesInSpace };
1237
1238   Address cur_addr_;              // Current iteration point.
1239   Address cur_end_;               // End iteration point.
1240   HeapObjectCallback size_func_;  // Size function or NULL.
1241   PagedSpace* space_;
1242   PageMode page_mode_;
1243
1244   // Fast (inlined) path of next().
1245   inline HeapObject* FromCurrentPage();
1246
1247   // Slow path of next(), goes into the next page.  Returns false if the
1248   // iteration has ended.
1249   bool AdvanceToNextPage();
1250
1251   // Initializes fields.
1252   inline void Initialize(PagedSpace* owner, Address start, Address end,
1253                          PageMode mode, HeapObjectCallback size_func);
1254 };
1255
1256
1257 // -----------------------------------------------------------------------------
1258 // A PageIterator iterates the pages in a paged space.
1259
1260 class PageIterator BASE_EMBEDDED {
1261  public:
1262   explicit inline PageIterator(PagedSpace* space);
1263
1264   inline bool has_next();
1265   inline Page* next();
1266
1267  private:
1268   PagedSpace* space_;
1269   Page* prev_page_;  // Previous page returned.
1270   // Next page that will be returned.  Cached here so that we can use this
1271   // iterator for operations that deallocate pages.
1272   Page* next_page_;
1273 };
1274
1275
1276 // -----------------------------------------------------------------------------
1277 // A space has a circular list of pages. The next page can be accessed via
1278 // Page::next_page() call.
1279
1280 // An abstraction of allocation and relocation pointers in a page-structured
1281 // space.
1282 class AllocationInfo {
1283  public:
1284   AllocationInfo() : top_(NULL), limit_(NULL) {}
1285
1286   INLINE(void set_top(Address top)) {
1287     SLOW_DCHECK(top == NULL ||
1288                 (reinterpret_cast<intptr_t>(top) & kHeapObjectTagMask) == 0);
1289     top_ = top;
1290   }
1291
1292   INLINE(Address top()) const {
1293     SLOW_DCHECK(top_ == NULL ||
1294                 (reinterpret_cast<intptr_t>(top_) & kHeapObjectTagMask) == 0);
1295     return top_;
1296   }
1297
1298   Address* top_address() { return &top_; }
1299
1300   INLINE(void set_limit(Address limit)) {
1301     SLOW_DCHECK(limit == NULL ||
1302                 (reinterpret_cast<intptr_t>(limit) & kHeapObjectTagMask) == 0);
1303     limit_ = limit;
1304   }
1305
1306   INLINE(Address limit()) const {
1307     SLOW_DCHECK(limit_ == NULL ||
1308                 (reinterpret_cast<intptr_t>(limit_) & kHeapObjectTagMask) ==
1309                     0);
1310     return limit_;
1311   }
1312
1313   Address* limit_address() { return &limit_; }
1314
1315 #ifdef DEBUG
1316   bool VerifyPagedAllocation() {
1317     return (Page::FromAllocationTop(top_) == Page::FromAllocationTop(limit_)) &&
1318            (top_ <= limit_);
1319   }
1320 #endif
1321
1322  private:
1323   // Current allocation top.
1324   Address top_;
1325   // Current allocation limit.
1326   Address limit_;
1327 };
1328
1329
1330 // An abstraction of the accounting statistics of a page-structured space.
1331 // The 'capacity' of a space is the number of object-area bytes (i.e., not
1332 // including page bookkeeping structures) currently in the space. The 'size'
1333 // of a space is the number of allocated bytes, the 'waste' in the space is
1334 // the number of bytes that are not allocated and not available to
1335 // allocation without reorganizing the space via a GC (e.g. small blocks due
1336 // to internal fragmentation, top of page areas in map space), and the bytes
1337 // 'available' is the number of unallocated bytes that are not waste.  The
1338 // capacity is the sum of size, waste, and available.
1339 //
1340 // The stats are only set by functions that ensure they stay balanced. These
1341 // functions increase or decrease one of the non-capacity stats in
1342 // conjunction with capacity, or else they always balance increases and
1343 // decreases to the non-capacity stats.
1344 class AllocationStats BASE_EMBEDDED {
1345  public:
1346   AllocationStats() { Clear(); }
1347
1348   // Zero out all the allocation statistics (i.e., no capacity).
1349   void Clear() {
1350     capacity_ = 0;
1351     max_capacity_ = 0;
1352     size_ = 0;
1353     waste_ = 0;
1354   }
1355
1356   void ClearSizeWaste() {
1357     size_ = capacity_;
1358     waste_ = 0;
1359   }
1360
1361   // Reset the allocation statistics (i.e., available = capacity with no
1362   // wasted or allocated bytes).
1363   void Reset() {
1364     size_ = 0;
1365     waste_ = 0;
1366   }
1367
1368   // Accessors for the allocation statistics.
1369   intptr_t Capacity() { return capacity_; }
1370   intptr_t MaxCapacity() { return max_capacity_; }
1371   intptr_t Size() { return size_; }
1372   intptr_t Waste() { return waste_; }
1373
1374   // Grow the space by adding available bytes.  They are initially marked as
1375   // being in use (part of the size), but will normally be immediately freed,
1376   // putting them on the free list and removing them from size_.
1377   void ExpandSpace(int size_in_bytes) {
1378     capacity_ += size_in_bytes;
1379     size_ += size_in_bytes;
1380     if (capacity_ > max_capacity_) {
1381       max_capacity_ = capacity_;
1382     }
1383     DCHECK(size_ >= 0);
1384   }
1385
1386   // Shrink the space by removing available bytes.  Since shrinking is done
1387   // during sweeping, bytes have been marked as being in use (part of the size)
1388   // and are hereby freed.
1389   void ShrinkSpace(int size_in_bytes) {
1390     capacity_ -= size_in_bytes;
1391     size_ -= size_in_bytes;
1392     DCHECK(size_ >= 0);
1393   }
1394
1395   // Allocate from available bytes (available -> size).
1396   void AllocateBytes(intptr_t size_in_bytes) {
1397     size_ += size_in_bytes;
1398     DCHECK(size_ >= 0);
1399   }
1400
1401   // Free allocated bytes, making them available (size -> available).
1402   void DeallocateBytes(intptr_t size_in_bytes) {
1403     size_ -= size_in_bytes;
1404     DCHECK(size_ >= 0);
1405   }
1406
1407   // Waste free bytes (available -> waste).
1408   void WasteBytes(int size_in_bytes) {
1409     DCHECK(size_in_bytes >= 0);
1410     waste_ += size_in_bytes;
1411   }
1412
1413  private:
1414   intptr_t capacity_;
1415   intptr_t max_capacity_;
1416   intptr_t size_;
1417   intptr_t waste_;
1418 };
1419
1420
1421 // -----------------------------------------------------------------------------
1422 // Free lists for old object spaces
1423
1424 // The free list category holds a pointer to the top element and a pointer to
1425 // the end element of the linked list of free memory blocks.
1426 class FreeListCategory {
1427  public:
1428   FreeListCategory() : top_(0), end_(NULL), available_(0) {}
1429
1430   intptr_t Concatenate(FreeListCategory* category);
1431
1432   void Reset();
1433
1434   void Free(FreeSpace* node, int size_in_bytes);
1435
1436   FreeSpace* PickNodeFromList(int* node_size);
1437   FreeSpace* PickNodeFromList(int size_in_bytes, int* node_size);
1438
1439   intptr_t EvictFreeListItemsInList(Page* p);
1440   bool ContainsPageFreeListItemsInList(Page* p);
1441
1442   void RepairFreeList(Heap* heap);
1443
1444   FreeSpace* top() const {
1445     return reinterpret_cast<FreeSpace*>(base::NoBarrier_Load(&top_));
1446   }
1447
1448   void set_top(FreeSpace* top) {
1449     base::NoBarrier_Store(&top_, reinterpret_cast<base::AtomicWord>(top));
1450   }
1451
1452   FreeSpace* end() const { return end_; }
1453   void set_end(FreeSpace* end) { end_ = end; }
1454
1455   int* GetAvailableAddress() { return &available_; }
1456   int available() const { return available_; }
1457   void set_available(int available) { available_ = available; }
1458
1459   base::Mutex* mutex() { return &mutex_; }
1460
1461   bool IsEmpty() { return top() == 0; }
1462
1463 #ifdef DEBUG
1464   intptr_t SumFreeList();
1465   int FreeListLength();
1466 #endif
1467
1468  private:
1469   // top_ points to the top FreeSpace* in the free list category.
1470   base::AtomicWord top_;
1471   FreeSpace* end_;
1472   base::Mutex mutex_;
1473
1474   // Total available bytes in all blocks of this free list category.
1475   int available_;
1476 };
1477
1478
1479 // The free list for the old space.  The free list is organized in such a way
1480 // as to encourage objects allocated around the same time to be near each
1481 // other.  The normal way to allocate is intended to be by bumping a 'top'
1482 // pointer until it hits a 'limit' pointer.  When the limit is hit we need to
1483 // find a new space to allocate from.  This is done with the free list, which
1484 // is divided up into rough categories to cut down on waste.  Having finer
1485 // categories would scatter allocation more.
1486
1487 // The old space free list is organized in categories.
1488 // 1-31 words:  Such small free areas are discarded for efficiency reasons.
1489 //     They can be reclaimed by the compactor.  However the distance between top
1490 //     and limit may be this small.
1491 // 32-255 words: There is a list of spaces this large.  It is used for top and
1492 //     limit when the object we need to allocate is 1-31 words in size.  These
1493 //     spaces are called small.
1494 // 256-2047 words: There is a list of spaces this large.  It is used for top and
1495 //     limit when the object we need to allocate is 32-255 words in size.  These
1496 //     spaces are called medium.
1497 // 1048-16383 words: There is a list of spaces this large.  It is used for top
1498 //     and limit when the object we need to allocate is 256-2047 words in size.
1499 //     These spaces are call large.
1500 // At least 16384 words.  This list is for objects of 2048 words or larger.
1501 //     Empty pages are added to this list.  These spaces are called huge.
1502 class FreeList {
1503  public:
1504   explicit FreeList(PagedSpace* owner);
1505
1506   intptr_t Concatenate(FreeList* free_list);
1507
1508   // Clear the free list.
1509   void Reset();
1510
1511   // Return the number of bytes available on the free list.
1512   intptr_t available() {
1513     return small_list_.available() + medium_list_.available() +
1514            large_list_.available() + huge_list_.available();
1515   }
1516
1517   // Place a node on the free list.  The block of size 'size_in_bytes'
1518   // starting at 'start' is placed on the free list.  The return value is the
1519   // number of bytes that have been lost due to internal fragmentation by
1520   // freeing the block.  Bookkeeping information will be written to the block,
1521   // i.e., its contents will be destroyed.  The start address should be word
1522   // aligned, and the size should be a non-zero multiple of the word size.
1523   int Free(Address start, int size_in_bytes);
1524
1525   // This method returns how much memory can be allocated after freeing
1526   // maximum_freed memory.
1527   static inline int GuaranteedAllocatable(int maximum_freed) {
1528     if (maximum_freed < kSmallListMin) {
1529       return 0;
1530     } else if (maximum_freed <= kSmallListMax) {
1531       return kSmallAllocationMax;
1532     } else if (maximum_freed <= kMediumListMax) {
1533       return kMediumAllocationMax;
1534     } else if (maximum_freed <= kLargeListMax) {
1535       return kLargeAllocationMax;
1536     }
1537     return maximum_freed;
1538   }
1539
1540   // Allocate a block of size 'size_in_bytes' from the free list.  The block
1541   // is unitialized.  A failure is returned if no block is available.  The
1542   // number of bytes lost to fragmentation is returned in the output parameter
1543   // 'wasted_bytes'.  The size should be a non-zero multiple of the word size.
1544   MUST_USE_RESULT HeapObject* Allocate(int size_in_bytes);
1545
1546   bool IsEmpty() {
1547     return small_list_.IsEmpty() && medium_list_.IsEmpty() &&
1548            large_list_.IsEmpty() && huge_list_.IsEmpty();
1549   }
1550
1551 #ifdef DEBUG
1552   void Zap();
1553   intptr_t SumFreeLists();
1554   bool IsVeryLong();
1555 #endif
1556
1557   // Used after booting the VM.
1558   void RepairLists(Heap* heap);
1559
1560   intptr_t EvictFreeListItems(Page* p);
1561   bool ContainsPageFreeListItems(Page* p);
1562
1563   FreeListCategory* small_list() { return &small_list_; }
1564   FreeListCategory* medium_list() { return &medium_list_; }
1565   FreeListCategory* large_list() { return &large_list_; }
1566   FreeListCategory* huge_list() { return &huge_list_; }
1567
1568   static const int kSmallListMin = 0x20 * kPointerSize;
1569
1570  private:
1571   // The size range of blocks, in bytes.
1572   static const int kMinBlockSize = 3 * kPointerSize;
1573   static const int kMaxBlockSize = Page::kMaxRegularHeapObjectSize;
1574
1575   FreeSpace* FindNodeFor(int size_in_bytes, int* node_size);
1576
1577   PagedSpace* owner_;
1578   Heap* heap_;
1579
1580   static const int kSmallListMax = 0xff * kPointerSize;
1581   static const int kMediumListMax = 0x7ff * kPointerSize;
1582   static const int kLargeListMax = 0x3fff * kPointerSize;
1583   static const int kSmallAllocationMax = kSmallListMin - kPointerSize;
1584   static const int kMediumAllocationMax = kSmallListMax;
1585   static const int kLargeAllocationMax = kMediumListMax;
1586   FreeListCategory small_list_;
1587   FreeListCategory medium_list_;
1588   FreeListCategory large_list_;
1589   FreeListCategory huge_list_;
1590
1591   DISALLOW_IMPLICIT_CONSTRUCTORS(FreeList);
1592 };
1593
1594
1595 class AllocationResult {
1596  public:
1597   // Implicit constructor from Object*.
1598   AllocationResult(Object* object)  // NOLINT
1599       : object_(object) {
1600     // AllocationResults can't return Smis, which are used to represent
1601     // failure and the space to retry in.
1602     CHECK(!object->IsSmi());
1603   }
1604
1605   AllocationResult() : object_(Smi::FromInt(NEW_SPACE)) {}
1606
1607   static inline AllocationResult Retry(AllocationSpace space = NEW_SPACE) {
1608     return AllocationResult(space);
1609   }
1610
1611   inline bool IsRetry() { return object_->IsSmi(); }
1612
1613   template <typename T>
1614   bool To(T** obj) {
1615     if (IsRetry()) return false;
1616     *obj = T::cast(object_);
1617     return true;
1618   }
1619
1620   Object* ToObjectChecked() {
1621     CHECK(!IsRetry());
1622     return object_;
1623   }
1624
1625   AllocationSpace RetrySpace() {
1626     DCHECK(IsRetry());
1627     return static_cast<AllocationSpace>(Smi::cast(object_)->value());
1628   }
1629
1630  private:
1631   explicit AllocationResult(AllocationSpace space)
1632       : object_(Smi::FromInt(static_cast<int>(space))) {}
1633
1634   Object* object_;
1635 };
1636
1637
1638 STATIC_ASSERT(sizeof(AllocationResult) == kPointerSize);
1639
1640
1641 class PagedSpace : public Space {
1642  public:
1643   // Creates a space with a maximum capacity, and an id.
1644   PagedSpace(Heap* heap, intptr_t max_capacity, AllocationSpace id,
1645              Executability executable);
1646
1647   virtual ~PagedSpace() {}
1648
1649   // Set up the space using the given address range of virtual memory (from
1650   // the memory allocator's initial chunk) if possible.  If the block of
1651   // addresses is not big enough to contain a single page-aligned page, a
1652   // fresh chunk will be allocated.
1653   bool SetUp();
1654
1655   // Returns true if the space has been successfully set up and not
1656   // subsequently torn down.
1657   bool HasBeenSetUp();
1658
1659   // Cleans up the space, frees all pages in this space except those belonging
1660   // to the initial chunk, uncommits addresses in the initial chunk.
1661   void TearDown();
1662
1663   // Checks whether an object/address is in this space.
1664   inline bool Contains(Address a);
1665   bool Contains(HeapObject* o) { return Contains(o->address()); }
1666   // Unlike Contains() methods it is safe to call this one even for addresses
1667   // of unmapped memory.
1668   bool ContainsSafe(Address addr);
1669
1670   // Given an address occupied by a live object, return that object if it is
1671   // in this space, or a Smi if it is not.  The implementation iterates over
1672   // objects in the page containing the address, the cost is linear in the
1673   // number of objects in the page.  It may be slow.
1674   Object* FindObject(Address addr);
1675
1676   // During boot the free_space_map is created, and afterwards we may need
1677   // to write it into the free list nodes that were already created.
1678   void RepairFreeListsAfterDeserialization();
1679
1680   // Prepares for a mark-compact GC.
1681   void PrepareForMarkCompact();
1682
1683   // Current capacity without growing (Size() + Available()).
1684   intptr_t Capacity() { return accounting_stats_.Capacity(); }
1685
1686   // Total amount of memory committed for this space.  For paged
1687   // spaces this equals the capacity.
1688   intptr_t CommittedMemory() { return Capacity(); }
1689
1690   // The maximum amount of memory ever committed for this space.
1691   intptr_t MaximumCommittedMemory() { return accounting_stats_.MaxCapacity(); }
1692
1693   // Approximate amount of physical memory committed for this space.
1694   size_t CommittedPhysicalMemory();
1695
1696   struct SizeStats {
1697     intptr_t Total() {
1698       return small_size_ + medium_size_ + large_size_ + huge_size_;
1699     }
1700
1701     intptr_t small_size_;
1702     intptr_t medium_size_;
1703     intptr_t large_size_;
1704     intptr_t huge_size_;
1705   };
1706
1707   void ObtainFreeListStatistics(Page* p, SizeStats* sizes);
1708   void ResetFreeListStatistics();
1709
1710   // Sets the capacity, the available space and the wasted space to zero.
1711   // The stats are rebuilt during sweeping by adding each page to the
1712   // capacity and the size when it is encountered.  As free spaces are
1713   // discovered during the sweeping they are subtracted from the size and added
1714   // to the available and wasted totals.
1715   void ClearStats() {
1716     accounting_stats_.ClearSizeWaste();
1717     ResetFreeListStatistics();
1718   }
1719
1720   // Increases the number of available bytes of that space.
1721   void AddToAccountingStats(intptr_t bytes) {
1722     accounting_stats_.DeallocateBytes(bytes);
1723   }
1724
1725   // Available bytes without growing.  These are the bytes on the free list.
1726   // The bytes in the linear allocation area are not included in this total
1727   // because updating the stats would slow down allocation.  New pages are
1728   // immediately added to the free list so they show up here.
1729   intptr_t Available() { return free_list_.available(); }
1730
1731   // Allocated bytes in this space.  Garbage bytes that were not found due to
1732   // concurrent sweeping are counted as being allocated!  The bytes in the
1733   // current linear allocation area (between top and limit) are also counted
1734   // here.
1735   virtual intptr_t Size() { return accounting_stats_.Size(); }
1736
1737   // As size, but the bytes in lazily swept pages are estimated and the bytes
1738   // in the current linear allocation area are not included.
1739   virtual intptr_t SizeOfObjects();
1740
1741   // Wasted bytes in this space.  These are just the bytes that were thrown away
1742   // due to being too small to use for allocation.  They do not include the
1743   // free bytes that were not found at all due to lazy sweeping.
1744   virtual intptr_t Waste() { return accounting_stats_.Waste(); }
1745
1746   // Returns the allocation pointer in this space.
1747   Address top() { return allocation_info_.top(); }
1748   Address limit() { return allocation_info_.limit(); }
1749
1750   // The allocation top address.
1751   Address* allocation_top_address() { return allocation_info_.top_address(); }
1752
1753   // The allocation limit address.
1754   Address* allocation_limit_address() {
1755     return allocation_info_.limit_address();
1756   }
1757
1758   // Allocate the requested number of bytes in the space if possible, return a
1759   // failure object if not.
1760   MUST_USE_RESULT inline AllocationResult AllocateRaw(int size_in_bytes);
1761
1762   // Give a block of memory to the space's free list.  It might be added to
1763   // the free list or accounted as waste.
1764   // If add_to_freelist is false then just accounting stats are updated and
1765   // no attempt to add area to free list is made.
1766   int Free(Address start, int size_in_bytes) {
1767     int wasted = free_list_.Free(start, size_in_bytes);
1768     accounting_stats_.DeallocateBytes(size_in_bytes);
1769     accounting_stats_.WasteBytes(wasted);
1770     return size_in_bytes - wasted;
1771   }
1772
1773   void ResetFreeList() { free_list_.Reset(); }
1774
1775   // Set space allocation info.
1776   void SetTopAndLimit(Address top, Address limit) {
1777     DCHECK(top == limit ||
1778            Page::FromAddress(top) == Page::FromAddress(limit - 1));
1779     MemoryChunk::UpdateHighWaterMark(allocation_info_.top());
1780     allocation_info_.set_top(top);
1781     allocation_info_.set_limit(limit);
1782   }
1783
1784   // Empty space allocation info, returning unused area to free list.
1785   void EmptyAllocationInfo() {
1786     // Mark the old linear allocation area with a free space map so it can be
1787     // skipped when scanning the heap.
1788     int old_linear_size = static_cast<int>(limit() - top());
1789     Free(top(), old_linear_size);
1790     SetTopAndLimit(NULL, NULL);
1791   }
1792
1793   void Allocate(int bytes) { accounting_stats_.AllocateBytes(bytes); }
1794
1795   void IncreaseCapacity(int size);
1796
1797   // Releases an unused page and shrinks the space.
1798   void ReleasePage(Page* page);
1799
1800   // The dummy page that anchors the linked list of pages.
1801   Page* anchor() { return &anchor_; }
1802
1803 #ifdef VERIFY_HEAP
1804   // Verify integrity of this space.
1805   virtual void Verify(ObjectVisitor* visitor);
1806
1807   // Overridden by subclasses to verify space-specific object
1808   // properties (e.g., only maps or free-list nodes are in map space).
1809   virtual void VerifyObject(HeapObject* obj) {}
1810 #endif
1811
1812 #ifdef DEBUG
1813   // Print meta info and objects in this space.
1814   virtual void Print();
1815
1816   // Reports statistics for the space
1817   void ReportStatistics();
1818
1819   // Report code object related statistics
1820   void CollectCodeStatistics();
1821   static void ReportCodeStatistics(Isolate* isolate);
1822   static void ResetCodeStatistics(Isolate* isolate);
1823 #endif
1824
1825   // Evacuation candidates are swept by evacuator.  Needs to return a valid
1826   // result before _and_ after evacuation has finished.
1827   static bool ShouldBeSweptBySweeperThreads(Page* p) {
1828     return !p->IsEvacuationCandidate() &&
1829            !p->IsFlagSet(Page::RESCAN_ON_EVACUATION) && !p->WasSwept();
1830   }
1831
1832   void IncrementUnsweptFreeBytes(intptr_t by) { unswept_free_bytes_ += by; }
1833
1834   void IncreaseUnsweptFreeBytes(Page* p) {
1835     DCHECK(ShouldBeSweptBySweeperThreads(p));
1836     unswept_free_bytes_ += (p->area_size() - p->LiveBytes());
1837   }
1838
1839   void DecrementUnsweptFreeBytes(intptr_t by) { unswept_free_bytes_ -= by; }
1840
1841   void DecreaseUnsweptFreeBytes(Page* p) {
1842     DCHECK(ShouldBeSweptBySweeperThreads(p));
1843     unswept_free_bytes_ -= (p->area_size() - p->LiveBytes());
1844   }
1845
1846   void ResetUnsweptFreeBytes() { unswept_free_bytes_ = 0; }
1847
1848   // This function tries to steal size_in_bytes memory from the sweeper threads
1849   // free-lists. If it does not succeed stealing enough memory, it will wait
1850   // for the sweeper threads to finish sweeping.
1851   // It returns true when sweeping is completed and false otherwise.
1852   bool EnsureSweeperProgress(intptr_t size_in_bytes);
1853
1854   void set_end_of_unswept_pages(Page* page) { end_of_unswept_pages_ = page; }
1855
1856   Page* end_of_unswept_pages() { return end_of_unswept_pages_; }
1857
1858   Page* FirstPage() { return anchor_.next_page(); }
1859   Page* LastPage() { return anchor_.prev_page(); }
1860
1861   void EvictEvacuationCandidatesFromFreeLists();
1862
1863   bool CanExpand();
1864
1865   // Returns the number of total pages in this space.
1866   int CountTotalPages();
1867
1868   // Return size of allocatable area on a page in this space.
1869   inline int AreaSize() { return area_size_; }
1870
1871   void CreateEmergencyMemory();
1872   void FreeEmergencyMemory();
1873   void UseEmergencyMemory();
1874
1875   bool HasEmergencyMemory() { return emergency_memory_ != NULL; }
1876
1877  protected:
1878   FreeList* free_list() { return &free_list_; }
1879
1880   int area_size_;
1881
1882   // Maximum capacity of this space.
1883   intptr_t max_capacity_;
1884
1885   // Accounting information for this space.
1886   AllocationStats accounting_stats_;
1887
1888   // The dummy page that anchors the double linked list of pages.
1889   Page anchor_;
1890
1891   // The space's free list.
1892   FreeList free_list_;
1893
1894   // Normal allocation information.
1895   AllocationInfo allocation_info_;
1896
1897   // The number of free bytes which could be reclaimed by advancing the
1898   // concurrent sweeper threads.
1899   intptr_t unswept_free_bytes_;
1900
1901   // The sweeper threads iterate over the list of pointer and data space pages
1902   // and sweep these pages concurrently. They will stop sweeping after the
1903   // end_of_unswept_pages_ page.
1904   Page* end_of_unswept_pages_;
1905
1906   // Emergency memory is the memory of a full page for a given space, allocated
1907   // conservatively before evacuating a page. If compaction fails due to out
1908   // of memory error the emergency memory can be used to complete compaction.
1909   // If not used, the emergency memory is released after compaction.
1910   MemoryChunk* emergency_memory_;
1911
1912   // Expands the space by allocating a fixed number of pages. Returns false if
1913   // it cannot allocate requested number of pages from OS, or if the hard heap
1914   // size limit has been hit.
1915   bool Expand();
1916
1917   // Generic fast case allocation function that tries linear allocation at the
1918   // address denoted by top in allocation_info_.
1919   inline HeapObject* AllocateLinearly(int size_in_bytes);
1920
1921   // If sweeping is still in progress try to sweep unswept pages. If that is
1922   // not successful, wait for the sweeper threads and re-try free-list
1923   // allocation.
1924   MUST_USE_RESULT HeapObject* WaitForSweeperThreadsAndRetryAllocation(
1925       int size_in_bytes);
1926
1927   // Slow path of AllocateRaw.  This function is space-dependent.
1928   MUST_USE_RESULT HeapObject* SlowAllocateRaw(int size_in_bytes);
1929
1930   friend class PageIterator;
1931   friend class MarkCompactCollector;
1932 };
1933
1934
1935 class NumberAndSizeInfo BASE_EMBEDDED {
1936  public:
1937   NumberAndSizeInfo() : number_(0), bytes_(0) {}
1938
1939   int number() const { return number_; }
1940   void increment_number(int num) { number_ += num; }
1941
1942   int bytes() const { return bytes_; }
1943   void increment_bytes(int size) { bytes_ += size; }
1944
1945   void clear() {
1946     number_ = 0;
1947     bytes_ = 0;
1948   }
1949
1950  private:
1951   int number_;
1952   int bytes_;
1953 };
1954
1955
1956 // HistogramInfo class for recording a single "bar" of a histogram.  This
1957 // class is used for collecting statistics to print to the log file.
1958 class HistogramInfo : public NumberAndSizeInfo {
1959  public:
1960   HistogramInfo() : NumberAndSizeInfo() {}
1961
1962   const char* name() { return name_; }
1963   void set_name(const char* name) { name_ = name; }
1964
1965  private:
1966   const char* name_;
1967 };
1968
1969
1970 enum SemiSpaceId { kFromSpace = 0, kToSpace = 1 };
1971
1972
1973 class SemiSpace;
1974
1975
1976 class NewSpacePage : public MemoryChunk {
1977  public:
1978   // GC related flags copied from from-space to to-space when
1979   // flipping semispaces.
1980   static const intptr_t kCopyOnFlipFlagsMask =
1981       (1 << MemoryChunk::POINTERS_TO_HERE_ARE_INTERESTING) |
1982       (1 << MemoryChunk::POINTERS_FROM_HERE_ARE_INTERESTING) |
1983       (1 << MemoryChunk::SCAN_ON_SCAVENGE);
1984
1985   static const int kAreaSize = Page::kMaxRegularHeapObjectSize;
1986
1987   inline NewSpacePage* next_page() const {
1988     return static_cast<NewSpacePage*>(next_chunk());
1989   }
1990
1991   inline void set_next_page(NewSpacePage* page) { set_next_chunk(page); }
1992
1993   inline NewSpacePage* prev_page() const {
1994     return static_cast<NewSpacePage*>(prev_chunk());
1995   }
1996
1997   inline void set_prev_page(NewSpacePage* page) { set_prev_chunk(page); }
1998
1999   SemiSpace* semi_space() { return reinterpret_cast<SemiSpace*>(owner()); }
2000
2001   bool is_anchor() { return !this->InNewSpace(); }
2002
2003   static bool IsAtStart(Address addr) {
2004     return (reinterpret_cast<intptr_t>(addr) & Page::kPageAlignmentMask) ==
2005            kObjectStartOffset;
2006   }
2007
2008   static bool IsAtEnd(Address addr) {
2009     return (reinterpret_cast<intptr_t>(addr) & Page::kPageAlignmentMask) == 0;
2010   }
2011
2012   Address address() { return reinterpret_cast<Address>(this); }
2013
2014   // Finds the NewSpacePage containing the given address.
2015   static inline NewSpacePage* FromAddress(Address address_in_page) {
2016     Address page_start =
2017         reinterpret_cast<Address>(reinterpret_cast<uintptr_t>(address_in_page) &
2018                                   ~Page::kPageAlignmentMask);
2019     NewSpacePage* page = reinterpret_cast<NewSpacePage*>(page_start);
2020     return page;
2021   }
2022
2023   // Find the page for a limit address. A limit address is either an address
2024   // inside a page, or the address right after the last byte of a page.
2025   static inline NewSpacePage* FromLimit(Address address_limit) {
2026     return NewSpacePage::FromAddress(address_limit - 1);
2027   }
2028
2029   // Checks if address1 and address2 are on the same new space page.
2030   static inline bool OnSamePage(Address address1, Address address2) {
2031     return NewSpacePage::FromAddress(address1) ==
2032            NewSpacePage::FromAddress(address2);
2033   }
2034
2035  private:
2036   // Create a NewSpacePage object that is only used as anchor
2037   // for the doubly-linked list of real pages.
2038   explicit NewSpacePage(SemiSpace* owner) { InitializeAsAnchor(owner); }
2039
2040   static NewSpacePage* Initialize(Heap* heap, Address start,
2041                                   SemiSpace* semi_space);
2042
2043   // Intialize a fake NewSpacePage used as sentinel at the ends
2044   // of a doubly-linked list of real NewSpacePages.
2045   // Only uses the prev/next links, and sets flags to not be in new-space.
2046   void InitializeAsAnchor(SemiSpace* owner);
2047
2048   friend class SemiSpace;
2049   friend class SemiSpaceIterator;
2050 };
2051
2052
2053 // -----------------------------------------------------------------------------
2054 // SemiSpace in young generation
2055 //
2056 // A semispace is a contiguous chunk of memory holding page-like memory
2057 // chunks. The mark-compact collector  uses the memory of the first page in
2058 // the from space as a marking stack when tracing live objects.
2059
2060 class SemiSpace : public Space {
2061  public:
2062   // Constructor.
2063   SemiSpace(Heap* heap, SemiSpaceId semispace)
2064       : Space(heap, NEW_SPACE, NOT_EXECUTABLE),
2065         start_(NULL),
2066         age_mark_(NULL),
2067         id_(semispace),
2068         anchor_(this),
2069         current_page_(NULL) {}
2070
2071   // Sets up the semispace using the given chunk.
2072   void SetUp(Address start, int initial_capacity, int target_capacity,
2073              int maximum_capacity);
2074
2075   // Tear 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() { return start_ != NULL; }
2081
2082   // Grow the semispace to the new capacity.  The new capacity
2083   // requested must be larger than the current capacity and less than
2084   // the maximum capacity.
2085   bool GrowTo(int new_capacity);
2086
2087   // Shrinks the semispace to the new capacity.  The new capacity
2088   // requested must be more than the amount of used memory in the
2089   // semispace and less than the current capacity.
2090   bool ShrinkTo(int new_capacity);
2091
2092   // Sets the total capacity. Only possible when the space is not committed.
2093   bool SetTotalCapacity(int new_capacity);
2094
2095   // Returns the start address of the first page of the space.
2096   Address space_start() {
2097     DCHECK(anchor_.next_page() != &anchor_);
2098     return anchor_.next_page()->area_start();
2099   }
2100
2101   // Returns the start address of the current page of the space.
2102   Address page_low() { return current_page_->area_start(); }
2103
2104   // Returns one past the end address of the space.
2105   Address space_end() { return anchor_.prev_page()->area_end(); }
2106
2107   // Returns one past the end address of the current page of the space.
2108   Address page_high() { return current_page_->area_end(); }
2109
2110   bool AdvancePage() {
2111     NewSpacePage* next_page = current_page_->next_page();
2112     if (next_page == anchor()) return false;
2113     current_page_ = next_page;
2114     return true;
2115   }
2116
2117   // Resets the space to using the first page.
2118   void Reset();
2119
2120   // Age mark accessors.
2121   Address age_mark() { return age_mark_; }
2122   void set_age_mark(Address mark);
2123
2124   // True if the address is in the address range of this semispace (not
2125   // necessarily below the allocation pointer).
2126   bool Contains(Address a) {
2127     return (reinterpret_cast<uintptr_t>(a) & address_mask_) ==
2128            reinterpret_cast<uintptr_t>(start_);
2129   }
2130
2131   // True if the object is a heap object in the address range of this
2132   // semispace (not necessarily below the allocation pointer).
2133   bool Contains(Object* o) {
2134     return (reinterpret_cast<uintptr_t>(o) & object_mask_) == object_expected_;
2135   }
2136
2137   // If we don't have these here then SemiSpace will be abstract.  However
2138   // they should never be called.
2139   virtual intptr_t Size() {
2140     UNREACHABLE();
2141     return 0;
2142   }
2143
2144   bool is_committed() { return committed_; }
2145   bool Commit();
2146   bool Uncommit();
2147
2148   NewSpacePage* first_page() { return anchor_.next_page(); }
2149   NewSpacePage* current_page() { return current_page_; }
2150
2151 #ifdef VERIFY_HEAP
2152   virtual void Verify();
2153 #endif
2154
2155 #ifdef DEBUG
2156   virtual void Print();
2157   // Validate a range of of addresses in a SemiSpace.
2158   // The "from" address must be on a page prior to the "to" address,
2159   // in the linked page order, or it must be earlier on the same page.
2160   static void AssertValidRange(Address from, Address to);
2161 #else
2162   // Do nothing.
2163   inline static void AssertValidRange(Address from, Address to) {}
2164 #endif
2165
2166   // Returns the current total capacity of the semispace.
2167   int TotalCapacity() { return total_capacity_; }
2168
2169   // Returns the target for total capacity of the semispace.
2170   int TargetCapacity() { return target_capacity_; }
2171
2172   // Returns the maximum total capacity of the semispace.
2173   int MaximumTotalCapacity() { return maximum_total_capacity_; }
2174
2175   // Returns the initial capacity of the semispace.
2176   int InitialTotalCapacity() { return initial_total_capacity_; }
2177
2178   SemiSpaceId id() { return id_; }
2179
2180   static void Swap(SemiSpace* from, SemiSpace* to);
2181
2182   // Returns the maximum amount of memory ever committed by the semi space.
2183   size_t MaximumCommittedMemory() { return maximum_committed_; }
2184
2185   // Approximate amount of physical memory committed for this space.
2186   size_t CommittedPhysicalMemory();
2187
2188  private:
2189   // Flips the semispace between being from-space and to-space.
2190   // Copies the flags into the masked positions on all pages in the space.
2191   void FlipPages(intptr_t flags, intptr_t flag_mask);
2192
2193   // Updates Capacity and MaximumCommitted based on new capacity.
2194   void SetCapacity(int new_capacity);
2195
2196   NewSpacePage* anchor() { return &anchor_; }
2197
2198   // The current and maximum total capacity of the space.
2199   int total_capacity_;
2200   int target_capacity_;
2201   int maximum_total_capacity_;
2202   int initial_total_capacity_;
2203
2204   intptr_t maximum_committed_;
2205
2206   // The start address of the space.
2207   Address start_;
2208   // Used to govern object promotion during mark-compact collection.
2209   Address age_mark_;
2210
2211   // Masks and comparison values to test for containment in this semispace.
2212   uintptr_t address_mask_;
2213   uintptr_t object_mask_;
2214   uintptr_t object_expected_;
2215
2216   bool committed_;
2217   SemiSpaceId id_;
2218
2219   NewSpacePage anchor_;
2220   NewSpacePage* current_page_;
2221
2222   friend class SemiSpaceIterator;
2223   friend class NewSpacePageIterator;
2224
2225  public:
2226   TRACK_MEMORY("SemiSpace")
2227 };
2228
2229
2230 // A SemiSpaceIterator is an ObjectIterator that iterates over the active
2231 // semispace of the heap's new space.  It iterates over the objects in the
2232 // semispace from a given start address (defaulting to the bottom of the
2233 // semispace) to the top of the semispace.  New objects allocated after the
2234 // iterator is created are not iterated.
2235 class SemiSpaceIterator : public ObjectIterator {
2236  public:
2237   // Create an iterator over the objects in the given space.  If no start
2238   // address is given, the iterator starts from the bottom of the space.  If
2239   // no size function is given, the iterator calls Object::Size().
2240
2241   // Iterate over all of allocated to-space.
2242   explicit SemiSpaceIterator(NewSpace* space);
2243   // Iterate over all of allocated to-space, with a custome size function.
2244   SemiSpaceIterator(NewSpace* space, HeapObjectCallback size_func);
2245   // Iterate over part of allocated to-space, from start to the end
2246   // of allocation.
2247   SemiSpaceIterator(NewSpace* space, Address start);
2248   // Iterate from one address to another in the same semi-space.
2249   SemiSpaceIterator(Address from, Address to);
2250
2251   HeapObject* Next() {
2252     if (current_ == limit_) return NULL;
2253     if (NewSpacePage::IsAtEnd(current_)) {
2254       NewSpacePage* page = NewSpacePage::FromLimit(current_);
2255       page = page->next_page();
2256       DCHECK(!page->is_anchor());
2257       current_ = page->area_start();
2258       if (current_ == limit_) return NULL;
2259     }
2260
2261     HeapObject* object = HeapObject::FromAddress(current_);
2262     int size = (size_func_ == NULL) ? object->Size() : size_func_(object);
2263
2264     current_ += size;
2265     return object;
2266   }
2267
2268   // Implementation of the ObjectIterator functions.
2269   virtual HeapObject* next_object() { return Next(); }
2270
2271  private:
2272   void Initialize(Address start, Address end, HeapObjectCallback size_func);
2273
2274   // The current iteration point.
2275   Address current_;
2276   // The end of iteration.
2277   Address limit_;
2278   // The callback function.
2279   HeapObjectCallback size_func_;
2280 };
2281
2282
2283 // -----------------------------------------------------------------------------
2284 // A PageIterator iterates the pages in a semi-space.
2285 class NewSpacePageIterator BASE_EMBEDDED {
2286  public:
2287   // Make an iterator that runs over all pages in to-space.
2288   explicit inline NewSpacePageIterator(NewSpace* space);
2289
2290   // Make an iterator that runs over all pages in the given semispace,
2291   // even those not used in allocation.
2292   explicit inline NewSpacePageIterator(SemiSpace* space);
2293
2294   // Make iterator that iterates from the page containing start
2295   // to the page that contains limit in the same semispace.
2296   inline NewSpacePageIterator(Address start, Address limit);
2297
2298   inline bool has_next();
2299   inline NewSpacePage* next();
2300
2301  private:
2302   NewSpacePage* prev_page_;  // Previous page returned.
2303   // Next page that will be returned.  Cached here so that we can use this
2304   // iterator for operations that deallocate pages.
2305   NewSpacePage* next_page_;
2306   // Last page returned.
2307   NewSpacePage* last_page_;
2308 };
2309
2310
2311 // -----------------------------------------------------------------------------
2312 // The young generation space.
2313 //
2314 // The new space consists of a contiguous pair of semispaces.  It simply
2315 // forwards most functions to the appropriate semispace.
2316
2317 class NewSpace : public Space {
2318  public:
2319   // Constructor.
2320   explicit NewSpace(Heap* heap)
2321       : Space(heap, NEW_SPACE, NOT_EXECUTABLE),
2322         to_space_(heap, kToSpace),
2323         from_space_(heap, kFromSpace),
2324         reservation_(),
2325         inline_allocation_limit_step_(0) {}
2326
2327   // Sets up the new space using the given chunk.
2328   bool SetUp(int reserved_semispace_size_, int max_semi_space_size);
2329
2330   // Tears down the space.  Heap memory was not allocated by the space, so it
2331   // is not deallocated here.
2332   void TearDown();
2333
2334   // True if the space has been set up but not torn down.
2335   bool HasBeenSetUp() {
2336     return to_space_.HasBeenSetUp() && from_space_.HasBeenSetUp();
2337   }
2338
2339   // Flip the pair of spaces.
2340   void Flip();
2341
2342   // Grow the capacity of the semispaces.  Assumes that they are not at
2343   // their maximum capacity.
2344   void Grow();
2345
2346   // Grow the capacity of the semispaces by one page.
2347   bool GrowOnePage();
2348
2349   // Shrink the capacity of the semispaces.
2350   void Shrink();
2351
2352   // True if the address or object lies in the address range of either
2353   // semispace (not necessarily below the allocation pointer).
2354   bool Contains(Address a) {
2355     return (reinterpret_cast<uintptr_t>(a) & address_mask_) ==
2356            reinterpret_cast<uintptr_t>(start_);
2357   }
2358
2359   bool Contains(Object* o) {
2360     Address a = reinterpret_cast<Address>(o);
2361     return (reinterpret_cast<uintptr_t>(a) & object_mask_) == object_expected_;
2362   }
2363
2364   // Return the allocated bytes in the active semispace.
2365   virtual intptr_t Size() {
2366     return pages_used_ * NewSpacePage::kAreaSize +
2367            static_cast<int>(top() - to_space_.page_low());
2368   }
2369
2370   // The same, but returning an int.  We have to have the one that returns
2371   // intptr_t because it is inherited, but if we know we are dealing with the
2372   // new space, which can't get as big as the other spaces then this is useful:
2373   int SizeAsInt() { return static_cast<int>(Size()); }
2374
2375   // Return the allocatable capacity of a semispace.
2376   intptr_t Capacity() {
2377     SLOW_DCHECK(to_space_.TotalCapacity() == from_space_.TotalCapacity());
2378     return (to_space_.TotalCapacity() / Page::kPageSize) *
2379            NewSpacePage::kAreaSize;
2380   }
2381
2382   // Return the current size of a semispace, allocatable and non-allocatable
2383   // memory.
2384   intptr_t TotalCapacity() {
2385     DCHECK(to_space_.TotalCapacity() == from_space_.TotalCapacity());
2386     return to_space_.TotalCapacity();
2387   }
2388
2389   // Return the total amount of memory committed for new space.
2390   intptr_t CommittedMemory() {
2391     if (from_space_.is_committed()) return 2 * Capacity();
2392     return TotalCapacity();
2393   }
2394
2395   // Return the total amount of memory committed for new space.
2396   intptr_t MaximumCommittedMemory() {
2397     return to_space_.MaximumCommittedMemory() +
2398            from_space_.MaximumCommittedMemory();
2399   }
2400
2401   // Approximate amount of physical memory committed for this space.
2402   size_t CommittedPhysicalMemory();
2403
2404   // Return the available bytes without growing.
2405   intptr_t Available() { return Capacity() - Size(); }
2406
2407   // Return the maximum capacity of a semispace.
2408   int MaximumCapacity() {
2409     DCHECK(to_space_.MaximumTotalCapacity() ==
2410            from_space_.MaximumTotalCapacity());
2411     return to_space_.MaximumTotalCapacity();
2412   }
2413
2414   bool IsAtMaximumCapacity() { return TotalCapacity() == MaximumCapacity(); }
2415
2416   // Returns the initial capacity of a semispace.
2417   int InitialTotalCapacity() {
2418     DCHECK(to_space_.InitialTotalCapacity() ==
2419            from_space_.InitialTotalCapacity());
2420     return to_space_.InitialTotalCapacity();
2421   }
2422
2423   // Return the address of the allocation pointer in the active semispace.
2424   Address top() {
2425     DCHECK(to_space_.current_page()->ContainsLimit(allocation_info_.top()));
2426     return allocation_info_.top();
2427   }
2428
2429   void set_top(Address top) {
2430     DCHECK(to_space_.current_page()->ContainsLimit(top));
2431     allocation_info_.set_top(top);
2432   }
2433
2434   // Return the address of the allocation pointer limit in the active semispace.
2435   Address limit() {
2436     DCHECK(to_space_.current_page()->ContainsLimit(allocation_info_.limit()));
2437     return allocation_info_.limit();
2438   }
2439
2440   // Return the address of the first object in the active semispace.
2441   Address bottom() { return to_space_.space_start(); }
2442
2443   // Get the age mark of the inactive semispace.
2444   Address age_mark() { return from_space_.age_mark(); }
2445   // Set the age mark in the active semispace.
2446   void set_age_mark(Address mark) { to_space_.set_age_mark(mark); }
2447
2448   // The start address of the space and a bit mask. Anding an address in the
2449   // new space with the mask will result in the start address.
2450   Address start() { return start_; }
2451   uintptr_t mask() { return address_mask_; }
2452
2453   INLINE(uint32_t AddressToMarkbitIndex(Address addr)) {
2454     DCHECK(Contains(addr));
2455     DCHECK(IsAligned(OffsetFrom(addr), kPointerSize) ||
2456            IsAligned(OffsetFrom(addr) - 1, kPointerSize));
2457     return static_cast<uint32_t>(addr - start_) >> kPointerSizeLog2;
2458   }
2459
2460   INLINE(Address MarkbitIndexToAddress(uint32_t index)) {
2461     return reinterpret_cast<Address>(index << kPointerSizeLog2);
2462   }
2463
2464   // The allocation top and limit address.
2465   Address* allocation_top_address() { return allocation_info_.top_address(); }
2466
2467   // The allocation limit address.
2468   Address* allocation_limit_address() {
2469     return allocation_info_.limit_address();
2470   }
2471
2472   MUST_USE_RESULT INLINE(AllocationResult AllocateRaw(int size_in_bytes));
2473
2474   // Reset the allocation pointer to the beginning of the active semispace.
2475   void ResetAllocationInfo();
2476
2477   void UpdateInlineAllocationLimit(int size_in_bytes);
2478   void LowerInlineAllocationLimit(intptr_t step) {
2479     inline_allocation_limit_step_ = step;
2480     UpdateInlineAllocationLimit(0);
2481     top_on_previous_step_ = allocation_info_.top();
2482   }
2483
2484   // Get the extent of the inactive semispace (for use as a marking stack,
2485   // or to zap it). Notice: space-addresses are not necessarily on the
2486   // same page, so FromSpaceStart() might be above FromSpaceEnd().
2487   Address FromSpacePageLow() { return from_space_.page_low(); }
2488   Address FromSpacePageHigh() { return from_space_.page_high(); }
2489   Address FromSpaceStart() { return from_space_.space_start(); }
2490   Address FromSpaceEnd() { return from_space_.space_end(); }
2491
2492   // Get the extent of the active semispace's pages' memory.
2493   Address ToSpaceStart() { return to_space_.space_start(); }
2494   Address ToSpaceEnd() { return to_space_.space_end(); }
2495
2496   inline bool ToSpaceContains(Address address) {
2497     return to_space_.Contains(address);
2498   }
2499   inline bool FromSpaceContains(Address address) {
2500     return from_space_.Contains(address);
2501   }
2502
2503   // True if the object is a heap object in the address range of the
2504   // respective semispace (not necessarily below the allocation pointer of the
2505   // semispace).
2506   inline bool ToSpaceContains(Object* o) { return to_space_.Contains(o); }
2507   inline bool FromSpaceContains(Object* o) { return from_space_.Contains(o); }
2508
2509   // Try to switch the active semispace to a new, empty, page.
2510   // Returns false if this isn't possible or reasonable (i.e., there
2511   // are no pages, or the current page is already empty), or true
2512   // if successful.
2513   bool AddFreshPage();
2514
2515 #ifdef VERIFY_HEAP
2516   // Verify the active semispace.
2517   virtual void Verify();
2518 #endif
2519
2520 #ifdef DEBUG
2521   // Print the active semispace.
2522   virtual void Print() { to_space_.Print(); }
2523 #endif
2524
2525   // Iterates the active semispace to collect statistics.
2526   void CollectStatistics();
2527   // Reports previously collected statistics of the active semispace.
2528   void ReportStatistics();
2529   // Clears previously collected statistics.
2530   void ClearHistograms();
2531
2532   // Record the allocation or promotion of a heap object.  Note that we don't
2533   // record every single allocation, but only those that happen in the
2534   // to space during a scavenge GC.
2535   void RecordAllocation(HeapObject* obj);
2536   void RecordPromotion(HeapObject* obj);
2537
2538   // Return whether the operation succeded.
2539   bool CommitFromSpaceIfNeeded() {
2540     if (from_space_.is_committed()) return true;
2541     return from_space_.Commit();
2542   }
2543
2544   bool UncommitFromSpace() {
2545     if (!from_space_.is_committed()) return true;
2546     return from_space_.Uncommit();
2547   }
2548
2549   inline intptr_t inline_allocation_limit_step() {
2550     return inline_allocation_limit_step_;
2551   }
2552
2553   SemiSpace* active_space() { return &to_space_; }
2554
2555  private:
2556   // Update allocation info to match the current to-space page.
2557   void UpdateAllocationInfo();
2558
2559   Address chunk_base_;
2560   uintptr_t chunk_size_;
2561
2562   // The semispaces.
2563   SemiSpace to_space_;
2564   SemiSpace from_space_;
2565   base::VirtualMemory reservation_;
2566   int pages_used_;
2567
2568   // Start address and bit mask for containment testing.
2569   Address start_;
2570   uintptr_t address_mask_;
2571   uintptr_t object_mask_;
2572   uintptr_t object_expected_;
2573
2574   // Allocation pointer and limit for normal allocation and allocation during
2575   // mark-compact collection.
2576   AllocationInfo allocation_info_;
2577
2578   // When incremental marking is active we will set allocation_info_.limit
2579   // to be lower than actual limit and then will gradually increase it
2580   // in steps to guarantee that we do incremental marking steps even
2581   // when all allocation is performed from inlined generated code.
2582   intptr_t inline_allocation_limit_step_;
2583
2584   Address top_on_previous_step_;
2585
2586   HistogramInfo* allocated_histogram_;
2587   HistogramInfo* promoted_histogram_;
2588
2589   MUST_USE_RESULT AllocationResult SlowAllocateRaw(int size_in_bytes);
2590
2591   friend class SemiSpaceIterator;
2592
2593  public:
2594   TRACK_MEMORY("NewSpace")
2595 };
2596
2597
2598 // -----------------------------------------------------------------------------
2599 // Old object space (excluding map objects)
2600
2601 class OldSpace : public PagedSpace {
2602  public:
2603   // Creates an old space object with a given maximum capacity.
2604   // The constructor does not allocate pages from OS.
2605   OldSpace(Heap* heap, intptr_t max_capacity, AllocationSpace id,
2606            Executability executable)
2607       : PagedSpace(heap, max_capacity, id, executable) {}
2608
2609  public:
2610   TRACK_MEMORY("OldSpace")
2611 };
2612
2613
2614 // For contiguous spaces, top should be in the space (or at the end) and limit
2615 // should be the end of the space.
2616 #define DCHECK_SEMISPACE_ALLOCATION_INFO(info, space) \
2617   SLOW_DCHECK((space).page_low() <= (info).top() &&   \
2618               (info).top() <= (space).page_high() &&  \
2619               (info).limit() <= (space).page_high())
2620
2621
2622 // -----------------------------------------------------------------------------
2623 // Old space for all map objects
2624
2625 class MapSpace : public PagedSpace {
2626  public:
2627   // Creates a map space object with a maximum capacity.
2628   MapSpace(Heap* heap, intptr_t max_capacity, AllocationSpace id)
2629       : PagedSpace(heap, max_capacity, id, NOT_EXECUTABLE),
2630         max_map_space_pages_(kMaxMapPageIndex - 1) {}
2631
2632   // Given an index, returns the page address.
2633   // TODO(1600): this limit is artifical just to keep code compilable
2634   static const int kMaxMapPageIndex = 1 << 16;
2635
2636   virtual int RoundSizeDownToObjectAlignment(int size) {
2637     if (base::bits::IsPowerOfTwo32(Map::kSize)) {
2638       return RoundDown(size, Map::kSize);
2639     } else {
2640       return (size / Map::kSize) * Map::kSize;
2641     }
2642   }
2643
2644  protected:
2645   virtual void VerifyObject(HeapObject* obj);
2646
2647  private:
2648   static const int kMapsPerPage = Page::kMaxRegularHeapObjectSize / Map::kSize;
2649
2650   // Do map space compaction if there is a page gap.
2651   int CompactionThreshold() {
2652     return kMapsPerPage * (max_map_space_pages_ - 1);
2653   }
2654
2655   const int max_map_space_pages_;
2656
2657  public:
2658   TRACK_MEMORY("MapSpace")
2659 };
2660
2661
2662 // -----------------------------------------------------------------------------
2663 // Old space for simple property cell objects
2664
2665 class CellSpace : public PagedSpace {
2666  public:
2667   // Creates a property cell space object with a maximum capacity.
2668   CellSpace(Heap* heap, intptr_t max_capacity, AllocationSpace id)
2669       : PagedSpace(heap, max_capacity, id, NOT_EXECUTABLE) {}
2670
2671   virtual int RoundSizeDownToObjectAlignment(int size) {
2672     if (base::bits::IsPowerOfTwo32(Cell::kSize)) {
2673       return RoundDown(size, Cell::kSize);
2674     } else {
2675       return (size / Cell::kSize) * Cell::kSize;
2676     }
2677   }
2678
2679  protected:
2680   virtual void VerifyObject(HeapObject* obj);
2681
2682  public:
2683   TRACK_MEMORY("CellSpace")
2684 };
2685
2686
2687 // -----------------------------------------------------------------------------
2688 // Old space for all global object property cell objects
2689
2690 class PropertyCellSpace : public PagedSpace {
2691  public:
2692   // Creates a property cell space object with a maximum capacity.
2693   PropertyCellSpace(Heap* heap, intptr_t max_capacity, AllocationSpace id)
2694       : PagedSpace(heap, max_capacity, id, NOT_EXECUTABLE) {}
2695
2696   virtual int RoundSizeDownToObjectAlignment(int size) {
2697     if (base::bits::IsPowerOfTwo32(PropertyCell::kSize)) {
2698       return RoundDown(size, PropertyCell::kSize);
2699     } else {
2700       return (size / PropertyCell::kSize) * PropertyCell::kSize;
2701     }
2702   }
2703
2704  protected:
2705   virtual void VerifyObject(HeapObject* obj);
2706
2707  public:
2708   TRACK_MEMORY("PropertyCellSpace")
2709 };
2710
2711
2712 // -----------------------------------------------------------------------------
2713 // Large objects ( > Page::kMaxHeapObjectSize ) are allocated and managed by
2714 // the large object space. A large object is allocated from OS heap with
2715 // extra padding bytes (Page::kPageSize + Page::kObjectStartOffset).
2716 // A large object always starts at Page::kObjectStartOffset to a page.
2717 // Large objects do not move during garbage collections.
2718
2719 class LargeObjectSpace : public Space {
2720  public:
2721   LargeObjectSpace(Heap* heap, intptr_t max_capacity, AllocationSpace id);
2722   virtual ~LargeObjectSpace() {}
2723
2724   // Initializes internal data structures.
2725   bool SetUp();
2726
2727   // Releases internal resources, frees objects in this space.
2728   void TearDown();
2729
2730   static intptr_t ObjectSizeFor(intptr_t chunk_size) {
2731     if (chunk_size <= (Page::kPageSize + Page::kObjectStartOffset)) return 0;
2732     return chunk_size - Page::kPageSize - Page::kObjectStartOffset;
2733   }
2734
2735   // Shared implementation of AllocateRaw, AllocateRawCode and
2736   // AllocateRawFixedArray.
2737   MUST_USE_RESULT AllocationResult
2738       AllocateRaw(int object_size, Executability executable);
2739
2740   bool CanAllocateSize(int size) { return Size() + size <= max_capacity_; }
2741
2742   // Available bytes for objects in this space.
2743   inline intptr_t Available();
2744
2745   virtual intptr_t Size() { return size_; }
2746
2747   virtual intptr_t SizeOfObjects() { return objects_size_; }
2748
2749   intptr_t MaximumCommittedMemory() { return maximum_committed_; }
2750
2751   intptr_t CommittedMemory() { return Size(); }
2752
2753   // Approximate amount of physical memory committed for this space.
2754   size_t CommittedPhysicalMemory();
2755
2756   int PageCount() { return page_count_; }
2757
2758   // Finds an object for a given address, returns a Smi if it is not found.
2759   // The function iterates through all objects in this space, may be slow.
2760   Object* FindObject(Address a);
2761
2762   // Finds a large object page containing the given address, returns NULL
2763   // if such a page doesn't exist.
2764   LargePage* FindPage(Address a);
2765
2766   // Frees unmarked objects.
2767   void FreeUnmarkedObjects();
2768
2769   // Checks whether a heap object is in this space; O(1).
2770   bool Contains(HeapObject* obj);
2771
2772   // Checks whether the space is empty.
2773   bool IsEmpty() { return first_page_ == NULL; }
2774
2775   LargePage* first_page() { return first_page_; }
2776
2777 #ifdef VERIFY_HEAP
2778   virtual void Verify();
2779 #endif
2780
2781 #ifdef DEBUG
2782   virtual void Print();
2783   void ReportStatistics();
2784   void CollectCodeStatistics();
2785 #endif
2786   // Checks whether an address is in the object area in this space.  It
2787   // iterates all objects in the space. May be slow.
2788   bool SlowContains(Address addr) { return FindObject(addr)->IsHeapObject(); }
2789
2790  private:
2791   intptr_t max_capacity_;
2792   intptr_t maximum_committed_;
2793   // The head of the linked list of large object chunks.
2794   LargePage* first_page_;
2795   intptr_t size_;          // allocated bytes
2796   int page_count_;         // number of chunks
2797   intptr_t objects_size_;  // size of objects
2798   // Map MemoryChunk::kAlignment-aligned chunks to large pages covering them
2799   HashMap chunk_map_;
2800
2801   friend class LargeObjectIterator;
2802
2803  public:
2804   TRACK_MEMORY("LargeObjectSpace")
2805 };
2806
2807
2808 class LargeObjectIterator : public ObjectIterator {
2809  public:
2810   explicit LargeObjectIterator(LargeObjectSpace* space);
2811   LargeObjectIterator(LargeObjectSpace* space, HeapObjectCallback size_func);
2812
2813   HeapObject* Next();
2814
2815   // implementation of ObjectIterator.
2816   virtual HeapObject* next_object() { return Next(); }
2817
2818  private:
2819   LargePage* current_;
2820   HeapObjectCallback size_func_;
2821 };
2822
2823
2824 // Iterates over the chunks (pages and large object pages) that can contain
2825 // pointers to new space.
2826 class PointerChunkIterator BASE_EMBEDDED {
2827  public:
2828   inline explicit PointerChunkIterator(Heap* heap);
2829
2830   // Return NULL when the iterator is done.
2831   MemoryChunk* next() {
2832     switch (state_) {
2833       case kOldPointerState: {
2834         if (old_pointer_iterator_.has_next()) {
2835           return old_pointer_iterator_.next();
2836         }
2837         state_ = kMapState;
2838         // Fall through.
2839       }
2840       case kMapState: {
2841         if (map_iterator_.has_next()) {
2842           return map_iterator_.next();
2843         }
2844         state_ = kLargeObjectState;
2845         // Fall through.
2846       }
2847       case kLargeObjectState: {
2848         HeapObject* heap_object;
2849         do {
2850           heap_object = lo_iterator_.Next();
2851           if (heap_object == NULL) {
2852             state_ = kFinishedState;
2853             return NULL;
2854           }
2855           // Fixed arrays are the only pointer-containing objects in large
2856           // object space.
2857         } while (!heap_object->IsFixedArray());
2858         MemoryChunk* answer = MemoryChunk::FromAddress(heap_object->address());
2859         return answer;
2860       }
2861       case kFinishedState:
2862         return NULL;
2863       default:
2864         break;
2865     }
2866     UNREACHABLE();
2867     return NULL;
2868   }
2869
2870
2871  private:
2872   enum State { kOldPointerState, kMapState, kLargeObjectState, kFinishedState };
2873   State state_;
2874   PageIterator old_pointer_iterator_;
2875   PageIterator map_iterator_;
2876   LargeObjectIterator lo_iterator_;
2877 };
2878
2879
2880 #ifdef DEBUG
2881 struct CommentStatistic {
2882   const char* comment;
2883   int size;
2884   int count;
2885   void Clear() {
2886     comment = NULL;
2887     size = 0;
2888     count = 0;
2889   }
2890   // Must be small, since an iteration is used for lookup.
2891   static const int kMaxComments = 64;
2892 };
2893 #endif
2894 }
2895 }  // namespace v8::internal
2896
2897 #endif  // V8_HEAP_SPACES_H_