deps: upgrade v8 to 3.31.74.1
[platform/upstream/nodejs.git] / deps / v8 / src / heap / mark-compact.cc
1 // Copyright 2012 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 #include "src/v8.h"
6
7 #include "src/base/atomicops.h"
8 #include "src/base/bits.h"
9 #include "src/code-stubs.h"
10 #include "src/compilation-cache.h"
11 #include "src/cpu-profiler.h"
12 #include "src/deoptimizer.h"
13 #include "src/execution.h"
14 #include "src/gdb-jit.h"
15 #include "src/global-handles.h"
16 #include "src/heap/incremental-marking.h"
17 #include "src/heap/mark-compact.h"
18 #include "src/heap/objects-visiting.h"
19 #include "src/heap/objects-visiting-inl.h"
20 #include "src/heap/spaces-inl.h"
21 #include "src/heap-profiler.h"
22 #include "src/ic/ic.h"
23 #include "src/ic/stub-cache.h"
24
25 namespace v8 {
26 namespace internal {
27
28
29 const char* Marking::kWhiteBitPattern = "00";
30 const char* Marking::kBlackBitPattern = "10";
31 const char* Marking::kGreyBitPattern = "11";
32 const char* Marking::kImpossibleBitPattern = "01";
33
34
35 // -------------------------------------------------------------------------
36 // MarkCompactCollector
37
38 MarkCompactCollector::MarkCompactCollector(Heap* heap)
39     :  // NOLINT
40 #ifdef DEBUG
41       state_(IDLE),
42 #endif
43       reduce_memory_footprint_(false),
44       abort_incremental_marking_(false),
45       marking_parity_(ODD_MARKING_PARITY),
46       compacting_(false),
47       was_marked_incrementally_(false),
48       sweeping_in_progress_(false),
49       pending_sweeper_jobs_semaphore_(0),
50       evacuation_(false),
51       migration_slots_buffer_(NULL),
52       heap_(heap),
53       marking_deque_memory_(NULL),
54       marking_deque_memory_committed_(false),
55       code_flusher_(NULL),
56       have_code_to_deoptimize_(false) {
57 }
58
59 #ifdef VERIFY_HEAP
60 class VerifyMarkingVisitor : public ObjectVisitor {
61  public:
62   explicit VerifyMarkingVisitor(Heap* heap) : heap_(heap) {}
63
64   void VisitPointers(Object** start, Object** end) {
65     for (Object** current = start; current < end; current++) {
66       if ((*current)->IsHeapObject()) {
67         HeapObject* object = HeapObject::cast(*current);
68         CHECK(heap_->mark_compact_collector()->IsMarked(object));
69       }
70     }
71   }
72
73   void VisitEmbeddedPointer(RelocInfo* rinfo) {
74     DCHECK(rinfo->rmode() == RelocInfo::EMBEDDED_OBJECT);
75     if (!rinfo->host()->IsWeakObject(rinfo->target_object())) {
76       Object* p = rinfo->target_object();
77       VisitPointer(&p);
78     }
79   }
80
81   void VisitCell(RelocInfo* rinfo) {
82     Code* code = rinfo->host();
83     DCHECK(rinfo->rmode() == RelocInfo::CELL);
84     if (!code->IsWeakObject(rinfo->target_cell())) {
85       ObjectVisitor::VisitCell(rinfo);
86     }
87   }
88
89  private:
90   Heap* heap_;
91 };
92
93
94 static void VerifyMarking(Heap* heap, Address bottom, Address top) {
95   VerifyMarkingVisitor visitor(heap);
96   HeapObject* object;
97   Address next_object_must_be_here_or_later = bottom;
98
99   for (Address current = bottom; current < top; current += kPointerSize) {
100     object = HeapObject::FromAddress(current);
101     if (MarkCompactCollector::IsMarked(object)) {
102       CHECK(current >= next_object_must_be_here_or_later);
103       object->Iterate(&visitor);
104       next_object_must_be_here_or_later = current + object->Size();
105     }
106   }
107 }
108
109
110 static void VerifyMarking(NewSpace* space) {
111   Address end = space->top();
112   NewSpacePageIterator it(space->bottom(), end);
113   // The bottom position is at the start of its page. Allows us to use
114   // page->area_start() as start of range on all pages.
115   CHECK_EQ(space->bottom(),
116            NewSpacePage::FromAddress(space->bottom())->area_start());
117   while (it.has_next()) {
118     NewSpacePage* page = it.next();
119     Address limit = it.has_next() ? page->area_end() : end;
120     CHECK(limit == end || !page->Contains(end));
121     VerifyMarking(space->heap(), page->area_start(), limit);
122   }
123 }
124
125
126 static void VerifyMarking(PagedSpace* space) {
127   PageIterator it(space);
128
129   while (it.has_next()) {
130     Page* p = it.next();
131     VerifyMarking(space->heap(), p->area_start(), p->area_end());
132   }
133 }
134
135
136 static void VerifyMarking(Heap* heap) {
137   VerifyMarking(heap->old_pointer_space());
138   VerifyMarking(heap->old_data_space());
139   VerifyMarking(heap->code_space());
140   VerifyMarking(heap->cell_space());
141   VerifyMarking(heap->property_cell_space());
142   VerifyMarking(heap->map_space());
143   VerifyMarking(heap->new_space());
144
145   VerifyMarkingVisitor visitor(heap);
146
147   LargeObjectIterator it(heap->lo_space());
148   for (HeapObject* obj = it.Next(); obj != NULL; obj = it.Next()) {
149     if (MarkCompactCollector::IsMarked(obj)) {
150       obj->Iterate(&visitor);
151     }
152   }
153
154   heap->IterateStrongRoots(&visitor, VISIT_ONLY_STRONG);
155 }
156
157
158 class VerifyEvacuationVisitor : public ObjectVisitor {
159  public:
160   void VisitPointers(Object** start, Object** end) {
161     for (Object** current = start; current < end; current++) {
162       if ((*current)->IsHeapObject()) {
163         HeapObject* object = HeapObject::cast(*current);
164         CHECK(!MarkCompactCollector::IsOnEvacuationCandidate(object));
165       }
166     }
167   }
168 };
169
170
171 static void VerifyEvacuation(Page* page) {
172   VerifyEvacuationVisitor visitor;
173   HeapObjectIterator iterator(page, NULL);
174   for (HeapObject* heap_object = iterator.Next(); heap_object != NULL;
175        heap_object = iterator.Next()) {
176     // We skip free space objects.
177     if (!heap_object->IsFiller()) {
178       heap_object->Iterate(&visitor);
179     }
180   }
181 }
182
183
184 static void VerifyEvacuation(NewSpace* space) {
185   NewSpacePageIterator it(space->bottom(), space->top());
186   VerifyEvacuationVisitor visitor;
187
188   while (it.has_next()) {
189     NewSpacePage* page = it.next();
190     Address current = page->area_start();
191     Address limit = it.has_next() ? page->area_end() : space->top();
192     CHECK(limit == space->top() || !page->Contains(space->top()));
193     while (current < limit) {
194       HeapObject* object = HeapObject::FromAddress(current);
195       object->Iterate(&visitor);
196       current += object->Size();
197     }
198   }
199 }
200
201
202 static void VerifyEvacuation(Heap* heap, PagedSpace* space) {
203   if (FLAG_use_allocation_folding &&
204       (space == heap->old_pointer_space() || space == heap->old_data_space())) {
205     return;
206   }
207   PageIterator it(space);
208
209   while (it.has_next()) {
210     Page* p = it.next();
211     if (p->IsEvacuationCandidate()) continue;
212     VerifyEvacuation(p);
213   }
214 }
215
216
217 static void VerifyEvacuation(Heap* heap) {
218   VerifyEvacuation(heap, heap->old_pointer_space());
219   VerifyEvacuation(heap, heap->old_data_space());
220   VerifyEvacuation(heap, heap->code_space());
221   VerifyEvacuation(heap, heap->cell_space());
222   VerifyEvacuation(heap, heap->property_cell_space());
223   VerifyEvacuation(heap, heap->map_space());
224   VerifyEvacuation(heap->new_space());
225
226   VerifyEvacuationVisitor visitor;
227   heap->IterateStrongRoots(&visitor, VISIT_ALL);
228 }
229 #endif  // VERIFY_HEAP
230
231
232 void MarkCompactCollector::SetUp() {
233   free_list_old_data_space_.Reset(new FreeList(heap_->old_data_space()));
234   free_list_old_pointer_space_.Reset(new FreeList(heap_->old_pointer_space()));
235 }
236
237
238 void MarkCompactCollector::TearDown() {
239   AbortCompaction();
240   delete marking_deque_memory_;
241 }
242
243
244 void MarkCompactCollector::AddEvacuationCandidate(Page* p) {
245   p->MarkEvacuationCandidate();
246   evacuation_candidates_.Add(p);
247 }
248
249
250 static void TraceFragmentation(PagedSpace* space) {
251   int number_of_pages = space->CountTotalPages();
252   intptr_t reserved = (number_of_pages * space->AreaSize());
253   intptr_t free = reserved - space->SizeOfObjects();
254   PrintF("[%s]: %d pages, %d (%.1f%%) free\n",
255          AllocationSpaceName(space->identity()), number_of_pages,
256          static_cast<int>(free), static_cast<double>(free) * 100 / reserved);
257 }
258
259
260 bool MarkCompactCollector::StartCompaction(CompactionMode mode) {
261   if (!compacting_) {
262     DCHECK(evacuation_candidates_.length() == 0);
263
264 #ifdef ENABLE_GDB_JIT_INTERFACE
265     // If GDBJIT interface is active disable compaction.
266     if (FLAG_gdbjit) return false;
267 #endif
268
269     CollectEvacuationCandidates(heap()->old_pointer_space());
270     CollectEvacuationCandidates(heap()->old_data_space());
271
272     if (FLAG_compact_code_space && (mode == NON_INCREMENTAL_COMPACTION ||
273                                     FLAG_incremental_code_compaction)) {
274       CollectEvacuationCandidates(heap()->code_space());
275     } else if (FLAG_trace_fragmentation) {
276       TraceFragmentation(heap()->code_space());
277     }
278
279     if (FLAG_trace_fragmentation) {
280       TraceFragmentation(heap()->map_space());
281       TraceFragmentation(heap()->cell_space());
282       TraceFragmentation(heap()->property_cell_space());
283     }
284
285     heap()->old_pointer_space()->EvictEvacuationCandidatesFromFreeLists();
286     heap()->old_data_space()->EvictEvacuationCandidatesFromFreeLists();
287     heap()->code_space()->EvictEvacuationCandidatesFromFreeLists();
288
289     compacting_ = evacuation_candidates_.length() > 0;
290   }
291
292   return compacting_;
293 }
294
295
296 void MarkCompactCollector::CollectGarbage() {
297   // Make sure that Prepare() has been called. The individual steps below will
298   // update the state as they proceed.
299   DCHECK(state_ == PREPARE_GC);
300
301   MarkLiveObjects();
302   DCHECK(heap_->incremental_marking()->IsStopped());
303
304   if (FLAG_collect_maps) ClearNonLiveReferences();
305
306   ProcessAndClearWeakCells();
307
308   ClearWeakCollections();
309
310   heap_->set_encountered_weak_cells(Smi::FromInt(0));
311
312   isolate()->global_handles()->CollectPhantomCallbackData();
313
314 #ifdef VERIFY_HEAP
315   if (FLAG_verify_heap) {
316     VerifyMarking(heap_);
317   }
318 #endif
319
320   SweepSpaces();
321
322 #ifdef VERIFY_HEAP
323   if (heap()->weak_embedded_objects_verification_enabled()) {
324     VerifyWeakEmbeddedObjectsInCode();
325   }
326   if (FLAG_collect_maps && FLAG_omit_map_checks_for_leaf_maps) {
327     VerifyOmittedMapChecks();
328   }
329 #endif
330
331   Finish();
332
333   if (marking_parity_ == EVEN_MARKING_PARITY) {
334     marking_parity_ = ODD_MARKING_PARITY;
335   } else {
336     DCHECK(marking_parity_ == ODD_MARKING_PARITY);
337     marking_parity_ = EVEN_MARKING_PARITY;
338   }
339 }
340
341
342 #ifdef VERIFY_HEAP
343 void MarkCompactCollector::VerifyMarkbitsAreClean(PagedSpace* space) {
344   PageIterator it(space);
345
346   while (it.has_next()) {
347     Page* p = it.next();
348     CHECK(p->markbits()->IsClean());
349     CHECK_EQ(0, p->LiveBytes());
350   }
351 }
352
353
354 void MarkCompactCollector::VerifyMarkbitsAreClean(NewSpace* space) {
355   NewSpacePageIterator it(space->bottom(), space->top());
356
357   while (it.has_next()) {
358     NewSpacePage* p = it.next();
359     CHECK(p->markbits()->IsClean());
360     CHECK_EQ(0, p->LiveBytes());
361   }
362 }
363
364
365 void MarkCompactCollector::VerifyMarkbitsAreClean() {
366   VerifyMarkbitsAreClean(heap_->old_pointer_space());
367   VerifyMarkbitsAreClean(heap_->old_data_space());
368   VerifyMarkbitsAreClean(heap_->code_space());
369   VerifyMarkbitsAreClean(heap_->cell_space());
370   VerifyMarkbitsAreClean(heap_->property_cell_space());
371   VerifyMarkbitsAreClean(heap_->map_space());
372   VerifyMarkbitsAreClean(heap_->new_space());
373
374   LargeObjectIterator it(heap_->lo_space());
375   for (HeapObject* obj = it.Next(); obj != NULL; obj = it.Next()) {
376     MarkBit mark_bit = Marking::MarkBitFrom(obj);
377     CHECK(Marking::IsWhite(mark_bit));
378     CHECK_EQ(0, Page::FromAddress(obj->address())->LiveBytes());
379   }
380 }
381
382
383 void MarkCompactCollector::VerifyWeakEmbeddedObjectsInCode() {
384   HeapObjectIterator code_iterator(heap()->code_space());
385   for (HeapObject* obj = code_iterator.Next(); obj != NULL;
386        obj = code_iterator.Next()) {
387     Code* code = Code::cast(obj);
388     if (!code->is_optimized_code()) continue;
389     if (WillBeDeoptimized(code)) continue;
390     code->VerifyEmbeddedObjectsDependency();
391   }
392 }
393
394
395 void MarkCompactCollector::VerifyOmittedMapChecks() {
396   HeapObjectIterator iterator(heap()->map_space());
397   for (HeapObject* obj = iterator.Next(); obj != NULL; obj = iterator.Next()) {
398     Map* map = Map::cast(obj);
399     map->VerifyOmittedMapChecks();
400   }
401 }
402 #endif  // VERIFY_HEAP
403
404
405 static void ClearMarkbitsInPagedSpace(PagedSpace* space) {
406   PageIterator it(space);
407
408   while (it.has_next()) {
409     Bitmap::Clear(it.next());
410   }
411 }
412
413
414 static void ClearMarkbitsInNewSpace(NewSpace* space) {
415   NewSpacePageIterator it(space->ToSpaceStart(), space->ToSpaceEnd());
416
417   while (it.has_next()) {
418     Bitmap::Clear(it.next());
419   }
420 }
421
422
423 void MarkCompactCollector::ClearMarkbits() {
424   ClearMarkbitsInPagedSpace(heap_->code_space());
425   ClearMarkbitsInPagedSpace(heap_->map_space());
426   ClearMarkbitsInPagedSpace(heap_->old_pointer_space());
427   ClearMarkbitsInPagedSpace(heap_->old_data_space());
428   ClearMarkbitsInPagedSpace(heap_->cell_space());
429   ClearMarkbitsInPagedSpace(heap_->property_cell_space());
430   ClearMarkbitsInNewSpace(heap_->new_space());
431
432   LargeObjectIterator it(heap_->lo_space());
433   for (HeapObject* obj = it.Next(); obj != NULL; obj = it.Next()) {
434     MarkBit mark_bit = Marking::MarkBitFrom(obj);
435     mark_bit.Clear();
436     mark_bit.Next().Clear();
437     Page::FromAddress(obj->address())->ResetProgressBar();
438     Page::FromAddress(obj->address())->ResetLiveBytes();
439   }
440 }
441
442
443 class MarkCompactCollector::SweeperTask : public v8::Task {
444  public:
445   SweeperTask(Heap* heap, PagedSpace* space) : heap_(heap), space_(space) {}
446
447   virtual ~SweeperTask() {}
448
449  private:
450   // v8::Task overrides.
451   void Run() OVERRIDE {
452     heap_->mark_compact_collector()->SweepInParallel(space_, 0);
453     heap_->mark_compact_collector()->pending_sweeper_jobs_semaphore_.Signal();
454   }
455
456   Heap* heap_;
457   PagedSpace* space_;
458
459   DISALLOW_COPY_AND_ASSIGN(SweeperTask);
460 };
461
462
463 void MarkCompactCollector::StartSweeperThreads() {
464   DCHECK(free_list_old_pointer_space_.get()->IsEmpty());
465   DCHECK(free_list_old_data_space_.get()->IsEmpty());
466   V8::GetCurrentPlatform()->CallOnBackgroundThread(
467       new SweeperTask(heap(), heap()->old_data_space()),
468       v8::Platform::kShortRunningTask);
469   V8::GetCurrentPlatform()->CallOnBackgroundThread(
470       new SweeperTask(heap(), heap()->old_pointer_space()),
471       v8::Platform::kShortRunningTask);
472 }
473
474
475 void MarkCompactCollector::EnsureSweepingCompleted() {
476   DCHECK(sweeping_in_progress_ == true);
477
478   // If sweeping is not completed or not running at all, we try to complete it
479   // here.
480   if (!FLAG_concurrent_sweeping || !IsSweepingCompleted()) {
481     SweepInParallel(heap()->paged_space(OLD_DATA_SPACE), 0);
482     SweepInParallel(heap()->paged_space(OLD_POINTER_SPACE), 0);
483   }
484   // Wait twice for both jobs.
485   if (FLAG_concurrent_sweeping) {
486     pending_sweeper_jobs_semaphore_.Wait();
487     pending_sweeper_jobs_semaphore_.Wait();
488   }
489   ParallelSweepSpacesComplete();
490   sweeping_in_progress_ = false;
491   RefillFreeList(heap()->paged_space(OLD_DATA_SPACE));
492   RefillFreeList(heap()->paged_space(OLD_POINTER_SPACE));
493   heap()->paged_space(OLD_DATA_SPACE)->ResetUnsweptFreeBytes();
494   heap()->paged_space(OLD_POINTER_SPACE)->ResetUnsweptFreeBytes();
495
496 #ifdef VERIFY_HEAP
497   if (FLAG_verify_heap && !evacuation()) {
498     VerifyEvacuation(heap_);
499   }
500 #endif
501 }
502
503
504 bool MarkCompactCollector::IsSweepingCompleted() {
505   if (!pending_sweeper_jobs_semaphore_.WaitFor(
506           base::TimeDelta::FromSeconds(0))) {
507     return false;
508   }
509   pending_sweeper_jobs_semaphore_.Signal();
510   return true;
511 }
512
513
514 void MarkCompactCollector::RefillFreeList(PagedSpace* space) {
515   FreeList* free_list;
516
517   if (space == heap()->old_pointer_space()) {
518     free_list = free_list_old_pointer_space_.get();
519   } else if (space == heap()->old_data_space()) {
520     free_list = free_list_old_data_space_.get();
521   } else {
522     // Any PagedSpace might invoke RefillFreeLists, so we need to make sure
523     // to only refill them for old data and pointer spaces.
524     return;
525   }
526
527   intptr_t freed_bytes = space->free_list()->Concatenate(free_list);
528   space->AddToAccountingStats(freed_bytes);
529   space->DecrementUnsweptFreeBytes(freed_bytes);
530 }
531
532
533 void Marking::TransferMark(Address old_start, Address new_start) {
534   // This is only used when resizing an object.
535   DCHECK(MemoryChunk::FromAddress(old_start) ==
536          MemoryChunk::FromAddress(new_start));
537
538   if (!heap_->incremental_marking()->IsMarking()) return;
539
540   // If the mark doesn't move, we don't check the color of the object.
541   // It doesn't matter whether the object is black, since it hasn't changed
542   // size, so the adjustment to the live data count will be zero anyway.
543   if (old_start == new_start) return;
544
545   MarkBit new_mark_bit = MarkBitFrom(new_start);
546   MarkBit old_mark_bit = MarkBitFrom(old_start);
547
548 #ifdef DEBUG
549   ObjectColor old_color = Color(old_mark_bit);
550 #endif
551
552   if (Marking::IsBlack(old_mark_bit)) {
553     old_mark_bit.Clear();
554     DCHECK(IsWhite(old_mark_bit));
555     Marking::MarkBlack(new_mark_bit);
556     return;
557   } else if (Marking::IsGrey(old_mark_bit)) {
558     old_mark_bit.Clear();
559     old_mark_bit.Next().Clear();
560     DCHECK(IsWhite(old_mark_bit));
561     heap_->incremental_marking()->WhiteToGreyAndPush(
562         HeapObject::FromAddress(new_start), new_mark_bit);
563     heap_->incremental_marking()->RestartIfNotMarking();
564   }
565
566 #ifdef DEBUG
567   ObjectColor new_color = Color(new_mark_bit);
568   DCHECK(new_color == old_color);
569 #endif
570 }
571
572
573 const char* AllocationSpaceName(AllocationSpace space) {
574   switch (space) {
575     case NEW_SPACE:
576       return "NEW_SPACE";
577     case OLD_POINTER_SPACE:
578       return "OLD_POINTER_SPACE";
579     case OLD_DATA_SPACE:
580       return "OLD_DATA_SPACE";
581     case CODE_SPACE:
582       return "CODE_SPACE";
583     case MAP_SPACE:
584       return "MAP_SPACE";
585     case CELL_SPACE:
586       return "CELL_SPACE";
587     case PROPERTY_CELL_SPACE:
588       return "PROPERTY_CELL_SPACE";
589     case LO_SPACE:
590       return "LO_SPACE";
591     default:
592       UNREACHABLE();
593   }
594
595   return NULL;
596 }
597
598
599 // Returns zero for pages that have so little fragmentation that it is not
600 // worth defragmenting them.  Otherwise a positive integer that gives an
601 // estimate of fragmentation on an arbitrary scale.
602 static int FreeListFragmentation(PagedSpace* space, Page* p) {
603   // If page was not swept then there are no free list items on it.
604   if (!p->WasSwept()) {
605     if (FLAG_trace_fragmentation) {
606       PrintF("%p [%s]: %d bytes live (unswept)\n", reinterpret_cast<void*>(p),
607              AllocationSpaceName(space->identity()), p->LiveBytes());
608     }
609     return 0;
610   }
611
612   PagedSpace::SizeStats sizes;
613   space->ObtainFreeListStatistics(p, &sizes);
614
615   intptr_t ratio;
616   intptr_t ratio_threshold;
617   intptr_t area_size = space->AreaSize();
618   if (space->identity() == CODE_SPACE) {
619     ratio = (sizes.medium_size_ * 10 + sizes.large_size_ * 2) * 100 / area_size;
620     ratio_threshold = 10;
621   } else {
622     ratio = (sizes.small_size_ * 5 + sizes.medium_size_) * 100 / area_size;
623     ratio_threshold = 15;
624   }
625
626   if (FLAG_trace_fragmentation) {
627     PrintF("%p [%s]: %d (%.2f%%) %d (%.2f%%) %d (%.2f%%) %d (%.2f%%) %s\n",
628            reinterpret_cast<void*>(p), AllocationSpaceName(space->identity()),
629            static_cast<int>(sizes.small_size_),
630            static_cast<double>(sizes.small_size_ * 100) / area_size,
631            static_cast<int>(sizes.medium_size_),
632            static_cast<double>(sizes.medium_size_ * 100) / area_size,
633            static_cast<int>(sizes.large_size_),
634            static_cast<double>(sizes.large_size_ * 100) / area_size,
635            static_cast<int>(sizes.huge_size_),
636            static_cast<double>(sizes.huge_size_ * 100) / area_size,
637            (ratio > ratio_threshold) ? "[fragmented]" : "");
638   }
639
640   if (FLAG_always_compact && sizes.Total() != area_size) {
641     return 1;
642   }
643
644   if (ratio <= ratio_threshold) return 0;  // Not fragmented.
645
646   return static_cast<int>(ratio - ratio_threshold);
647 }
648
649
650 void MarkCompactCollector::CollectEvacuationCandidates(PagedSpace* space) {
651   DCHECK(space->identity() == OLD_POINTER_SPACE ||
652          space->identity() == OLD_DATA_SPACE ||
653          space->identity() == CODE_SPACE);
654
655   static const int kMaxMaxEvacuationCandidates = 1000;
656   int number_of_pages = space->CountTotalPages();
657   int max_evacuation_candidates =
658       static_cast<int>(std::sqrt(number_of_pages / 2.0) + 1);
659
660   if (FLAG_stress_compaction || FLAG_always_compact) {
661     max_evacuation_candidates = kMaxMaxEvacuationCandidates;
662   }
663
664   class Candidate {
665    public:
666     Candidate() : fragmentation_(0), page_(NULL) {}
667     Candidate(int f, Page* p) : fragmentation_(f), page_(p) {}
668
669     int fragmentation() { return fragmentation_; }
670     Page* page() { return page_; }
671
672    private:
673     int fragmentation_;
674     Page* page_;
675   };
676
677   enum CompactionMode { COMPACT_FREE_LISTS, REDUCE_MEMORY_FOOTPRINT };
678
679   CompactionMode mode = COMPACT_FREE_LISTS;
680
681   intptr_t reserved = number_of_pages * space->AreaSize();
682   intptr_t over_reserved = reserved - space->SizeOfObjects();
683   static const intptr_t kFreenessThreshold = 50;
684
685   if (reduce_memory_footprint_ && over_reserved >= space->AreaSize()) {
686     // If reduction of memory footprint was requested, we are aggressive
687     // about choosing pages to free.  We expect that half-empty pages
688     // are easier to compact so slightly bump the limit.
689     mode = REDUCE_MEMORY_FOOTPRINT;
690     max_evacuation_candidates += 2;
691   }
692
693
694   if (over_reserved > reserved / 3 && over_reserved >= 2 * space->AreaSize()) {
695     // If over-usage is very high (more than a third of the space), we
696     // try to free all mostly empty pages.  We expect that almost empty
697     // pages are even easier to compact so bump the limit even more.
698     mode = REDUCE_MEMORY_FOOTPRINT;
699     max_evacuation_candidates *= 2;
700   }
701
702   if (FLAG_trace_fragmentation && mode == REDUCE_MEMORY_FOOTPRINT) {
703     PrintF(
704         "Estimated over reserved memory: %.1f / %.1f MB (threshold %d), "
705         "evacuation candidate limit: %d\n",
706         static_cast<double>(over_reserved) / MB,
707         static_cast<double>(reserved) / MB,
708         static_cast<int>(kFreenessThreshold), max_evacuation_candidates);
709   }
710
711   intptr_t estimated_release = 0;
712
713   Candidate candidates[kMaxMaxEvacuationCandidates];
714
715   max_evacuation_candidates =
716       Min(kMaxMaxEvacuationCandidates, max_evacuation_candidates);
717
718   int count = 0;
719   int fragmentation = 0;
720   Candidate* least = NULL;
721
722   PageIterator it(space);
723   if (it.has_next()) it.next();  // Never compact the first page.
724
725   while (it.has_next()) {
726     Page* p = it.next();
727     p->ClearEvacuationCandidate();
728
729     if (FLAG_stress_compaction) {
730       unsigned int counter = space->heap()->ms_count();
731       uintptr_t page_number = reinterpret_cast<uintptr_t>(p) >> kPageSizeBits;
732       if ((counter & 1) == (page_number & 1)) fragmentation = 1;
733     } else if (mode == REDUCE_MEMORY_FOOTPRINT) {
734       // Don't try to release too many pages.
735       if (estimated_release >= over_reserved) {
736         continue;
737       }
738
739       intptr_t free_bytes = 0;
740
741       if (!p->WasSwept()) {
742         free_bytes = (p->area_size() - p->LiveBytes());
743       } else {
744         PagedSpace::SizeStats sizes;
745         space->ObtainFreeListStatistics(p, &sizes);
746         free_bytes = sizes.Total();
747       }
748
749       int free_pct = static_cast<int>(free_bytes * 100) / p->area_size();
750
751       if (free_pct >= kFreenessThreshold) {
752         estimated_release += free_bytes;
753         fragmentation = free_pct;
754       } else {
755         fragmentation = 0;
756       }
757
758       if (FLAG_trace_fragmentation) {
759         PrintF("%p [%s]: %d (%.2f%%) free %s\n", reinterpret_cast<void*>(p),
760                AllocationSpaceName(space->identity()),
761                static_cast<int>(free_bytes),
762                static_cast<double>(free_bytes * 100) / p->area_size(),
763                (fragmentation > 0) ? "[fragmented]" : "");
764       }
765     } else {
766       fragmentation = FreeListFragmentation(space, p);
767     }
768
769     if (fragmentation != 0) {
770       if (count < max_evacuation_candidates) {
771         candidates[count++] = Candidate(fragmentation, p);
772       } else {
773         if (least == NULL) {
774           for (int i = 0; i < max_evacuation_candidates; i++) {
775             if (least == NULL ||
776                 candidates[i].fragmentation() < least->fragmentation()) {
777               least = candidates + i;
778             }
779           }
780         }
781         if (least->fragmentation() < fragmentation) {
782           *least = Candidate(fragmentation, p);
783           least = NULL;
784         }
785       }
786     }
787   }
788
789   for (int i = 0; i < count; i++) {
790     AddEvacuationCandidate(candidates[i].page());
791   }
792
793   if (count > 0 && FLAG_trace_fragmentation) {
794     PrintF("Collected %d evacuation candidates for space %s\n", count,
795            AllocationSpaceName(space->identity()));
796   }
797 }
798
799
800 void MarkCompactCollector::AbortCompaction() {
801   if (compacting_) {
802     int npages = evacuation_candidates_.length();
803     for (int i = 0; i < npages; i++) {
804       Page* p = evacuation_candidates_[i];
805       slots_buffer_allocator_.DeallocateChain(p->slots_buffer_address());
806       p->ClearEvacuationCandidate();
807       p->ClearFlag(MemoryChunk::RESCAN_ON_EVACUATION);
808     }
809     compacting_ = false;
810     evacuation_candidates_.Rewind(0);
811     invalidated_code_.Rewind(0);
812   }
813   DCHECK_EQ(0, evacuation_candidates_.length());
814 }
815
816
817 void MarkCompactCollector::Prepare() {
818   was_marked_incrementally_ = heap()->incremental_marking()->IsMarking();
819
820 #ifdef DEBUG
821   DCHECK(state_ == IDLE);
822   state_ = PREPARE_GC;
823 #endif
824
825   DCHECK(!FLAG_never_compact || !FLAG_always_compact);
826
827   if (sweeping_in_progress()) {
828     // Instead of waiting we could also abort the sweeper threads here.
829     EnsureSweepingCompleted();
830   }
831
832   // Clear marking bits if incremental marking is aborted.
833   if (was_marked_incrementally_ && abort_incremental_marking_) {
834     heap()->incremental_marking()->Abort();
835     ClearMarkbits();
836     AbortWeakCollections();
837     AbortWeakCells();
838     AbortCompaction();
839     was_marked_incrementally_ = false;
840   }
841
842   // Don't start compaction if we are in the middle of incremental
843   // marking cycle. We did not collect any slots.
844   if (!FLAG_never_compact && !was_marked_incrementally_) {
845     StartCompaction(NON_INCREMENTAL_COMPACTION);
846   }
847
848   PagedSpaces spaces(heap());
849   for (PagedSpace* space = spaces.next(); space != NULL;
850        space = spaces.next()) {
851     space->PrepareForMarkCompact();
852   }
853
854 #ifdef VERIFY_HEAP
855   if (!was_marked_incrementally_ && FLAG_verify_heap) {
856     VerifyMarkbitsAreClean();
857   }
858 #endif
859 }
860
861
862 void MarkCompactCollector::Finish() {
863 #ifdef DEBUG
864   DCHECK(state_ == SWEEP_SPACES || state_ == RELOCATE_OBJECTS);
865   state_ = IDLE;
866 #endif
867   // The stub cache is not traversed during GC; clear the cache to
868   // force lazy re-initialization of it. This must be done after the
869   // GC, because it relies on the new address of certain old space
870   // objects (empty string, illegal builtin).
871   isolate()->stub_cache()->Clear();
872
873   if (have_code_to_deoptimize_) {
874     // Some code objects were marked for deoptimization during the GC.
875     Deoptimizer::DeoptimizeMarkedCode(isolate());
876     have_code_to_deoptimize_ = false;
877   }
878
879   heap_->incremental_marking()->ClearIdleMarkingDelayCounter();
880 }
881
882
883 // -------------------------------------------------------------------------
884 // Phase 1: tracing and marking live objects.
885 //   before: all objects are in normal state.
886 //   after: a live object's map pointer is marked as '00'.
887
888 // Marking all live objects in the heap as part of mark-sweep or mark-compact
889 // collection.  Before marking, all objects are in their normal state.  After
890 // marking, live objects' map pointers are marked indicating that the object
891 // has been found reachable.
892 //
893 // The marking algorithm is a (mostly) depth-first (because of possible stack
894 // overflow) traversal of the graph of objects reachable from the roots.  It
895 // uses an explicit stack of pointers rather than recursion.  The young
896 // generation's inactive ('from') space is used as a marking stack.  The
897 // objects in the marking stack are the ones that have been reached and marked
898 // but their children have not yet been visited.
899 //
900 // The marking stack can overflow during traversal.  In that case, we set an
901 // overflow flag.  When the overflow flag is set, we continue marking objects
902 // reachable from the objects on the marking stack, but no longer push them on
903 // the marking stack.  Instead, we mark them as both marked and overflowed.
904 // When the stack is in the overflowed state, objects marked as overflowed
905 // have been reached and marked but their children have not been visited yet.
906 // After emptying the marking stack, we clear the overflow flag and traverse
907 // the heap looking for objects marked as overflowed, push them on the stack,
908 // and continue with marking.  This process repeats until all reachable
909 // objects have been marked.
910
911 void CodeFlusher::ProcessJSFunctionCandidates() {
912   Code* lazy_compile = isolate_->builtins()->builtin(Builtins::kCompileLazy);
913   Object* undefined = isolate_->heap()->undefined_value();
914
915   JSFunction* candidate = jsfunction_candidates_head_;
916   JSFunction* next_candidate;
917   while (candidate != NULL) {
918     next_candidate = GetNextCandidate(candidate);
919     ClearNextCandidate(candidate, undefined);
920
921     SharedFunctionInfo* shared = candidate->shared();
922
923     Code* code = shared->code();
924     MarkBit code_mark = Marking::MarkBitFrom(code);
925     if (!code_mark.Get()) {
926       if (FLAG_trace_code_flushing && shared->is_compiled()) {
927         PrintF("[code-flushing clears: ");
928         shared->ShortPrint();
929         PrintF(" - age: %d]\n", code->GetAge());
930       }
931       shared->set_code(lazy_compile);
932       candidate->set_code(lazy_compile);
933     } else {
934       candidate->set_code(code);
935     }
936
937     // We are in the middle of a GC cycle so the write barrier in the code
938     // setter did not record the slot update and we have to do that manually.
939     Address slot = candidate->address() + JSFunction::kCodeEntryOffset;
940     Code* target = Code::cast(Code::GetObjectFromEntryAddress(slot));
941     isolate_->heap()->mark_compact_collector()->RecordCodeEntrySlot(slot,
942                                                                     target);
943
944     Object** shared_code_slot =
945         HeapObject::RawField(shared, SharedFunctionInfo::kCodeOffset);
946     isolate_->heap()->mark_compact_collector()->RecordSlot(
947         shared_code_slot, shared_code_slot, *shared_code_slot);
948
949     candidate = next_candidate;
950   }
951
952   jsfunction_candidates_head_ = NULL;
953 }
954
955
956 void CodeFlusher::ProcessSharedFunctionInfoCandidates() {
957   Code* lazy_compile = isolate_->builtins()->builtin(Builtins::kCompileLazy);
958
959   SharedFunctionInfo* candidate = shared_function_info_candidates_head_;
960   SharedFunctionInfo* next_candidate;
961   while (candidate != NULL) {
962     next_candidate = GetNextCandidate(candidate);
963     ClearNextCandidate(candidate);
964
965     Code* code = candidate->code();
966     MarkBit code_mark = Marking::MarkBitFrom(code);
967     if (!code_mark.Get()) {
968       if (FLAG_trace_code_flushing && candidate->is_compiled()) {
969         PrintF("[code-flushing clears: ");
970         candidate->ShortPrint();
971         PrintF(" - age: %d]\n", code->GetAge());
972       }
973       candidate->set_code(lazy_compile);
974     }
975
976     Object** code_slot =
977         HeapObject::RawField(candidate, SharedFunctionInfo::kCodeOffset);
978     isolate_->heap()->mark_compact_collector()->RecordSlot(code_slot, code_slot,
979                                                            *code_slot);
980
981     candidate = next_candidate;
982   }
983
984   shared_function_info_candidates_head_ = NULL;
985 }
986
987
988 void CodeFlusher::ProcessOptimizedCodeMaps() {
989   STATIC_ASSERT(SharedFunctionInfo::kEntryLength == 4);
990
991   SharedFunctionInfo* holder = optimized_code_map_holder_head_;
992   SharedFunctionInfo* next_holder;
993
994   while (holder != NULL) {
995     next_holder = GetNextCodeMap(holder);
996     ClearNextCodeMap(holder);
997
998     FixedArray* code_map = FixedArray::cast(holder->optimized_code_map());
999     int new_length = SharedFunctionInfo::kEntriesStart;
1000     int old_length = code_map->length();
1001     for (int i = SharedFunctionInfo::kEntriesStart; i < old_length;
1002          i += SharedFunctionInfo::kEntryLength) {
1003       Code* code =
1004           Code::cast(code_map->get(i + SharedFunctionInfo::kCachedCodeOffset));
1005       if (!Marking::MarkBitFrom(code).Get()) continue;
1006
1007       // Move every slot in the entry.
1008       for (int j = 0; j < SharedFunctionInfo::kEntryLength; j++) {
1009         int dst_index = new_length++;
1010         Object** slot = code_map->RawFieldOfElementAt(dst_index);
1011         Object* object = code_map->get(i + j);
1012         code_map->set(dst_index, object);
1013         if (j == SharedFunctionInfo::kOsrAstIdOffset) {
1014           DCHECK(object->IsSmi());
1015         } else {
1016           DCHECK(
1017               Marking::IsBlack(Marking::MarkBitFrom(HeapObject::cast(*slot))));
1018           isolate_->heap()->mark_compact_collector()->RecordSlot(slot, slot,
1019                                                                  *slot);
1020         }
1021       }
1022     }
1023
1024     // Trim the optimized code map if entries have been removed.
1025     if (new_length < old_length) {
1026       holder->TrimOptimizedCodeMap(old_length - new_length);
1027     }
1028
1029     holder = next_holder;
1030   }
1031
1032   optimized_code_map_holder_head_ = NULL;
1033 }
1034
1035
1036 void CodeFlusher::EvictCandidate(SharedFunctionInfo* shared_info) {
1037   // Make sure previous flushing decisions are revisited.
1038   isolate_->heap()->incremental_marking()->RecordWrites(shared_info);
1039
1040   if (FLAG_trace_code_flushing) {
1041     PrintF("[code-flushing abandons function-info: ");
1042     shared_info->ShortPrint();
1043     PrintF("]\n");
1044   }
1045
1046   SharedFunctionInfo* candidate = shared_function_info_candidates_head_;
1047   SharedFunctionInfo* next_candidate;
1048   if (candidate == shared_info) {
1049     next_candidate = GetNextCandidate(shared_info);
1050     shared_function_info_candidates_head_ = next_candidate;
1051     ClearNextCandidate(shared_info);
1052   } else {
1053     while (candidate != NULL) {
1054       next_candidate = GetNextCandidate(candidate);
1055
1056       if (next_candidate == shared_info) {
1057         next_candidate = GetNextCandidate(shared_info);
1058         SetNextCandidate(candidate, next_candidate);
1059         ClearNextCandidate(shared_info);
1060         break;
1061       }
1062
1063       candidate = next_candidate;
1064     }
1065   }
1066 }
1067
1068
1069 void CodeFlusher::EvictCandidate(JSFunction* function) {
1070   DCHECK(!function->next_function_link()->IsUndefined());
1071   Object* undefined = isolate_->heap()->undefined_value();
1072
1073   // Make sure previous flushing decisions are revisited.
1074   isolate_->heap()->incremental_marking()->RecordWrites(function);
1075   isolate_->heap()->incremental_marking()->RecordWrites(function->shared());
1076
1077   if (FLAG_trace_code_flushing) {
1078     PrintF("[code-flushing abandons closure: ");
1079     function->shared()->ShortPrint();
1080     PrintF("]\n");
1081   }
1082
1083   JSFunction* candidate = jsfunction_candidates_head_;
1084   JSFunction* next_candidate;
1085   if (candidate == function) {
1086     next_candidate = GetNextCandidate(function);
1087     jsfunction_candidates_head_ = next_candidate;
1088     ClearNextCandidate(function, undefined);
1089   } else {
1090     while (candidate != NULL) {
1091       next_candidate = GetNextCandidate(candidate);
1092
1093       if (next_candidate == function) {
1094         next_candidate = GetNextCandidate(function);
1095         SetNextCandidate(candidate, next_candidate);
1096         ClearNextCandidate(function, undefined);
1097         break;
1098       }
1099
1100       candidate = next_candidate;
1101     }
1102   }
1103 }
1104
1105
1106 void CodeFlusher::EvictOptimizedCodeMap(SharedFunctionInfo* code_map_holder) {
1107   DCHECK(!FixedArray::cast(code_map_holder->optimized_code_map())
1108               ->get(SharedFunctionInfo::kNextMapIndex)
1109               ->IsUndefined());
1110
1111   // Make sure previous flushing decisions are revisited.
1112   isolate_->heap()->incremental_marking()->RecordWrites(code_map_holder);
1113
1114   if (FLAG_trace_code_flushing) {
1115     PrintF("[code-flushing abandons code-map: ");
1116     code_map_holder->ShortPrint();
1117     PrintF("]\n");
1118   }
1119
1120   SharedFunctionInfo* holder = optimized_code_map_holder_head_;
1121   SharedFunctionInfo* next_holder;
1122   if (holder == code_map_holder) {
1123     next_holder = GetNextCodeMap(code_map_holder);
1124     optimized_code_map_holder_head_ = next_holder;
1125     ClearNextCodeMap(code_map_holder);
1126   } else {
1127     while (holder != NULL) {
1128       next_holder = GetNextCodeMap(holder);
1129
1130       if (next_holder == code_map_holder) {
1131         next_holder = GetNextCodeMap(code_map_holder);
1132         SetNextCodeMap(holder, next_holder);
1133         ClearNextCodeMap(code_map_holder);
1134         break;
1135       }
1136
1137       holder = next_holder;
1138     }
1139   }
1140 }
1141
1142
1143 void CodeFlusher::EvictJSFunctionCandidates() {
1144   JSFunction* candidate = jsfunction_candidates_head_;
1145   JSFunction* next_candidate;
1146   while (candidate != NULL) {
1147     next_candidate = GetNextCandidate(candidate);
1148     EvictCandidate(candidate);
1149     candidate = next_candidate;
1150   }
1151   DCHECK(jsfunction_candidates_head_ == NULL);
1152 }
1153
1154
1155 void CodeFlusher::EvictSharedFunctionInfoCandidates() {
1156   SharedFunctionInfo* candidate = shared_function_info_candidates_head_;
1157   SharedFunctionInfo* next_candidate;
1158   while (candidate != NULL) {
1159     next_candidate = GetNextCandidate(candidate);
1160     EvictCandidate(candidate);
1161     candidate = next_candidate;
1162   }
1163   DCHECK(shared_function_info_candidates_head_ == NULL);
1164 }
1165
1166
1167 void CodeFlusher::EvictOptimizedCodeMaps() {
1168   SharedFunctionInfo* holder = optimized_code_map_holder_head_;
1169   SharedFunctionInfo* next_holder;
1170   while (holder != NULL) {
1171     next_holder = GetNextCodeMap(holder);
1172     EvictOptimizedCodeMap(holder);
1173     holder = next_holder;
1174   }
1175   DCHECK(optimized_code_map_holder_head_ == NULL);
1176 }
1177
1178
1179 void CodeFlusher::IteratePointersToFromSpace(ObjectVisitor* v) {
1180   Heap* heap = isolate_->heap();
1181
1182   JSFunction** slot = &jsfunction_candidates_head_;
1183   JSFunction* candidate = jsfunction_candidates_head_;
1184   while (candidate != NULL) {
1185     if (heap->InFromSpace(candidate)) {
1186       v->VisitPointer(reinterpret_cast<Object**>(slot));
1187     }
1188     candidate = GetNextCandidate(*slot);
1189     slot = GetNextCandidateSlot(*slot);
1190   }
1191 }
1192
1193
1194 MarkCompactCollector::~MarkCompactCollector() {
1195   if (code_flusher_ != NULL) {
1196     delete code_flusher_;
1197     code_flusher_ = NULL;
1198   }
1199 }
1200
1201
1202 static inline HeapObject* ShortCircuitConsString(Object** p) {
1203   // Optimization: If the heap object pointed to by p is a non-internalized
1204   // cons string whose right substring is HEAP->empty_string, update
1205   // it in place to its left substring.  Return the updated value.
1206   //
1207   // Here we assume that if we change *p, we replace it with a heap object
1208   // (i.e., the left substring of a cons string is always a heap object).
1209   //
1210   // The check performed is:
1211   //   object->IsConsString() && !object->IsInternalizedString() &&
1212   //   (ConsString::cast(object)->second() == HEAP->empty_string())
1213   // except the maps for the object and its possible substrings might be
1214   // marked.
1215   HeapObject* object = HeapObject::cast(*p);
1216   Map* map = object->map();
1217   InstanceType type = map->instance_type();
1218   if (!IsShortcutCandidate(type)) return object;
1219
1220   Object* second = reinterpret_cast<ConsString*>(object)->second();
1221   Heap* heap = map->GetHeap();
1222   if (second != heap->empty_string()) {
1223     return object;
1224   }
1225
1226   // Since we don't have the object's start, it is impossible to update the
1227   // page dirty marks. Therefore, we only replace the string with its left
1228   // substring when page dirty marks do not change.
1229   Object* first = reinterpret_cast<ConsString*>(object)->first();
1230   if (!heap->InNewSpace(object) && heap->InNewSpace(first)) return object;
1231
1232   *p = first;
1233   return HeapObject::cast(first);
1234 }
1235
1236
1237 class MarkCompactMarkingVisitor
1238     : public StaticMarkingVisitor<MarkCompactMarkingVisitor> {
1239  public:
1240   static void ObjectStatsVisitBase(StaticVisitorBase::VisitorId id, Map* map,
1241                                    HeapObject* obj);
1242
1243   static void ObjectStatsCountFixedArray(
1244       FixedArrayBase* fixed_array, FixedArraySubInstanceType fast_type,
1245       FixedArraySubInstanceType dictionary_type);
1246
1247   template <MarkCompactMarkingVisitor::VisitorId id>
1248   class ObjectStatsTracker {
1249    public:
1250     static inline void Visit(Map* map, HeapObject* obj);
1251   };
1252
1253   static void Initialize();
1254
1255   INLINE(static void VisitPointer(Heap* heap, Object** p)) {
1256     MarkObjectByPointer(heap->mark_compact_collector(), p, p);
1257   }
1258
1259   INLINE(static void VisitPointers(Heap* heap, Object** start, Object** end)) {
1260     // Mark all objects pointed to in [start, end).
1261     const int kMinRangeForMarkingRecursion = 64;
1262     if (end - start >= kMinRangeForMarkingRecursion) {
1263       if (VisitUnmarkedObjects(heap, start, end)) return;
1264       // We are close to a stack overflow, so just mark the objects.
1265     }
1266     MarkCompactCollector* collector = heap->mark_compact_collector();
1267     for (Object** p = start; p < end; p++) {
1268       MarkObjectByPointer(collector, start, p);
1269     }
1270   }
1271
1272   // Marks the object black and pushes it on the marking stack.
1273   INLINE(static void MarkObject(Heap* heap, HeapObject* object)) {
1274     MarkBit mark = Marking::MarkBitFrom(object);
1275     heap->mark_compact_collector()->MarkObject(object, mark);
1276   }
1277
1278   // Marks the object black without pushing it on the marking stack.
1279   // Returns true if object needed marking and false otherwise.
1280   INLINE(static bool MarkObjectWithoutPush(Heap* heap, HeapObject* object)) {
1281     MarkBit mark_bit = Marking::MarkBitFrom(object);
1282     if (!mark_bit.Get()) {
1283       heap->mark_compact_collector()->SetMark(object, mark_bit);
1284       return true;
1285     }
1286     return false;
1287   }
1288
1289   // Mark object pointed to by p.
1290   INLINE(static void MarkObjectByPointer(MarkCompactCollector* collector,
1291                                          Object** anchor_slot, Object** p)) {
1292     if (!(*p)->IsHeapObject()) return;
1293     HeapObject* object = ShortCircuitConsString(p);
1294     collector->RecordSlot(anchor_slot, p, object);
1295     MarkBit mark = Marking::MarkBitFrom(object);
1296     collector->MarkObject(object, mark);
1297   }
1298
1299
1300   // Visit an unmarked object.
1301   INLINE(static void VisitUnmarkedObject(MarkCompactCollector* collector,
1302                                          HeapObject* obj)) {
1303 #ifdef DEBUG
1304     DCHECK(collector->heap()->Contains(obj));
1305     DCHECK(!collector->heap()->mark_compact_collector()->IsMarked(obj));
1306 #endif
1307     Map* map = obj->map();
1308     Heap* heap = obj->GetHeap();
1309     MarkBit mark = Marking::MarkBitFrom(obj);
1310     heap->mark_compact_collector()->SetMark(obj, mark);
1311     // Mark the map pointer and the body.
1312     MarkBit map_mark = Marking::MarkBitFrom(map);
1313     heap->mark_compact_collector()->MarkObject(map, map_mark);
1314     IterateBody(map, obj);
1315   }
1316
1317   // Visit all unmarked objects pointed to by [start, end).
1318   // Returns false if the operation fails (lack of stack space).
1319   INLINE(static bool VisitUnmarkedObjects(Heap* heap, Object** start,
1320                                           Object** end)) {
1321     // Return false is we are close to the stack limit.
1322     StackLimitCheck check(heap->isolate());
1323     if (check.HasOverflowed()) return false;
1324
1325     MarkCompactCollector* collector = heap->mark_compact_collector();
1326     // Visit the unmarked objects.
1327     for (Object** p = start; p < end; p++) {
1328       Object* o = *p;
1329       if (!o->IsHeapObject()) continue;
1330       collector->RecordSlot(start, p, o);
1331       HeapObject* obj = HeapObject::cast(o);
1332       MarkBit mark = Marking::MarkBitFrom(obj);
1333       if (mark.Get()) continue;
1334       VisitUnmarkedObject(collector, obj);
1335     }
1336     return true;
1337   }
1338
1339  private:
1340   template <int id>
1341   static inline void TrackObjectStatsAndVisit(Map* map, HeapObject* obj);
1342
1343   // Code flushing support.
1344
1345   static const int kRegExpCodeThreshold = 5;
1346
1347   static void UpdateRegExpCodeAgeAndFlush(Heap* heap, JSRegExp* re,
1348                                           bool is_one_byte) {
1349     // Make sure that the fixed array is in fact initialized on the RegExp.
1350     // We could potentially trigger a GC when initializing the RegExp.
1351     if (HeapObject::cast(re->data())->map()->instance_type() !=
1352         FIXED_ARRAY_TYPE)
1353       return;
1354
1355     // Make sure this is a RegExp that actually contains code.
1356     if (re->TypeTag() != JSRegExp::IRREGEXP) return;
1357
1358     Object* code = re->DataAt(JSRegExp::code_index(is_one_byte));
1359     if (!code->IsSmi() &&
1360         HeapObject::cast(code)->map()->instance_type() == CODE_TYPE) {
1361       // Save a copy that can be reinstated if we need the code again.
1362       re->SetDataAt(JSRegExp::saved_code_index(is_one_byte), code);
1363
1364       // Saving a copy might create a pointer into compaction candidate
1365       // that was not observed by marker.  This might happen if JSRegExp data
1366       // was marked through the compilation cache before marker reached JSRegExp
1367       // object.
1368       FixedArray* data = FixedArray::cast(re->data());
1369       Object** slot =
1370           data->data_start() + JSRegExp::saved_code_index(is_one_byte);
1371       heap->mark_compact_collector()->RecordSlot(slot, slot, code);
1372
1373       // Set a number in the 0-255 range to guarantee no smi overflow.
1374       re->SetDataAt(JSRegExp::code_index(is_one_byte),
1375                     Smi::FromInt(heap->sweep_generation() & 0xff));
1376     } else if (code->IsSmi()) {
1377       int value = Smi::cast(code)->value();
1378       // The regexp has not been compiled yet or there was a compilation error.
1379       if (value == JSRegExp::kUninitializedValue ||
1380           value == JSRegExp::kCompilationErrorValue) {
1381         return;
1382       }
1383
1384       // Check if we should flush now.
1385       if (value == ((heap->sweep_generation() - kRegExpCodeThreshold) & 0xff)) {
1386         re->SetDataAt(JSRegExp::code_index(is_one_byte),
1387                       Smi::FromInt(JSRegExp::kUninitializedValue));
1388         re->SetDataAt(JSRegExp::saved_code_index(is_one_byte),
1389                       Smi::FromInt(JSRegExp::kUninitializedValue));
1390       }
1391     }
1392   }
1393
1394
1395   // Works by setting the current sweep_generation (as a smi) in the
1396   // code object place in the data array of the RegExp and keeps a copy
1397   // around that can be reinstated if we reuse the RegExp before flushing.
1398   // If we did not use the code for kRegExpCodeThreshold mark sweep GCs
1399   // we flush the code.
1400   static void VisitRegExpAndFlushCode(Map* map, HeapObject* object) {
1401     Heap* heap = map->GetHeap();
1402     MarkCompactCollector* collector = heap->mark_compact_collector();
1403     if (!collector->is_code_flushing_enabled()) {
1404       VisitJSRegExp(map, object);
1405       return;
1406     }
1407     JSRegExp* re = reinterpret_cast<JSRegExp*>(object);
1408     // Flush code or set age on both one byte and two byte code.
1409     UpdateRegExpCodeAgeAndFlush(heap, re, true);
1410     UpdateRegExpCodeAgeAndFlush(heap, re, false);
1411     // Visit the fields of the RegExp, including the updated FixedArray.
1412     VisitJSRegExp(map, object);
1413   }
1414
1415   static VisitorDispatchTable<Callback> non_count_table_;
1416 };
1417
1418
1419 void MarkCompactMarkingVisitor::ObjectStatsCountFixedArray(
1420     FixedArrayBase* fixed_array, FixedArraySubInstanceType fast_type,
1421     FixedArraySubInstanceType dictionary_type) {
1422   Heap* heap = fixed_array->map()->GetHeap();
1423   if (fixed_array->map() != heap->fixed_cow_array_map() &&
1424       fixed_array->map() != heap->fixed_double_array_map() &&
1425       fixed_array != heap->empty_fixed_array()) {
1426     if (fixed_array->IsDictionary()) {
1427       heap->RecordFixedArraySubTypeStats(dictionary_type, fixed_array->Size());
1428     } else {
1429       heap->RecordFixedArraySubTypeStats(fast_type, fixed_array->Size());
1430     }
1431   }
1432 }
1433
1434
1435 void MarkCompactMarkingVisitor::ObjectStatsVisitBase(
1436     MarkCompactMarkingVisitor::VisitorId id, Map* map, HeapObject* obj) {
1437   Heap* heap = map->GetHeap();
1438   int object_size = obj->Size();
1439   heap->RecordObjectStats(map->instance_type(), object_size);
1440   non_count_table_.GetVisitorById(id)(map, obj);
1441   if (obj->IsJSObject()) {
1442     JSObject* object = JSObject::cast(obj);
1443     ObjectStatsCountFixedArray(object->elements(), DICTIONARY_ELEMENTS_SUB_TYPE,
1444                                FAST_ELEMENTS_SUB_TYPE);
1445     ObjectStatsCountFixedArray(object->properties(),
1446                                DICTIONARY_PROPERTIES_SUB_TYPE,
1447                                FAST_PROPERTIES_SUB_TYPE);
1448   }
1449 }
1450
1451
1452 template <MarkCompactMarkingVisitor::VisitorId id>
1453 void MarkCompactMarkingVisitor::ObjectStatsTracker<id>::Visit(Map* map,
1454                                                               HeapObject* obj) {
1455   ObjectStatsVisitBase(id, map, obj);
1456 }
1457
1458
1459 template <>
1460 class MarkCompactMarkingVisitor::ObjectStatsTracker<
1461     MarkCompactMarkingVisitor::kVisitMap> {
1462  public:
1463   static inline void Visit(Map* map, HeapObject* obj) {
1464     Heap* heap = map->GetHeap();
1465     Map* map_obj = Map::cast(obj);
1466     DCHECK(map->instance_type() == MAP_TYPE);
1467     DescriptorArray* array = map_obj->instance_descriptors();
1468     if (map_obj->owns_descriptors() &&
1469         array != heap->empty_descriptor_array()) {
1470       int fixed_array_size = array->Size();
1471       heap->RecordFixedArraySubTypeStats(DESCRIPTOR_ARRAY_SUB_TYPE,
1472                                          fixed_array_size);
1473     }
1474     if (map_obj->HasTransitionArray()) {
1475       int fixed_array_size = map_obj->transitions()->Size();
1476       heap->RecordFixedArraySubTypeStats(TRANSITION_ARRAY_SUB_TYPE,
1477                                          fixed_array_size);
1478     }
1479     if (map_obj->has_code_cache()) {
1480       CodeCache* cache = CodeCache::cast(map_obj->code_cache());
1481       heap->RecordFixedArraySubTypeStats(MAP_CODE_CACHE_SUB_TYPE,
1482                                          cache->default_cache()->Size());
1483       if (!cache->normal_type_cache()->IsUndefined()) {
1484         heap->RecordFixedArraySubTypeStats(
1485             MAP_CODE_CACHE_SUB_TYPE,
1486             FixedArray::cast(cache->normal_type_cache())->Size());
1487       }
1488     }
1489     ObjectStatsVisitBase(kVisitMap, map, obj);
1490   }
1491 };
1492
1493
1494 template <>
1495 class MarkCompactMarkingVisitor::ObjectStatsTracker<
1496     MarkCompactMarkingVisitor::kVisitCode> {
1497  public:
1498   static inline void Visit(Map* map, HeapObject* obj) {
1499     Heap* heap = map->GetHeap();
1500     int object_size = obj->Size();
1501     DCHECK(map->instance_type() == CODE_TYPE);
1502     Code* code_obj = Code::cast(obj);
1503     heap->RecordCodeSubTypeStats(code_obj->kind(), code_obj->GetRawAge(),
1504                                  object_size);
1505     ObjectStatsVisitBase(kVisitCode, map, obj);
1506   }
1507 };
1508
1509
1510 template <>
1511 class MarkCompactMarkingVisitor::ObjectStatsTracker<
1512     MarkCompactMarkingVisitor::kVisitSharedFunctionInfo> {
1513  public:
1514   static inline void Visit(Map* map, HeapObject* obj) {
1515     Heap* heap = map->GetHeap();
1516     SharedFunctionInfo* sfi = SharedFunctionInfo::cast(obj);
1517     if (sfi->scope_info() != heap->empty_fixed_array()) {
1518       heap->RecordFixedArraySubTypeStats(
1519           SCOPE_INFO_SUB_TYPE, FixedArray::cast(sfi->scope_info())->Size());
1520     }
1521     ObjectStatsVisitBase(kVisitSharedFunctionInfo, map, obj);
1522   }
1523 };
1524
1525
1526 template <>
1527 class MarkCompactMarkingVisitor::ObjectStatsTracker<
1528     MarkCompactMarkingVisitor::kVisitFixedArray> {
1529  public:
1530   static inline void Visit(Map* map, HeapObject* obj) {
1531     Heap* heap = map->GetHeap();
1532     FixedArray* fixed_array = FixedArray::cast(obj);
1533     if (fixed_array == heap->string_table()) {
1534       heap->RecordFixedArraySubTypeStats(STRING_TABLE_SUB_TYPE,
1535                                          fixed_array->Size());
1536     }
1537     ObjectStatsVisitBase(kVisitFixedArray, map, obj);
1538   }
1539 };
1540
1541
1542 void MarkCompactMarkingVisitor::Initialize() {
1543   StaticMarkingVisitor<MarkCompactMarkingVisitor>::Initialize();
1544
1545   table_.Register(kVisitJSRegExp, &VisitRegExpAndFlushCode);
1546
1547   if (FLAG_track_gc_object_stats) {
1548     // Copy the visitor table to make call-through possible.
1549     non_count_table_.CopyFrom(&table_);
1550 #define VISITOR_ID_COUNT_FUNCTION(id) \
1551   table_.Register(kVisit##id, ObjectStatsTracker<kVisit##id>::Visit);
1552     VISITOR_ID_LIST(VISITOR_ID_COUNT_FUNCTION)
1553 #undef VISITOR_ID_COUNT_FUNCTION
1554   }
1555 }
1556
1557
1558 VisitorDispatchTable<MarkCompactMarkingVisitor::Callback>
1559     MarkCompactMarkingVisitor::non_count_table_;
1560
1561
1562 class CodeMarkingVisitor : public ThreadVisitor {
1563  public:
1564   explicit CodeMarkingVisitor(MarkCompactCollector* collector)
1565       : collector_(collector) {}
1566
1567   void VisitThread(Isolate* isolate, ThreadLocalTop* top) {
1568     collector_->PrepareThreadForCodeFlushing(isolate, top);
1569   }
1570
1571  private:
1572   MarkCompactCollector* collector_;
1573 };
1574
1575
1576 class SharedFunctionInfoMarkingVisitor : public ObjectVisitor {
1577  public:
1578   explicit SharedFunctionInfoMarkingVisitor(MarkCompactCollector* collector)
1579       : collector_(collector) {}
1580
1581   void VisitPointers(Object** start, Object** end) {
1582     for (Object** p = start; p < end; p++) VisitPointer(p);
1583   }
1584
1585   void VisitPointer(Object** slot) {
1586     Object* obj = *slot;
1587     if (obj->IsSharedFunctionInfo()) {
1588       SharedFunctionInfo* shared = reinterpret_cast<SharedFunctionInfo*>(obj);
1589       MarkBit shared_mark = Marking::MarkBitFrom(shared);
1590       MarkBit code_mark = Marking::MarkBitFrom(shared->code());
1591       collector_->MarkObject(shared->code(), code_mark);
1592       collector_->MarkObject(shared, shared_mark);
1593     }
1594   }
1595
1596  private:
1597   MarkCompactCollector* collector_;
1598 };
1599
1600
1601 void MarkCompactCollector::PrepareThreadForCodeFlushing(Isolate* isolate,
1602                                                         ThreadLocalTop* top) {
1603   for (StackFrameIterator it(isolate, top); !it.done(); it.Advance()) {
1604     // Note: for the frame that has a pending lazy deoptimization
1605     // StackFrame::unchecked_code will return a non-optimized code object for
1606     // the outermost function and StackFrame::LookupCode will return
1607     // actual optimized code object.
1608     StackFrame* frame = it.frame();
1609     Code* code = frame->unchecked_code();
1610     MarkBit code_mark = Marking::MarkBitFrom(code);
1611     MarkObject(code, code_mark);
1612     if (frame->is_optimized()) {
1613       MarkCompactMarkingVisitor::MarkInlinedFunctionsCode(heap(),
1614                                                           frame->LookupCode());
1615     }
1616   }
1617 }
1618
1619
1620 void MarkCompactCollector::PrepareForCodeFlushing() {
1621   // Enable code flushing for non-incremental cycles.
1622   if (FLAG_flush_code && !FLAG_flush_code_incrementally) {
1623     EnableCodeFlushing(!was_marked_incrementally_);
1624   }
1625
1626   // If code flushing is disabled, there is no need to prepare for it.
1627   if (!is_code_flushing_enabled()) return;
1628
1629   // Ensure that empty descriptor array is marked. Method MarkDescriptorArray
1630   // relies on it being marked before any other descriptor array.
1631   HeapObject* descriptor_array = heap()->empty_descriptor_array();
1632   MarkBit descriptor_array_mark = Marking::MarkBitFrom(descriptor_array);
1633   MarkObject(descriptor_array, descriptor_array_mark);
1634
1635   // Make sure we are not referencing the code from the stack.
1636   DCHECK(this == heap()->mark_compact_collector());
1637   PrepareThreadForCodeFlushing(heap()->isolate(),
1638                                heap()->isolate()->thread_local_top());
1639
1640   // Iterate the archived stacks in all threads to check if
1641   // the code is referenced.
1642   CodeMarkingVisitor code_marking_visitor(this);
1643   heap()->isolate()->thread_manager()->IterateArchivedThreads(
1644       &code_marking_visitor);
1645
1646   SharedFunctionInfoMarkingVisitor visitor(this);
1647   heap()->isolate()->compilation_cache()->IterateFunctions(&visitor);
1648   heap()->isolate()->handle_scope_implementer()->Iterate(&visitor);
1649
1650   ProcessMarkingDeque();
1651 }
1652
1653
1654 // Visitor class for marking heap roots.
1655 class RootMarkingVisitor : public ObjectVisitor {
1656  public:
1657   explicit RootMarkingVisitor(Heap* heap)
1658       : collector_(heap->mark_compact_collector()) {}
1659
1660   void VisitPointer(Object** p) { MarkObjectByPointer(p); }
1661
1662   void VisitPointers(Object** start, Object** end) {
1663     for (Object** p = start; p < end; p++) MarkObjectByPointer(p);
1664   }
1665
1666   // Skip the weak next code link in a code object, which is visited in
1667   // ProcessTopOptimizedFrame.
1668   void VisitNextCodeLink(Object** p) {}
1669
1670  private:
1671   void MarkObjectByPointer(Object** p) {
1672     if (!(*p)->IsHeapObject()) return;
1673
1674     // Replace flat cons strings in place.
1675     HeapObject* object = ShortCircuitConsString(p);
1676     MarkBit mark_bit = Marking::MarkBitFrom(object);
1677     if (mark_bit.Get()) return;
1678
1679     Map* map = object->map();
1680     // Mark the object.
1681     collector_->SetMark(object, mark_bit);
1682
1683     // Mark the map pointer and body, and push them on the marking stack.
1684     MarkBit map_mark = Marking::MarkBitFrom(map);
1685     collector_->MarkObject(map, map_mark);
1686     MarkCompactMarkingVisitor::IterateBody(map, object);
1687
1688     // Mark all the objects reachable from the map and body.  May leave
1689     // overflowed objects in the heap.
1690     collector_->EmptyMarkingDeque();
1691   }
1692
1693   MarkCompactCollector* collector_;
1694 };
1695
1696
1697 // Helper class for pruning the string table.
1698 template <bool finalize_external_strings>
1699 class StringTableCleaner : public ObjectVisitor {
1700  public:
1701   explicit StringTableCleaner(Heap* heap) : heap_(heap), pointers_removed_(0) {}
1702
1703   virtual void VisitPointers(Object** start, Object** end) {
1704     // Visit all HeapObject pointers in [start, end).
1705     for (Object** p = start; p < end; p++) {
1706       Object* o = *p;
1707       if (o->IsHeapObject() &&
1708           !Marking::MarkBitFrom(HeapObject::cast(o)).Get()) {
1709         if (finalize_external_strings) {
1710           DCHECK(o->IsExternalString());
1711           heap_->FinalizeExternalString(String::cast(*p));
1712         } else {
1713           pointers_removed_++;
1714         }
1715         // Set the entry to the_hole_value (as deleted).
1716         *p = heap_->the_hole_value();
1717       }
1718     }
1719   }
1720
1721   int PointersRemoved() {
1722     DCHECK(!finalize_external_strings);
1723     return pointers_removed_;
1724   }
1725
1726  private:
1727   Heap* heap_;
1728   int pointers_removed_;
1729 };
1730
1731
1732 typedef StringTableCleaner<false> InternalizedStringTableCleaner;
1733 typedef StringTableCleaner<true> ExternalStringTableCleaner;
1734
1735
1736 // Implementation of WeakObjectRetainer for mark compact GCs. All marked objects
1737 // are retained.
1738 class MarkCompactWeakObjectRetainer : public WeakObjectRetainer {
1739  public:
1740   virtual Object* RetainAs(Object* object) {
1741     if (Marking::MarkBitFrom(HeapObject::cast(object)).Get()) {
1742       return object;
1743     } else if (object->IsAllocationSite() &&
1744                !(AllocationSite::cast(object)->IsZombie())) {
1745       // "dead" AllocationSites need to live long enough for a traversal of new
1746       // space. These sites get a one-time reprieve.
1747       AllocationSite* site = AllocationSite::cast(object);
1748       site->MarkZombie();
1749       site->GetHeap()->mark_compact_collector()->MarkAllocationSite(site);
1750       return object;
1751     } else {
1752       return NULL;
1753     }
1754   }
1755 };
1756
1757
1758 // Fill the marking stack with overflowed objects returned by the given
1759 // iterator.  Stop when the marking stack is filled or the end of the space
1760 // is reached, whichever comes first.
1761 template <class T>
1762 static void DiscoverGreyObjectsWithIterator(Heap* heap,
1763                                             MarkingDeque* marking_deque,
1764                                             T* it) {
1765   // The caller should ensure that the marking stack is initially not full,
1766   // so that we don't waste effort pointlessly scanning for objects.
1767   DCHECK(!marking_deque->IsFull());
1768
1769   Map* filler_map = heap->one_pointer_filler_map();
1770   for (HeapObject* object = it->Next(); object != NULL; object = it->Next()) {
1771     MarkBit markbit = Marking::MarkBitFrom(object);
1772     if ((object->map() != filler_map) && Marking::IsGrey(markbit)) {
1773       Marking::GreyToBlack(markbit);
1774       MemoryChunk::IncrementLiveBytesFromGC(object->address(), object->Size());
1775       marking_deque->PushBlack(object);
1776       if (marking_deque->IsFull()) return;
1777     }
1778   }
1779 }
1780
1781
1782 static inline int MarkWordToObjectStarts(uint32_t mark_bits, int* starts);
1783
1784
1785 static void DiscoverGreyObjectsOnPage(MarkingDeque* marking_deque,
1786                                       MemoryChunk* p) {
1787   DCHECK(!marking_deque->IsFull());
1788   DCHECK(strcmp(Marking::kWhiteBitPattern, "00") == 0);
1789   DCHECK(strcmp(Marking::kBlackBitPattern, "10") == 0);
1790   DCHECK(strcmp(Marking::kGreyBitPattern, "11") == 0);
1791   DCHECK(strcmp(Marking::kImpossibleBitPattern, "01") == 0);
1792
1793   for (MarkBitCellIterator it(p); !it.Done(); it.Advance()) {
1794     Address cell_base = it.CurrentCellBase();
1795     MarkBit::CellType* cell = it.CurrentCell();
1796
1797     const MarkBit::CellType current_cell = *cell;
1798     if (current_cell == 0) continue;
1799
1800     MarkBit::CellType grey_objects;
1801     if (it.HasNext()) {
1802       const MarkBit::CellType next_cell = *(cell + 1);
1803       grey_objects = current_cell & ((current_cell >> 1) |
1804                                      (next_cell << (Bitmap::kBitsPerCell - 1)));
1805     } else {
1806       grey_objects = current_cell & (current_cell >> 1);
1807     }
1808
1809     int offset = 0;
1810     while (grey_objects != 0) {
1811       int trailing_zeros = base::bits::CountTrailingZeros32(grey_objects);
1812       grey_objects >>= trailing_zeros;
1813       offset += trailing_zeros;
1814       MarkBit markbit(cell, 1 << offset, false);
1815       DCHECK(Marking::IsGrey(markbit));
1816       Marking::GreyToBlack(markbit);
1817       Address addr = cell_base + offset * kPointerSize;
1818       HeapObject* object = HeapObject::FromAddress(addr);
1819       MemoryChunk::IncrementLiveBytesFromGC(object->address(), object->Size());
1820       marking_deque->PushBlack(object);
1821       if (marking_deque->IsFull()) return;
1822       offset += 2;
1823       grey_objects >>= 2;
1824     }
1825
1826     grey_objects >>= (Bitmap::kBitsPerCell - 1);
1827   }
1828 }
1829
1830
1831 int MarkCompactCollector::DiscoverAndEvacuateBlackObjectsOnPage(
1832     NewSpace* new_space, NewSpacePage* p) {
1833   DCHECK(strcmp(Marking::kWhiteBitPattern, "00") == 0);
1834   DCHECK(strcmp(Marking::kBlackBitPattern, "10") == 0);
1835   DCHECK(strcmp(Marking::kGreyBitPattern, "11") == 0);
1836   DCHECK(strcmp(Marking::kImpossibleBitPattern, "01") == 0);
1837
1838   MarkBit::CellType* cells = p->markbits()->cells();
1839   int survivors_size = 0;
1840
1841   for (MarkBitCellIterator it(p); !it.Done(); it.Advance()) {
1842     Address cell_base = it.CurrentCellBase();
1843     MarkBit::CellType* cell = it.CurrentCell();
1844
1845     MarkBit::CellType current_cell = *cell;
1846     if (current_cell == 0) continue;
1847
1848     int offset = 0;
1849     while (current_cell != 0) {
1850       int trailing_zeros = base::bits::CountTrailingZeros32(current_cell);
1851       current_cell >>= trailing_zeros;
1852       offset += trailing_zeros;
1853       Address address = cell_base + offset * kPointerSize;
1854       HeapObject* object = HeapObject::FromAddress(address);
1855
1856       int size = object->Size();
1857       survivors_size += size;
1858
1859       Heap::UpdateAllocationSiteFeedback(object, Heap::RECORD_SCRATCHPAD_SLOT);
1860
1861       offset++;
1862       current_cell >>= 1;
1863
1864       // TODO(hpayer): Refactor EvacuateObject and call this function instead.
1865       if (heap()->ShouldBePromoted(object->address(), size) &&
1866           TryPromoteObject(object, size)) {
1867         continue;
1868       }
1869
1870       AllocationResult allocation = new_space->AllocateRaw(size);
1871       if (allocation.IsRetry()) {
1872         if (!new_space->AddFreshPage()) {
1873           // Shouldn't happen. We are sweeping linearly, and to-space
1874           // has the same number of pages as from-space, so there is
1875           // always room.
1876           UNREACHABLE();
1877         }
1878         allocation = new_space->AllocateRaw(size);
1879         DCHECK(!allocation.IsRetry());
1880       }
1881       Object* target = allocation.ToObjectChecked();
1882
1883       MigrateObject(HeapObject::cast(target), object, size, NEW_SPACE);
1884       heap()->IncrementSemiSpaceCopiedObjectSize(size);
1885     }
1886     *cells = 0;
1887   }
1888   return survivors_size;
1889 }
1890
1891
1892 static void DiscoverGreyObjectsInSpace(Heap* heap, MarkingDeque* marking_deque,
1893                                        PagedSpace* space) {
1894   PageIterator it(space);
1895   while (it.has_next()) {
1896     Page* p = it.next();
1897     DiscoverGreyObjectsOnPage(marking_deque, p);
1898     if (marking_deque->IsFull()) return;
1899   }
1900 }
1901
1902
1903 static void DiscoverGreyObjectsInNewSpace(Heap* heap,
1904                                           MarkingDeque* marking_deque) {
1905   NewSpace* space = heap->new_space();
1906   NewSpacePageIterator it(space->bottom(), space->top());
1907   while (it.has_next()) {
1908     NewSpacePage* page = it.next();
1909     DiscoverGreyObjectsOnPage(marking_deque, page);
1910     if (marking_deque->IsFull()) return;
1911   }
1912 }
1913
1914
1915 bool MarkCompactCollector::IsUnmarkedHeapObject(Object** p) {
1916   Object* o = *p;
1917   if (!o->IsHeapObject()) return false;
1918   HeapObject* heap_object = HeapObject::cast(o);
1919   MarkBit mark = Marking::MarkBitFrom(heap_object);
1920   return !mark.Get();
1921 }
1922
1923
1924 bool MarkCompactCollector::IsUnmarkedHeapObjectWithHeap(Heap* heap,
1925                                                         Object** p) {
1926   Object* o = *p;
1927   DCHECK(o->IsHeapObject());
1928   HeapObject* heap_object = HeapObject::cast(o);
1929   MarkBit mark = Marking::MarkBitFrom(heap_object);
1930   return !mark.Get();
1931 }
1932
1933
1934 void MarkCompactCollector::MarkStringTable(RootMarkingVisitor* visitor) {
1935   StringTable* string_table = heap()->string_table();
1936   // Mark the string table itself.
1937   MarkBit string_table_mark = Marking::MarkBitFrom(string_table);
1938   if (!string_table_mark.Get()) {
1939     // String table could have already been marked by visiting the handles list.
1940     SetMark(string_table, string_table_mark);
1941   }
1942   // Explicitly mark the prefix.
1943   string_table->IteratePrefix(visitor);
1944   ProcessMarkingDeque();
1945 }
1946
1947
1948 void MarkCompactCollector::MarkAllocationSite(AllocationSite* site) {
1949   MarkBit mark_bit = Marking::MarkBitFrom(site);
1950   SetMark(site, mark_bit);
1951 }
1952
1953
1954 void MarkCompactCollector::MarkRoots(RootMarkingVisitor* visitor) {
1955   // Mark the heap roots including global variables, stack variables,
1956   // etc., and all objects reachable from them.
1957   heap()->IterateStrongRoots(visitor, VISIT_ONLY_STRONG);
1958
1959   // Handle the string table specially.
1960   MarkStringTable(visitor);
1961
1962   MarkWeakObjectToCodeTable();
1963
1964   // There may be overflowed objects in the heap.  Visit them now.
1965   while (marking_deque_.overflowed()) {
1966     RefillMarkingDeque();
1967     EmptyMarkingDeque();
1968   }
1969 }
1970
1971
1972 void MarkCompactCollector::MarkImplicitRefGroups() {
1973   List<ImplicitRefGroup*>* ref_groups =
1974       isolate()->global_handles()->implicit_ref_groups();
1975
1976   int last = 0;
1977   for (int i = 0; i < ref_groups->length(); i++) {
1978     ImplicitRefGroup* entry = ref_groups->at(i);
1979     DCHECK(entry != NULL);
1980
1981     if (!IsMarked(*entry->parent)) {
1982       (*ref_groups)[last++] = entry;
1983       continue;
1984     }
1985
1986     Object*** children = entry->children;
1987     // A parent object is marked, so mark all child heap objects.
1988     for (size_t j = 0; j < entry->length; ++j) {
1989       if ((*children[j])->IsHeapObject()) {
1990         HeapObject* child = HeapObject::cast(*children[j]);
1991         MarkBit mark = Marking::MarkBitFrom(child);
1992         MarkObject(child, mark);
1993       }
1994     }
1995
1996     // Once the entire group has been marked, dispose it because it's
1997     // not needed anymore.
1998     delete entry;
1999   }
2000   ref_groups->Rewind(last);
2001 }
2002
2003
2004 void MarkCompactCollector::MarkWeakObjectToCodeTable() {
2005   HeapObject* weak_object_to_code_table =
2006       HeapObject::cast(heap()->weak_object_to_code_table());
2007   if (!IsMarked(weak_object_to_code_table)) {
2008     MarkBit mark = Marking::MarkBitFrom(weak_object_to_code_table);
2009     SetMark(weak_object_to_code_table, mark);
2010   }
2011 }
2012
2013
2014 // Mark all objects reachable from the objects on the marking stack.
2015 // Before: the marking stack contains zero or more heap object pointers.
2016 // After: the marking stack is empty, and all objects reachable from the
2017 // marking stack have been marked, or are overflowed in the heap.
2018 void MarkCompactCollector::EmptyMarkingDeque() {
2019   Map* filler_map = heap_->one_pointer_filler_map();
2020   while (!marking_deque_.IsEmpty()) {
2021     HeapObject* object = marking_deque_.Pop();
2022     // Explicitly skip one word fillers. Incremental markbit patterns are
2023     // correct only for objects that occupy at least two words.
2024     Map* map = object->map();
2025     if (map == filler_map) continue;
2026
2027     DCHECK(object->IsHeapObject());
2028     DCHECK(heap()->Contains(object));
2029     DCHECK(!Marking::IsWhite(Marking::MarkBitFrom(object)));
2030
2031     MarkBit map_mark = Marking::MarkBitFrom(map);
2032     MarkObject(map, map_mark);
2033
2034     MarkCompactMarkingVisitor::IterateBody(map, object);
2035   }
2036 }
2037
2038
2039 // Sweep the heap for overflowed objects, clear their overflow bits, and
2040 // push them on the marking stack.  Stop early if the marking stack fills
2041 // before sweeping completes.  If sweeping completes, there are no remaining
2042 // overflowed objects in the heap so the overflow flag on the markings stack
2043 // is cleared.
2044 void MarkCompactCollector::RefillMarkingDeque() {
2045   DCHECK(marking_deque_.overflowed());
2046
2047   DiscoverGreyObjectsInNewSpace(heap(), &marking_deque_);
2048   if (marking_deque_.IsFull()) return;
2049
2050   DiscoverGreyObjectsInSpace(heap(), &marking_deque_,
2051                              heap()->old_pointer_space());
2052   if (marking_deque_.IsFull()) return;
2053
2054   DiscoverGreyObjectsInSpace(heap(), &marking_deque_, heap()->old_data_space());
2055   if (marking_deque_.IsFull()) return;
2056
2057   DiscoverGreyObjectsInSpace(heap(), &marking_deque_, heap()->code_space());
2058   if (marking_deque_.IsFull()) return;
2059
2060   DiscoverGreyObjectsInSpace(heap(), &marking_deque_, heap()->map_space());
2061   if (marking_deque_.IsFull()) return;
2062
2063   DiscoverGreyObjectsInSpace(heap(), &marking_deque_, heap()->cell_space());
2064   if (marking_deque_.IsFull()) return;
2065
2066   DiscoverGreyObjectsInSpace(heap(), &marking_deque_,
2067                              heap()->property_cell_space());
2068   if (marking_deque_.IsFull()) return;
2069
2070   LargeObjectIterator lo_it(heap()->lo_space());
2071   DiscoverGreyObjectsWithIterator(heap(), &marking_deque_, &lo_it);
2072   if (marking_deque_.IsFull()) return;
2073
2074   marking_deque_.ClearOverflowed();
2075 }
2076
2077
2078 // Mark all objects reachable (transitively) from objects on the marking
2079 // stack.  Before: the marking stack contains zero or more heap object
2080 // pointers.  After: the marking stack is empty and there are no overflowed
2081 // objects in the heap.
2082 void MarkCompactCollector::ProcessMarkingDeque() {
2083   EmptyMarkingDeque();
2084   while (marking_deque_.overflowed()) {
2085     RefillMarkingDeque();
2086     EmptyMarkingDeque();
2087   }
2088 }
2089
2090
2091 // Mark all objects reachable (transitively) from objects on the marking
2092 // stack including references only considered in the atomic marking pause.
2093 void MarkCompactCollector::ProcessEphemeralMarking(
2094     ObjectVisitor* visitor, bool only_process_harmony_weak_collections) {
2095   bool work_to_do = true;
2096   DCHECK(marking_deque_.IsEmpty() && !marking_deque_.overflowed());
2097   while (work_to_do) {
2098     if (!only_process_harmony_weak_collections) {
2099       isolate()->global_handles()->IterateObjectGroups(
2100           visitor, &IsUnmarkedHeapObjectWithHeap);
2101       MarkImplicitRefGroups();
2102     }
2103     ProcessWeakCollections();
2104     work_to_do = !marking_deque_.IsEmpty();
2105     ProcessMarkingDeque();
2106   }
2107 }
2108
2109
2110 void MarkCompactCollector::ProcessTopOptimizedFrame(ObjectVisitor* visitor) {
2111   for (StackFrameIterator it(isolate(), isolate()->thread_local_top());
2112        !it.done(); it.Advance()) {
2113     if (it.frame()->type() == StackFrame::JAVA_SCRIPT) {
2114       return;
2115     }
2116     if (it.frame()->type() == StackFrame::OPTIMIZED) {
2117       Code* code = it.frame()->LookupCode();
2118       if (!code->CanDeoptAt(it.frame()->pc())) {
2119         code->CodeIterateBody(visitor);
2120       }
2121       ProcessMarkingDeque();
2122       return;
2123     }
2124   }
2125 }
2126
2127
2128 void MarkCompactCollector::EnsureMarkingDequeIsCommittedAndInitialize() {
2129   if (marking_deque_memory_ == NULL) {
2130     marking_deque_memory_ = new base::VirtualMemory(4 * MB);
2131   }
2132   if (!marking_deque_memory_committed_) {
2133     bool success = marking_deque_memory_->Commit(
2134         reinterpret_cast<Address>(marking_deque_memory_->address()),
2135         marking_deque_memory_->size(),
2136         false);  // Not executable.
2137     CHECK(success);
2138     marking_deque_memory_committed_ = true;
2139     InitializeMarkingDeque();
2140   }
2141 }
2142
2143
2144 void MarkCompactCollector::InitializeMarkingDeque() {
2145   if (marking_deque_memory_committed_) {
2146     Address addr = static_cast<Address>(marking_deque_memory_->address());
2147     size_t size = marking_deque_memory_->size();
2148     if (FLAG_force_marking_deque_overflows) size = 64 * kPointerSize;
2149     marking_deque_.Initialize(addr, addr + size);
2150   }
2151 }
2152
2153
2154 void MarkCompactCollector::UncommitMarkingDeque() {
2155   if (marking_deque_memory_committed_) {
2156     bool success = marking_deque_memory_->Uncommit(
2157         reinterpret_cast<Address>(marking_deque_memory_->address()),
2158         marking_deque_memory_->size());
2159     CHECK(success);
2160     marking_deque_memory_committed_ = false;
2161   }
2162 }
2163
2164
2165 void MarkCompactCollector::MarkLiveObjects() {
2166   GCTracer::Scope gc_scope(heap()->tracer(), GCTracer::Scope::MC_MARK);
2167   double start_time = 0.0;
2168   if (FLAG_print_cumulative_gc_stat) {
2169     start_time = base::OS::TimeCurrentMillis();
2170   }
2171   // The recursive GC marker detects when it is nearing stack overflow,
2172   // and switches to a different marking system.  JS interrupts interfere
2173   // with the C stack limit check.
2174   PostponeInterruptsScope postpone(isolate());
2175
2176   IncrementalMarking* incremental_marking = heap_->incremental_marking();
2177   if (was_marked_incrementally_) {
2178     incremental_marking->Finalize();
2179   } else {
2180     // Abort any pending incremental activities e.g. incremental sweeping.
2181     incremental_marking->Abort();
2182     InitializeMarkingDeque();
2183   }
2184
2185 #ifdef DEBUG
2186   DCHECK(state_ == PREPARE_GC);
2187   state_ = MARK_LIVE_OBJECTS;
2188 #endif
2189
2190   EnsureMarkingDequeIsCommittedAndInitialize();
2191
2192   PrepareForCodeFlushing();
2193
2194   if (was_marked_incrementally_) {
2195     // There is no write barrier on cells so we have to scan them now at the end
2196     // of the incremental marking.
2197     {
2198       HeapObjectIterator cell_iterator(heap()->cell_space());
2199       HeapObject* cell;
2200       while ((cell = cell_iterator.Next()) != NULL) {
2201         DCHECK(cell->IsCell());
2202         if (IsMarked(cell)) {
2203           int offset = Cell::kValueOffset;
2204           MarkCompactMarkingVisitor::VisitPointer(
2205               heap(), reinterpret_cast<Object**>(cell->address() + offset));
2206         }
2207       }
2208     }
2209     {
2210       HeapObjectIterator js_global_property_cell_iterator(
2211           heap()->property_cell_space());
2212       HeapObject* cell;
2213       while ((cell = js_global_property_cell_iterator.Next()) != NULL) {
2214         DCHECK(cell->IsPropertyCell());
2215         if (IsMarked(cell)) {
2216           MarkCompactMarkingVisitor::VisitPropertyCell(cell->map(), cell);
2217         }
2218       }
2219     }
2220   }
2221
2222   RootMarkingVisitor root_visitor(heap());
2223   MarkRoots(&root_visitor);
2224
2225   ProcessTopOptimizedFrame(&root_visitor);
2226
2227   {
2228     GCTracer::Scope gc_scope(heap()->tracer(), GCTracer::Scope::MC_WEAKCLOSURE);
2229
2230     // The objects reachable from the roots are marked, yet unreachable
2231     // objects are unmarked.  Mark objects reachable due to host
2232     // application specific logic or through Harmony weak maps.
2233     ProcessEphemeralMarking(&root_visitor, false);
2234
2235     // The objects reachable from the roots, weak maps or object groups
2236     // are marked. Objects pointed to only by weak global handles cannot be
2237     // immediately reclaimed. Instead, we have to mark them as pending and mark
2238     // objects reachable from them.
2239     //
2240     // First we identify nonlive weak handles and mark them as pending
2241     // destruction.
2242     heap()->isolate()->global_handles()->IdentifyWeakHandles(
2243         &IsUnmarkedHeapObject);
2244     // Then we mark the objects.
2245     heap()->isolate()->global_handles()->IterateWeakRoots(&root_visitor);
2246     ProcessMarkingDeque();
2247
2248     // Repeat Harmony weak maps marking to mark unmarked objects reachable from
2249     // the weak roots we just marked as pending destruction.
2250     //
2251     // We only process harmony collections, as all object groups have been fully
2252     // processed and no weakly reachable node can discover new objects groups.
2253     ProcessEphemeralMarking(&root_visitor, true);
2254   }
2255
2256   AfterMarking();
2257
2258   if (FLAG_print_cumulative_gc_stat) {
2259     heap_->tracer()->AddMarkingTime(base::OS::TimeCurrentMillis() - start_time);
2260   }
2261 }
2262
2263
2264 void MarkCompactCollector::AfterMarking() {
2265   // Prune the string table removing all strings only pointed to by the
2266   // string table.  Cannot use string_table() here because the string
2267   // table is marked.
2268   StringTable* string_table = heap()->string_table();
2269   InternalizedStringTableCleaner internalized_visitor(heap());
2270   string_table->IterateElements(&internalized_visitor);
2271   string_table->ElementsRemoved(internalized_visitor.PointersRemoved());
2272
2273   ExternalStringTableCleaner external_visitor(heap());
2274   heap()->external_string_table_.Iterate(&external_visitor);
2275   heap()->external_string_table_.CleanUp();
2276
2277   // Process the weak references.
2278   MarkCompactWeakObjectRetainer mark_compact_object_retainer;
2279   heap()->ProcessWeakReferences(&mark_compact_object_retainer);
2280
2281   // Remove object groups after marking phase.
2282   heap()->isolate()->global_handles()->RemoveObjectGroups();
2283   heap()->isolate()->global_handles()->RemoveImplicitRefGroups();
2284
2285   // Flush code from collected candidates.
2286   if (is_code_flushing_enabled()) {
2287     code_flusher_->ProcessCandidates();
2288     // If incremental marker does not support code flushing, we need to
2289     // disable it before incremental marking steps for next cycle.
2290     if (FLAG_flush_code && !FLAG_flush_code_incrementally) {
2291       EnableCodeFlushing(false);
2292     }
2293   }
2294
2295   if (FLAG_track_gc_object_stats) {
2296     heap()->CheckpointObjectStats();
2297   }
2298 }
2299
2300
2301 void MarkCompactCollector::ClearNonLiveReferences() {
2302   // Iterate over the map space, setting map transitions that go from
2303   // a marked map to an unmarked map to null transitions.  This action
2304   // is carried out only on maps of JSObjects and related subtypes.
2305   HeapObjectIterator map_iterator(heap()->map_space());
2306   for (HeapObject* obj = map_iterator.Next(); obj != NULL;
2307        obj = map_iterator.Next()) {
2308     Map* map = Map::cast(obj);
2309
2310     if (!map->CanTransition()) continue;
2311
2312     MarkBit map_mark = Marking::MarkBitFrom(map);
2313     ClearNonLivePrototypeTransitions(map);
2314     ClearNonLiveMapTransitions(map, map_mark);
2315
2316     if (map_mark.Get()) {
2317       ClearNonLiveDependentCode(map->dependent_code());
2318     } else {
2319       ClearDependentCode(map->dependent_code());
2320       map->set_dependent_code(DependentCode::cast(heap()->empty_fixed_array()));
2321     }
2322   }
2323
2324   // Iterate over property cell space, removing dependent code that is not
2325   // otherwise kept alive by strong references.
2326   HeapObjectIterator cell_iterator(heap_->property_cell_space());
2327   for (HeapObject* cell = cell_iterator.Next(); cell != NULL;
2328        cell = cell_iterator.Next()) {
2329     if (IsMarked(cell)) {
2330       ClearNonLiveDependentCode(PropertyCell::cast(cell)->dependent_code());
2331     }
2332   }
2333
2334   // Iterate over allocation sites, removing dependent code that is not
2335   // otherwise kept alive by strong references.
2336   Object* undefined = heap()->undefined_value();
2337   for (Object* site = heap()->allocation_sites_list(); site != undefined;
2338        site = AllocationSite::cast(site)->weak_next()) {
2339     if (IsMarked(site)) {
2340       ClearNonLiveDependentCode(AllocationSite::cast(site)->dependent_code());
2341     }
2342   }
2343
2344   if (heap_->weak_object_to_code_table()->IsHashTable()) {
2345     WeakHashTable* table =
2346         WeakHashTable::cast(heap_->weak_object_to_code_table());
2347     uint32_t capacity = table->Capacity();
2348     for (uint32_t i = 0; i < capacity; i++) {
2349       uint32_t key_index = table->EntryToIndex(i);
2350       Object* key = table->get(key_index);
2351       if (!table->IsKey(key)) continue;
2352       uint32_t value_index = table->EntryToValueIndex(i);
2353       Object* value = table->get(value_index);
2354       if (key->IsCell() && !IsMarked(key)) {
2355         Cell* cell = Cell::cast(key);
2356         Object* object = cell->value();
2357         if (IsMarked(object)) {
2358           MarkBit mark = Marking::MarkBitFrom(cell);
2359           SetMark(cell, mark);
2360           Object** value_slot = HeapObject::RawField(cell, Cell::kValueOffset);
2361           RecordSlot(value_slot, value_slot, *value_slot);
2362         }
2363       }
2364       if (IsMarked(key)) {
2365         if (!IsMarked(value)) {
2366           HeapObject* obj = HeapObject::cast(value);
2367           MarkBit mark = Marking::MarkBitFrom(obj);
2368           SetMark(obj, mark);
2369         }
2370         ClearNonLiveDependentCode(DependentCode::cast(value));
2371       } else {
2372         ClearDependentCode(DependentCode::cast(value));
2373         table->set(key_index, heap_->the_hole_value());
2374         table->set(value_index, heap_->the_hole_value());
2375         table->ElementRemoved();
2376       }
2377     }
2378   }
2379 }
2380
2381
2382 void MarkCompactCollector::ClearNonLivePrototypeTransitions(Map* map) {
2383   int number_of_transitions = map->NumberOfProtoTransitions();
2384   FixedArray* prototype_transitions = map->GetPrototypeTransitions();
2385
2386   int new_number_of_transitions = 0;
2387   const int header = Map::kProtoTransitionHeaderSize;
2388   const int proto_offset = header + Map::kProtoTransitionPrototypeOffset;
2389   const int map_offset = header + Map::kProtoTransitionMapOffset;
2390   const int step = Map::kProtoTransitionElementsPerEntry;
2391   for (int i = 0; i < number_of_transitions; i++) {
2392     Object* prototype = prototype_transitions->get(proto_offset + i * step);
2393     Object* cached_map = prototype_transitions->get(map_offset + i * step);
2394     if (IsMarked(prototype) && IsMarked(cached_map)) {
2395       DCHECK(!prototype->IsUndefined());
2396       int proto_index = proto_offset + new_number_of_transitions * step;
2397       int map_index = map_offset + new_number_of_transitions * step;
2398       if (new_number_of_transitions != i) {
2399         prototype_transitions->set(proto_index, prototype,
2400                                    UPDATE_WRITE_BARRIER);
2401         prototype_transitions->set(map_index, cached_map, SKIP_WRITE_BARRIER);
2402       }
2403       Object** slot = prototype_transitions->RawFieldOfElementAt(proto_index);
2404       RecordSlot(slot, slot, prototype);
2405       new_number_of_transitions++;
2406     }
2407   }
2408
2409   if (new_number_of_transitions != number_of_transitions) {
2410     map->SetNumberOfProtoTransitions(new_number_of_transitions);
2411   }
2412
2413   // Fill slots that became free with undefined value.
2414   for (int i = new_number_of_transitions * step;
2415        i < number_of_transitions * step; i++) {
2416     prototype_transitions->set_undefined(header + i);
2417   }
2418 }
2419
2420
2421 void MarkCompactCollector::ClearNonLiveMapTransitions(Map* map,
2422                                                       MarkBit map_mark) {
2423   Object* potential_parent = map->GetBackPointer();
2424   if (!potential_parent->IsMap()) return;
2425   Map* parent = Map::cast(potential_parent);
2426
2427   // Follow back pointer, check whether we are dealing with a map transition
2428   // from a live map to a dead path and in case clear transitions of parent.
2429   bool current_is_alive = map_mark.Get();
2430   bool parent_is_alive = Marking::MarkBitFrom(parent).Get();
2431   if (!current_is_alive && parent_is_alive) {
2432     ClearMapTransitions(parent);
2433   }
2434 }
2435
2436
2437 // Clear a possible back pointer in case the transition leads to a dead map.
2438 // Return true in case a back pointer has been cleared and false otherwise.
2439 bool MarkCompactCollector::ClearMapBackPointer(Map* target) {
2440   if (Marking::MarkBitFrom(target).Get()) return false;
2441   target->SetBackPointer(heap_->undefined_value(), SKIP_WRITE_BARRIER);
2442   return true;
2443 }
2444
2445
2446 void MarkCompactCollector::ClearMapTransitions(Map* map) {
2447   // If there are no transitions to be cleared, return.
2448   // TODO(verwaest) Should be an assert, otherwise back pointers are not
2449   // properly cleared.
2450   if (!map->HasTransitionArray()) return;
2451
2452   TransitionArray* t = map->transitions();
2453
2454   int transition_index = 0;
2455
2456   DescriptorArray* descriptors = map->instance_descriptors();
2457   bool descriptors_owner_died = false;
2458
2459   // Compact all live descriptors to the left.
2460   for (int i = 0; i < t->number_of_transitions(); ++i) {
2461     Map* target = t->GetTarget(i);
2462     if (ClearMapBackPointer(target)) {
2463       if (target->instance_descriptors() == descriptors) {
2464         descriptors_owner_died = true;
2465       }
2466     } else {
2467       if (i != transition_index) {
2468         Name* key = t->GetKey(i);
2469         t->SetKey(transition_index, key);
2470         Object** key_slot = t->GetKeySlot(transition_index);
2471         RecordSlot(key_slot, key_slot, key);
2472         // Target slots do not need to be recorded since maps are not compacted.
2473         t->SetTarget(transition_index, t->GetTarget(i));
2474       }
2475       transition_index++;
2476     }
2477   }
2478
2479   // If there are no transitions to be cleared, return.
2480   // TODO(verwaest) Should be an assert, otherwise back pointers are not
2481   // properly cleared.
2482   if (transition_index == t->number_of_transitions()) return;
2483
2484   int number_of_own_descriptors = map->NumberOfOwnDescriptors();
2485
2486   if (descriptors_owner_died) {
2487     if (number_of_own_descriptors > 0) {
2488       TrimDescriptorArray(map, descriptors, number_of_own_descriptors);
2489       DCHECK(descriptors->number_of_descriptors() == number_of_own_descriptors);
2490       map->set_owns_descriptors(true);
2491     } else {
2492       DCHECK(descriptors == heap_->empty_descriptor_array());
2493     }
2494   }
2495
2496   // Note that we never eliminate a transition array, though we might right-trim
2497   // such that number_of_transitions() == 0. If this assumption changes,
2498   // TransitionArray::Insert() will need to deal with the case that a transition
2499   // array disappeared during GC.
2500   int trim = t->number_of_transitions_storage() - transition_index;
2501   if (trim > 0) {
2502     heap_->RightTrimFixedArray<Heap::FROM_GC>(
2503         t, t->IsSimpleTransition() ? trim
2504                                    : trim * TransitionArray::kTransitionSize);
2505     t->SetNumberOfTransitions(transition_index);
2506   }
2507   DCHECK(map->HasTransitionArray());
2508 }
2509
2510
2511 void MarkCompactCollector::TrimDescriptorArray(Map* map,
2512                                                DescriptorArray* descriptors,
2513                                                int number_of_own_descriptors) {
2514   int number_of_descriptors = descriptors->number_of_descriptors_storage();
2515   int to_trim = number_of_descriptors - number_of_own_descriptors;
2516   if (to_trim == 0) return;
2517
2518   heap_->RightTrimFixedArray<Heap::FROM_GC>(
2519       descriptors, to_trim * DescriptorArray::kDescriptorSize);
2520   descriptors->SetNumberOfDescriptors(number_of_own_descriptors);
2521
2522   if (descriptors->HasEnumCache()) TrimEnumCache(map, descriptors);
2523   descriptors->Sort();
2524 }
2525
2526
2527 void MarkCompactCollector::TrimEnumCache(Map* map,
2528                                          DescriptorArray* descriptors) {
2529   int live_enum = map->EnumLength();
2530   if (live_enum == kInvalidEnumCacheSentinel) {
2531     live_enum = map->NumberOfDescribedProperties(OWN_DESCRIPTORS, DONT_ENUM);
2532   }
2533   if (live_enum == 0) return descriptors->ClearEnumCache();
2534
2535   FixedArray* enum_cache = descriptors->GetEnumCache();
2536
2537   int to_trim = enum_cache->length() - live_enum;
2538   if (to_trim <= 0) return;
2539   heap_->RightTrimFixedArray<Heap::FROM_GC>(descriptors->GetEnumCache(),
2540                                             to_trim);
2541
2542   if (!descriptors->HasEnumIndicesCache()) return;
2543   FixedArray* enum_indices_cache = descriptors->GetEnumIndicesCache();
2544   heap_->RightTrimFixedArray<Heap::FROM_GC>(enum_indices_cache, to_trim);
2545 }
2546
2547
2548 void MarkCompactCollector::ClearDependentCode(DependentCode* entries) {
2549   DisallowHeapAllocation no_allocation;
2550   DependentCode::GroupStartIndexes starts(entries);
2551   int number_of_entries = starts.number_of_entries();
2552   if (number_of_entries == 0) return;
2553   int g = DependentCode::kWeakCodeGroup;
2554   for (int i = starts.at(g); i < starts.at(g + 1); i++) {
2555     // If the entry is compilation info then the map must be alive,
2556     // and ClearDependentCode shouldn't be called.
2557     DCHECK(entries->is_code_at(i));
2558     Code* code = entries->code_at(i);
2559     if (IsMarked(code) && !code->marked_for_deoptimization()) {
2560       DependentCode::SetMarkedForDeoptimization(
2561           code, static_cast<DependentCode::DependencyGroup>(g));
2562       code->InvalidateEmbeddedObjects();
2563       have_code_to_deoptimize_ = true;
2564     }
2565   }
2566   for (int i = 0; i < number_of_entries; i++) {
2567     entries->clear_at(i);
2568   }
2569 }
2570
2571
2572 int MarkCompactCollector::ClearNonLiveDependentCodeInGroup(
2573     DependentCode* entries, int group, int start, int end, int new_start) {
2574   int survived = 0;
2575   for (int i = start; i < end; i++) {
2576     Object* obj = entries->object_at(i);
2577     DCHECK(obj->IsCode() || IsMarked(obj));
2578     if (IsMarked(obj) &&
2579         (!obj->IsCode() || !WillBeDeoptimized(Code::cast(obj)))) {
2580       if (new_start + survived != i) {
2581         entries->set_object_at(new_start + survived, obj);
2582       }
2583       Object** slot = entries->slot_at(new_start + survived);
2584       RecordSlot(slot, slot, obj);
2585       survived++;
2586     }
2587   }
2588   entries->set_number_of_entries(
2589       static_cast<DependentCode::DependencyGroup>(group), survived);
2590   return survived;
2591 }
2592
2593
2594 void MarkCompactCollector::ClearNonLiveDependentCode(DependentCode* entries) {
2595   DisallowHeapAllocation no_allocation;
2596   DependentCode::GroupStartIndexes starts(entries);
2597   int number_of_entries = starts.number_of_entries();
2598   if (number_of_entries == 0) return;
2599   int new_number_of_entries = 0;
2600   // Go through all groups, remove dead codes and compact.
2601   for (int g = 0; g < DependentCode::kGroupCount; g++) {
2602     int survived = ClearNonLiveDependentCodeInGroup(
2603         entries, g, starts.at(g), starts.at(g + 1), new_number_of_entries);
2604     new_number_of_entries += survived;
2605   }
2606   for (int i = new_number_of_entries; i < number_of_entries; i++) {
2607     entries->clear_at(i);
2608   }
2609 }
2610
2611
2612 void MarkCompactCollector::ProcessWeakCollections() {
2613   GCTracer::Scope gc_scope(heap()->tracer(),
2614                            GCTracer::Scope::MC_WEAKCOLLECTION_PROCESS);
2615   Object* weak_collection_obj = heap()->encountered_weak_collections();
2616   while (weak_collection_obj != Smi::FromInt(0)) {
2617     JSWeakCollection* weak_collection =
2618         reinterpret_cast<JSWeakCollection*>(weak_collection_obj);
2619     DCHECK(MarkCompactCollector::IsMarked(weak_collection));
2620     if (weak_collection->table()->IsHashTable()) {
2621       ObjectHashTable* table = ObjectHashTable::cast(weak_collection->table());
2622       Object** anchor = reinterpret_cast<Object**>(table->address());
2623       for (int i = 0; i < table->Capacity(); i++) {
2624         if (MarkCompactCollector::IsMarked(HeapObject::cast(table->KeyAt(i)))) {
2625           Object** key_slot =
2626               table->RawFieldOfElementAt(ObjectHashTable::EntryToIndex(i));
2627           RecordSlot(anchor, key_slot, *key_slot);
2628           Object** value_slot =
2629               table->RawFieldOfElementAt(ObjectHashTable::EntryToValueIndex(i));
2630           MarkCompactMarkingVisitor::MarkObjectByPointer(this, anchor,
2631                                                          value_slot);
2632         }
2633       }
2634     }
2635     weak_collection_obj = weak_collection->next();
2636   }
2637 }
2638
2639
2640 void MarkCompactCollector::ClearWeakCollections() {
2641   GCTracer::Scope gc_scope(heap()->tracer(),
2642                            GCTracer::Scope::MC_WEAKCOLLECTION_CLEAR);
2643   Object* weak_collection_obj = heap()->encountered_weak_collections();
2644   while (weak_collection_obj != Smi::FromInt(0)) {
2645     JSWeakCollection* weak_collection =
2646         reinterpret_cast<JSWeakCollection*>(weak_collection_obj);
2647     DCHECK(MarkCompactCollector::IsMarked(weak_collection));
2648     if (weak_collection->table()->IsHashTable()) {
2649       ObjectHashTable* table = ObjectHashTable::cast(weak_collection->table());
2650       for (int i = 0; i < table->Capacity(); i++) {
2651         HeapObject* key = HeapObject::cast(table->KeyAt(i));
2652         if (!MarkCompactCollector::IsMarked(key)) {
2653           table->RemoveEntry(i);
2654         }
2655       }
2656     }
2657     weak_collection_obj = weak_collection->next();
2658     weak_collection->set_next(heap()->undefined_value());
2659   }
2660   heap()->set_encountered_weak_collections(Smi::FromInt(0));
2661 }
2662
2663
2664 void MarkCompactCollector::AbortWeakCollections() {
2665   GCTracer::Scope gc_scope(heap()->tracer(),
2666                            GCTracer::Scope::MC_WEAKCOLLECTION_ABORT);
2667   Object* weak_collection_obj = heap()->encountered_weak_collections();
2668   while (weak_collection_obj != Smi::FromInt(0)) {
2669     JSWeakCollection* weak_collection =
2670         reinterpret_cast<JSWeakCollection*>(weak_collection_obj);
2671     weak_collection_obj = weak_collection->next();
2672     weak_collection->set_next(heap()->undefined_value());
2673   }
2674   heap()->set_encountered_weak_collections(Smi::FromInt(0));
2675 }
2676
2677
2678 void MarkCompactCollector::ProcessAndClearWeakCells() {
2679   HeapObject* undefined = heap()->undefined_value();
2680   Object* weak_cell_obj = heap()->encountered_weak_cells();
2681   while (weak_cell_obj != Smi::FromInt(0)) {
2682     WeakCell* weak_cell = reinterpret_cast<WeakCell*>(weak_cell_obj);
2683     // We do not insert cleared weak cells into the list, so the value
2684     // cannot be a Smi here.
2685     HeapObject* value = HeapObject::cast(weak_cell->value());
2686     if (!MarkCompactCollector::IsMarked(value)) {
2687       weak_cell->clear();
2688     } else {
2689       Object** slot = HeapObject::RawField(weak_cell, WeakCell::kValueOffset);
2690       heap()->mark_compact_collector()->RecordSlot(slot, slot, value);
2691     }
2692     weak_cell_obj = weak_cell->next();
2693     weak_cell->set_next(undefined, SKIP_WRITE_BARRIER);
2694   }
2695   heap()->set_encountered_weak_cells(Smi::FromInt(0));
2696 }
2697
2698
2699 void MarkCompactCollector::AbortWeakCells() {
2700   Object* undefined = heap()->undefined_value();
2701   Object* weak_cell_obj = heap()->encountered_weak_cells();
2702   while (weak_cell_obj != Smi::FromInt(0)) {
2703     WeakCell* weak_cell = reinterpret_cast<WeakCell*>(weak_cell_obj);
2704     weak_cell_obj = weak_cell->next();
2705     weak_cell->set_next(undefined, SKIP_WRITE_BARRIER);
2706   }
2707   heap()->set_encountered_weak_cells(Smi::FromInt(0));
2708 }
2709
2710
2711 void MarkCompactCollector::RecordMigratedSlot(Object* value, Address slot) {
2712   if (heap_->InNewSpace(value)) {
2713     heap_->store_buffer()->Mark(slot);
2714   } else if (value->IsHeapObject() && IsOnEvacuationCandidate(value)) {
2715     SlotsBuffer::AddTo(&slots_buffer_allocator_, &migration_slots_buffer_,
2716                        reinterpret_cast<Object**>(slot),
2717                        SlotsBuffer::IGNORE_OVERFLOW);
2718   }
2719 }
2720
2721
2722 // We scavenge new space simultaneously with sweeping. This is done in two
2723 // passes.
2724 //
2725 // The first pass migrates all alive objects from one semispace to another or
2726 // promotes them to old space.  Forwarding address is written directly into
2727 // first word of object without any encoding.  If object is dead we write
2728 // NULL as a forwarding address.
2729 //
2730 // The second pass updates pointers to new space in all spaces.  It is possible
2731 // to encounter pointers to dead new space objects during traversal of pointers
2732 // to new space.  We should clear them to avoid encountering them during next
2733 // pointer iteration.  This is an issue if the store buffer overflows and we
2734 // have to scan the entire old space, including dead objects, looking for
2735 // pointers to new space.
2736 void MarkCompactCollector::MigrateObject(HeapObject* dst, HeapObject* src,
2737                                          int size, AllocationSpace dest) {
2738   Address dst_addr = dst->address();
2739   Address src_addr = src->address();
2740   DCHECK(heap()->AllowedToBeMigrated(src, dest));
2741   DCHECK(dest != LO_SPACE && size <= Page::kMaxRegularHeapObjectSize);
2742   if (dest == OLD_POINTER_SPACE) {
2743     Address src_slot = src_addr;
2744     Address dst_slot = dst_addr;
2745     DCHECK(IsAligned(size, kPointerSize));
2746
2747     bool may_contain_raw_values = src->MayContainRawValues();
2748 #if V8_DOUBLE_FIELDS_UNBOXING
2749     LayoutDescriptorHelper helper(src->map());
2750     bool has_only_tagged_fields = helper.all_fields_tagged();
2751 #endif
2752     for (int remaining = size / kPointerSize; remaining > 0; remaining--) {
2753       Object* value = Memory::Object_at(src_slot);
2754
2755       Memory::Object_at(dst_slot) = value;
2756
2757 #if V8_DOUBLE_FIELDS_UNBOXING
2758       if (!may_contain_raw_values &&
2759           (has_only_tagged_fields ||
2760            helper.IsTagged(static_cast<int>(src_slot - src_addr))))
2761 #else
2762       if (!may_contain_raw_values)
2763 #endif
2764       {
2765         RecordMigratedSlot(value, dst_slot);
2766       }
2767
2768       src_slot += kPointerSize;
2769       dst_slot += kPointerSize;
2770     }
2771
2772     if (compacting_ && dst->IsJSFunction()) {
2773       Address code_entry_slot = dst_addr + JSFunction::kCodeEntryOffset;
2774       Address code_entry = Memory::Address_at(code_entry_slot);
2775
2776       if (Page::FromAddress(code_entry)->IsEvacuationCandidate()) {
2777         SlotsBuffer::AddTo(&slots_buffer_allocator_, &migration_slots_buffer_,
2778                            SlotsBuffer::CODE_ENTRY_SLOT, code_entry_slot,
2779                            SlotsBuffer::IGNORE_OVERFLOW);
2780       }
2781     } else if (dst->IsConstantPoolArray()) {
2782       // We special case ConstantPoolArrays since they could contain integers
2783       // value entries which look like tagged pointers.
2784       // TODO(mstarzinger): restructure this code to avoid this special-casing.
2785       ConstantPoolArray* array = ConstantPoolArray::cast(dst);
2786       ConstantPoolArray::Iterator code_iter(array, ConstantPoolArray::CODE_PTR);
2787       while (!code_iter.is_finished()) {
2788         Address code_entry_slot =
2789             dst_addr + array->OffsetOfElementAt(code_iter.next_index());
2790         Address code_entry = Memory::Address_at(code_entry_slot);
2791
2792         if (Page::FromAddress(code_entry)->IsEvacuationCandidate()) {
2793           SlotsBuffer::AddTo(&slots_buffer_allocator_, &migration_slots_buffer_,
2794                              SlotsBuffer::CODE_ENTRY_SLOT, code_entry_slot,
2795                              SlotsBuffer::IGNORE_OVERFLOW);
2796         }
2797       }
2798       ConstantPoolArray::Iterator heap_iter(array, ConstantPoolArray::HEAP_PTR);
2799       while (!heap_iter.is_finished()) {
2800         Address heap_slot =
2801             dst_addr + array->OffsetOfElementAt(heap_iter.next_index());
2802         Object* value = Memory::Object_at(heap_slot);
2803         RecordMigratedSlot(value, heap_slot);
2804       }
2805     }
2806   } else if (dest == CODE_SPACE) {
2807     PROFILE(isolate(), CodeMoveEvent(src_addr, dst_addr));
2808     heap()->MoveBlock(dst_addr, src_addr, size);
2809     SlotsBuffer::AddTo(&slots_buffer_allocator_, &migration_slots_buffer_,
2810                        SlotsBuffer::RELOCATED_CODE_OBJECT, dst_addr,
2811                        SlotsBuffer::IGNORE_OVERFLOW);
2812     Code::cast(dst)->Relocate(dst_addr - src_addr);
2813   } else {
2814     DCHECK(dest == OLD_DATA_SPACE || dest == NEW_SPACE);
2815     heap()->MoveBlock(dst_addr, src_addr, size);
2816   }
2817   heap()->OnMoveEvent(dst, src, size);
2818   Memory::Address_at(src_addr) = dst_addr;
2819 }
2820
2821
2822 // Visitor for updating pointers from live objects in old spaces to new space.
2823 // It does not expect to encounter pointers to dead objects.
2824 class PointersUpdatingVisitor : public ObjectVisitor {
2825  public:
2826   explicit PointersUpdatingVisitor(Heap* heap) : heap_(heap) {}
2827
2828   void VisitPointer(Object** p) { UpdatePointer(p); }
2829
2830   void VisitPointers(Object** start, Object** end) {
2831     for (Object** p = start; p < end; p++) UpdatePointer(p);
2832   }
2833
2834   void VisitEmbeddedPointer(RelocInfo* rinfo) {
2835     DCHECK(rinfo->rmode() == RelocInfo::EMBEDDED_OBJECT);
2836     Object* target = rinfo->target_object();
2837     Object* old_target = target;
2838     VisitPointer(&target);
2839     // Avoid unnecessary changes that might unnecessary flush the instruction
2840     // cache.
2841     if (target != old_target) {
2842       rinfo->set_target_object(target);
2843     }
2844   }
2845
2846   void VisitCodeTarget(RelocInfo* rinfo) {
2847     DCHECK(RelocInfo::IsCodeTarget(rinfo->rmode()));
2848     Object* target = Code::GetCodeFromTargetAddress(rinfo->target_address());
2849     Object* old_target = target;
2850     VisitPointer(&target);
2851     if (target != old_target) {
2852       rinfo->set_target_address(Code::cast(target)->instruction_start());
2853     }
2854   }
2855
2856   void VisitCodeAgeSequence(RelocInfo* rinfo) {
2857     DCHECK(RelocInfo::IsCodeAgeSequence(rinfo->rmode()));
2858     Object* stub = rinfo->code_age_stub();
2859     DCHECK(stub != NULL);
2860     VisitPointer(&stub);
2861     if (stub != rinfo->code_age_stub()) {
2862       rinfo->set_code_age_stub(Code::cast(stub));
2863     }
2864   }
2865
2866   void VisitDebugTarget(RelocInfo* rinfo) {
2867     DCHECK((RelocInfo::IsJSReturn(rinfo->rmode()) &&
2868             rinfo->IsPatchedReturnSequence()) ||
2869            (RelocInfo::IsDebugBreakSlot(rinfo->rmode()) &&
2870             rinfo->IsPatchedDebugBreakSlotSequence()));
2871     Object* target = Code::GetCodeFromTargetAddress(rinfo->call_address());
2872     VisitPointer(&target);
2873     rinfo->set_call_address(Code::cast(target)->instruction_start());
2874   }
2875
2876   static inline void UpdateSlot(Heap* heap, Object** slot) {
2877     Object* obj = reinterpret_cast<Object*>(
2878         base::NoBarrier_Load(reinterpret_cast<base::AtomicWord*>(slot)));
2879
2880     if (!obj->IsHeapObject()) return;
2881
2882     HeapObject* heap_obj = HeapObject::cast(obj);
2883
2884     MapWord map_word = heap_obj->map_word();
2885     if (map_word.IsForwardingAddress()) {
2886       DCHECK(heap->InFromSpace(heap_obj) ||
2887              MarkCompactCollector::IsOnEvacuationCandidate(heap_obj));
2888       HeapObject* target = map_word.ToForwardingAddress();
2889       base::NoBarrier_CompareAndSwap(
2890           reinterpret_cast<base::AtomicWord*>(slot),
2891           reinterpret_cast<base::AtomicWord>(obj),
2892           reinterpret_cast<base::AtomicWord>(target));
2893       DCHECK(!heap->InFromSpace(target) &&
2894              !MarkCompactCollector::IsOnEvacuationCandidate(target));
2895     }
2896   }
2897
2898  private:
2899   inline void UpdatePointer(Object** p) { UpdateSlot(heap_, p); }
2900
2901   Heap* heap_;
2902 };
2903
2904
2905 static void UpdatePointer(HeapObject** address, HeapObject* object) {
2906   Address new_addr = Memory::Address_at(object->address());
2907
2908   // The new space sweep will overwrite the map word of dead objects
2909   // with NULL. In this case we do not need to transfer this entry to
2910   // the store buffer which we are rebuilding.
2911   // We perform the pointer update with a no barrier compare-and-swap. The
2912   // compare and swap may fail in the case where the pointer update tries to
2913   // update garbage memory which was concurrently accessed by the sweeper.
2914   if (new_addr != NULL) {
2915     base::NoBarrier_CompareAndSwap(
2916         reinterpret_cast<base::AtomicWord*>(address),
2917         reinterpret_cast<base::AtomicWord>(object),
2918         reinterpret_cast<base::AtomicWord>(HeapObject::FromAddress(new_addr)));
2919   }
2920 }
2921
2922
2923 static String* UpdateReferenceInExternalStringTableEntry(Heap* heap,
2924                                                          Object** p) {
2925   MapWord map_word = HeapObject::cast(*p)->map_word();
2926
2927   if (map_word.IsForwardingAddress()) {
2928     return String::cast(map_word.ToForwardingAddress());
2929   }
2930
2931   return String::cast(*p);
2932 }
2933
2934
2935 bool MarkCompactCollector::TryPromoteObject(HeapObject* object,
2936                                             int object_size) {
2937   DCHECK(object_size <= Page::kMaxRegularHeapObjectSize);
2938
2939   OldSpace* target_space = heap()->TargetSpace(object);
2940
2941   DCHECK(target_space == heap()->old_pointer_space() ||
2942          target_space == heap()->old_data_space());
2943   HeapObject* target;
2944   AllocationResult allocation = target_space->AllocateRaw(object_size);
2945   if (allocation.To(&target)) {
2946     MigrateObject(target, object, object_size, target_space->identity());
2947     heap()->IncrementPromotedObjectsSize(object_size);
2948     return true;
2949   }
2950
2951   return false;
2952 }
2953
2954
2955 void MarkCompactCollector::EvacuateNewSpace() {
2956   // There are soft limits in the allocation code, designed trigger a mark
2957   // sweep collection by failing allocations.  But since we are already in
2958   // a mark-sweep allocation, there is no sense in trying to trigger one.
2959   AlwaysAllocateScope scope(isolate());
2960
2961   NewSpace* new_space = heap()->new_space();
2962
2963   // Store allocation range before flipping semispaces.
2964   Address from_bottom = new_space->bottom();
2965   Address from_top = new_space->top();
2966
2967   // Flip the semispaces.  After flipping, to space is empty, from space has
2968   // live objects.
2969   new_space->Flip();
2970   new_space->ResetAllocationInfo();
2971
2972   int survivors_size = 0;
2973
2974   // First pass: traverse all objects in inactive semispace, remove marks,
2975   // migrate live objects and write forwarding addresses.  This stage puts
2976   // new entries in the store buffer and may cause some pages to be marked
2977   // scan-on-scavenge.
2978   NewSpacePageIterator it(from_bottom, from_top);
2979   while (it.has_next()) {
2980     NewSpacePage* p = it.next();
2981     survivors_size += DiscoverAndEvacuateBlackObjectsOnPage(new_space, p);
2982   }
2983
2984   heap_->IncrementYoungSurvivorsCounter(survivors_size);
2985   new_space->set_age_mark(new_space->top());
2986 }
2987
2988
2989 void MarkCompactCollector::EvacuateLiveObjectsFromPage(Page* p) {
2990   AlwaysAllocateScope always_allocate(isolate());
2991   PagedSpace* space = static_cast<PagedSpace*>(p->owner());
2992   DCHECK(p->IsEvacuationCandidate() && !p->WasSwept());
2993   p->SetWasSwept();
2994
2995   int offsets[16];
2996
2997   for (MarkBitCellIterator it(p); !it.Done(); it.Advance()) {
2998     Address cell_base = it.CurrentCellBase();
2999     MarkBit::CellType* cell = it.CurrentCell();
3000
3001     if (*cell == 0) continue;
3002
3003     int live_objects = MarkWordToObjectStarts(*cell, offsets);
3004     for (int i = 0; i < live_objects; i++) {
3005       Address object_addr = cell_base + offsets[i] * kPointerSize;
3006       HeapObject* object = HeapObject::FromAddress(object_addr);
3007       DCHECK(Marking::IsBlack(Marking::MarkBitFrom(object)));
3008
3009       int size = object->Size();
3010
3011       HeapObject* target_object;
3012       AllocationResult allocation = space->AllocateRaw(size);
3013       if (!allocation.To(&target_object)) {
3014         // If allocation failed, use emergency memory and re-try allocation.
3015         CHECK(space->HasEmergencyMemory());
3016         space->UseEmergencyMemory();
3017         allocation = space->AllocateRaw(size);
3018       }
3019       if (!allocation.To(&target_object)) {
3020         // OS refused to give us memory.
3021         V8::FatalProcessOutOfMemory("Evacuation");
3022         return;
3023       }
3024
3025       MigrateObject(target_object, object, size, space->identity());
3026       DCHECK(object->map_word().IsForwardingAddress());
3027     }
3028
3029     // Clear marking bits for current cell.
3030     *cell = 0;
3031   }
3032   p->ResetLiveBytes();
3033 }
3034
3035
3036 void MarkCompactCollector::EvacuatePages() {
3037   int npages = evacuation_candidates_.length();
3038   for (int i = 0; i < npages; i++) {
3039     Page* p = evacuation_candidates_[i];
3040     DCHECK(p->IsEvacuationCandidate() ||
3041            p->IsFlagSet(Page::RESCAN_ON_EVACUATION));
3042     DCHECK(static_cast<int>(p->parallel_sweeping()) ==
3043            MemoryChunk::SWEEPING_DONE);
3044     PagedSpace* space = static_cast<PagedSpace*>(p->owner());
3045     // Allocate emergency memory for the case when compaction fails due to out
3046     // of memory.
3047     if (!space->HasEmergencyMemory()) {
3048       space->CreateEmergencyMemory();
3049     }
3050     if (p->IsEvacuationCandidate()) {
3051       // During compaction we might have to request a new page. Check that we
3052       // have an emergency page and the space still has room for that.
3053       if (space->HasEmergencyMemory() && space->CanExpand()) {
3054         EvacuateLiveObjectsFromPage(p);
3055       } else {
3056         // Without room for expansion evacuation is not guaranteed to succeed.
3057         // Pessimistically abandon unevacuated pages.
3058         for (int j = i; j < npages; j++) {
3059           Page* page = evacuation_candidates_[j];
3060           slots_buffer_allocator_.DeallocateChain(page->slots_buffer_address());
3061           page->ClearEvacuationCandidate();
3062           page->SetFlag(Page::RESCAN_ON_EVACUATION);
3063         }
3064         break;
3065       }
3066     }
3067   }
3068   if (npages > 0) {
3069     // Release emergency memory.
3070     PagedSpaces spaces(heap());
3071     for (PagedSpace* space = spaces.next(); space != NULL;
3072          space = spaces.next()) {
3073       if (space->HasEmergencyMemory()) {
3074         space->FreeEmergencyMemory();
3075       }
3076     }
3077   }
3078 }
3079
3080
3081 class EvacuationWeakObjectRetainer : public WeakObjectRetainer {
3082  public:
3083   virtual Object* RetainAs(Object* object) {
3084     if (object->IsHeapObject()) {
3085       HeapObject* heap_object = HeapObject::cast(object);
3086       MapWord map_word = heap_object->map_word();
3087       if (map_word.IsForwardingAddress()) {
3088         return map_word.ToForwardingAddress();
3089       }
3090     }
3091     return object;
3092   }
3093 };
3094
3095
3096 static inline void UpdateSlot(Isolate* isolate, ObjectVisitor* v,
3097                               SlotsBuffer::SlotType slot_type, Address addr) {
3098   switch (slot_type) {
3099     case SlotsBuffer::CODE_TARGET_SLOT: {
3100       RelocInfo rinfo(addr, RelocInfo::CODE_TARGET, 0, NULL);
3101       rinfo.Visit(isolate, v);
3102       break;
3103     }
3104     case SlotsBuffer::CODE_ENTRY_SLOT: {
3105       v->VisitCodeEntry(addr);
3106       break;
3107     }
3108     case SlotsBuffer::RELOCATED_CODE_OBJECT: {
3109       HeapObject* obj = HeapObject::FromAddress(addr);
3110       Code::cast(obj)->CodeIterateBody(v);
3111       break;
3112     }
3113     case SlotsBuffer::DEBUG_TARGET_SLOT: {
3114       RelocInfo rinfo(addr, RelocInfo::DEBUG_BREAK_SLOT, 0, NULL);
3115       if (rinfo.IsPatchedDebugBreakSlotSequence()) rinfo.Visit(isolate, v);
3116       break;
3117     }
3118     case SlotsBuffer::JS_RETURN_SLOT: {
3119       RelocInfo rinfo(addr, RelocInfo::JS_RETURN, 0, NULL);
3120       if (rinfo.IsPatchedReturnSequence()) rinfo.Visit(isolate, v);
3121       break;
3122     }
3123     case SlotsBuffer::EMBEDDED_OBJECT_SLOT: {
3124       RelocInfo rinfo(addr, RelocInfo::EMBEDDED_OBJECT, 0, NULL);
3125       rinfo.Visit(isolate, v);
3126       break;
3127     }
3128     default:
3129       UNREACHABLE();
3130       break;
3131   }
3132 }
3133
3134
3135 enum SweepingMode { SWEEP_ONLY, SWEEP_AND_VISIT_LIVE_OBJECTS };
3136
3137
3138 enum SkipListRebuildingMode { REBUILD_SKIP_LIST, IGNORE_SKIP_LIST };
3139
3140
3141 enum FreeSpaceTreatmentMode { IGNORE_FREE_SPACE, ZAP_FREE_SPACE };
3142
3143
3144 template <MarkCompactCollector::SweepingParallelism mode>
3145 static intptr_t Free(PagedSpace* space, FreeList* free_list, Address start,
3146                      int size) {
3147   if (mode == MarkCompactCollector::SWEEP_ON_MAIN_THREAD) {
3148     DCHECK(free_list == NULL);
3149     return space->Free(start, size);
3150   } else {
3151     // TODO(hpayer): account for wasted bytes in concurrent sweeping too.
3152     return size - free_list->Free(start, size);
3153   }
3154 }
3155
3156
3157 // Sweeps a page. After sweeping the page can be iterated.
3158 // Slots in live objects pointing into evacuation candidates are updated
3159 // if requested.
3160 // Returns the size of the biggest continuous freed memory chunk in bytes.
3161 template <SweepingMode sweeping_mode,
3162           MarkCompactCollector::SweepingParallelism parallelism,
3163           SkipListRebuildingMode skip_list_mode,
3164           FreeSpaceTreatmentMode free_space_mode>
3165 static int Sweep(PagedSpace* space, FreeList* free_list, Page* p,
3166                  ObjectVisitor* v) {
3167   DCHECK(!p->IsEvacuationCandidate() && !p->WasSwept());
3168   DCHECK_EQ(skip_list_mode == REBUILD_SKIP_LIST,
3169             space->identity() == CODE_SPACE);
3170   DCHECK((p->skip_list() == NULL) || (skip_list_mode == REBUILD_SKIP_LIST));
3171   DCHECK(parallelism == MarkCompactCollector::SWEEP_ON_MAIN_THREAD ||
3172          sweeping_mode == SWEEP_ONLY);
3173
3174   Address free_start = p->area_start();
3175   DCHECK(reinterpret_cast<intptr_t>(free_start) % (32 * kPointerSize) == 0);
3176   int offsets[16];
3177
3178   SkipList* skip_list = p->skip_list();
3179   int curr_region = -1;
3180   if ((skip_list_mode == REBUILD_SKIP_LIST) && skip_list) {
3181     skip_list->Clear();
3182   }
3183
3184   intptr_t freed_bytes = 0;
3185   intptr_t max_freed_bytes = 0;
3186
3187   for (MarkBitCellIterator it(p); !it.Done(); it.Advance()) {
3188     Address cell_base = it.CurrentCellBase();
3189     MarkBit::CellType* cell = it.CurrentCell();
3190     int live_objects = MarkWordToObjectStarts(*cell, offsets);
3191     int live_index = 0;
3192     for (; live_objects != 0; live_objects--) {
3193       Address free_end = cell_base + offsets[live_index++] * kPointerSize;
3194       if (free_end != free_start) {
3195         int size = static_cast<int>(free_end - free_start);
3196         if (free_space_mode == ZAP_FREE_SPACE) {
3197           memset(free_start, 0xcc, size);
3198         }
3199         freed_bytes = Free<parallelism>(space, free_list, free_start, size);
3200         max_freed_bytes = Max(freed_bytes, max_freed_bytes);
3201 #ifdef ENABLE_GDB_JIT_INTERFACE
3202         if (FLAG_gdbjit && space->identity() == CODE_SPACE) {
3203           GDBJITInterface::RemoveCodeRange(free_start, free_end);
3204         }
3205 #endif
3206       }
3207       HeapObject* live_object = HeapObject::FromAddress(free_end);
3208       DCHECK(Marking::IsBlack(Marking::MarkBitFrom(live_object)));
3209       Map* map = live_object->synchronized_map();
3210       int size = live_object->SizeFromMap(map);
3211       if (sweeping_mode == SWEEP_AND_VISIT_LIVE_OBJECTS) {
3212         live_object->IterateBody(map->instance_type(), size, v);
3213       }
3214       if ((skip_list_mode == REBUILD_SKIP_LIST) && skip_list != NULL) {
3215         int new_region_start = SkipList::RegionNumber(free_end);
3216         int new_region_end =
3217             SkipList::RegionNumber(free_end + size - kPointerSize);
3218         if (new_region_start != curr_region || new_region_end != curr_region) {
3219           skip_list->AddObject(free_end, size);
3220           curr_region = new_region_end;
3221         }
3222       }
3223       free_start = free_end + size;
3224     }
3225     // Clear marking bits for current cell.
3226     *cell = 0;
3227   }
3228   if (free_start != p->area_end()) {
3229     int size = static_cast<int>(p->area_end() - free_start);
3230     if (free_space_mode == ZAP_FREE_SPACE) {
3231       memset(free_start, 0xcc, size);
3232     }
3233     freed_bytes = Free<parallelism>(space, free_list, free_start, size);
3234     max_freed_bytes = Max(freed_bytes, max_freed_bytes);
3235 #ifdef ENABLE_GDB_JIT_INTERFACE
3236     if (FLAG_gdbjit && space->identity() == CODE_SPACE) {
3237       GDBJITInterface::RemoveCodeRange(free_start, p->area_end());
3238     }
3239 #endif
3240   }
3241   p->ResetLiveBytes();
3242
3243   if (parallelism == MarkCompactCollector::SWEEP_IN_PARALLEL) {
3244     // When concurrent sweeping is active, the page will be marked after
3245     // sweeping by the main thread.
3246     p->set_parallel_sweeping(MemoryChunk::SWEEPING_FINALIZE);
3247   } else {
3248     p->SetWasSwept();
3249   }
3250   return FreeList::GuaranteedAllocatable(static_cast<int>(max_freed_bytes));
3251 }
3252
3253
3254 static bool SetMarkBitsUnderInvalidatedCode(Code* code, bool value) {
3255   Page* p = Page::FromAddress(code->address());
3256
3257   if (p->IsEvacuationCandidate() || p->IsFlagSet(Page::RESCAN_ON_EVACUATION)) {
3258     return false;
3259   }
3260
3261   Address code_start = code->address();
3262   Address code_end = code_start + code->Size();
3263
3264   uint32_t start_index = MemoryChunk::FastAddressToMarkbitIndex(code_start);
3265   uint32_t end_index =
3266       MemoryChunk::FastAddressToMarkbitIndex(code_end - kPointerSize);
3267
3268   Bitmap* b = p->markbits();
3269
3270   MarkBit start_mark_bit = b->MarkBitFromIndex(start_index);
3271   MarkBit end_mark_bit = b->MarkBitFromIndex(end_index);
3272
3273   MarkBit::CellType* start_cell = start_mark_bit.cell();
3274   MarkBit::CellType* end_cell = end_mark_bit.cell();
3275
3276   if (value) {
3277     MarkBit::CellType start_mask = ~(start_mark_bit.mask() - 1);
3278     MarkBit::CellType end_mask = (end_mark_bit.mask() << 1) - 1;
3279
3280     if (start_cell == end_cell) {
3281       *start_cell |= start_mask & end_mask;
3282     } else {
3283       *start_cell |= start_mask;
3284       for (MarkBit::CellType* cell = start_cell + 1; cell < end_cell; cell++) {
3285         *cell = ~0;
3286       }
3287       *end_cell |= end_mask;
3288     }
3289   } else {
3290     for (MarkBit::CellType* cell = start_cell; cell <= end_cell; cell++) {
3291       *cell = 0;
3292     }
3293   }
3294
3295   return true;
3296 }
3297
3298
3299 static bool IsOnInvalidatedCodeObject(Address addr) {
3300   // We did not record any slots in large objects thus
3301   // we can safely go to the page from the slot address.
3302   Page* p = Page::FromAddress(addr);
3303
3304   // First check owner's identity because old pointer and old data spaces
3305   // are swept lazily and might still have non-zero mark-bits on some
3306   // pages.
3307   if (p->owner()->identity() != CODE_SPACE) return false;
3308
3309   // In code space only bits on evacuation candidates (but we don't record
3310   // any slots on them) and under invalidated code objects are non-zero.
3311   MarkBit mark_bit =
3312       p->markbits()->MarkBitFromIndex(Page::FastAddressToMarkbitIndex(addr));
3313
3314   return mark_bit.Get();
3315 }
3316
3317
3318 void MarkCompactCollector::InvalidateCode(Code* code) {
3319   if (heap_->incremental_marking()->IsCompacting() &&
3320       !ShouldSkipEvacuationSlotRecording(code)) {
3321     DCHECK(compacting_);
3322
3323     // If the object is white than no slots were recorded on it yet.
3324     MarkBit mark_bit = Marking::MarkBitFrom(code);
3325     if (Marking::IsWhite(mark_bit)) return;
3326
3327     invalidated_code_.Add(code);
3328   }
3329 }
3330
3331
3332 // Return true if the given code is deoptimized or will be deoptimized.
3333 bool MarkCompactCollector::WillBeDeoptimized(Code* code) {
3334   return code->is_optimized_code() && code->marked_for_deoptimization();
3335 }
3336
3337
3338 bool MarkCompactCollector::MarkInvalidatedCode() {
3339   bool code_marked = false;
3340
3341   int length = invalidated_code_.length();
3342   for (int i = 0; i < length; i++) {
3343     Code* code = invalidated_code_[i];
3344
3345     if (SetMarkBitsUnderInvalidatedCode(code, true)) {
3346       code_marked = true;
3347     }
3348   }
3349
3350   return code_marked;
3351 }
3352
3353
3354 void MarkCompactCollector::RemoveDeadInvalidatedCode() {
3355   int length = invalidated_code_.length();
3356   for (int i = 0; i < length; i++) {
3357     if (!IsMarked(invalidated_code_[i])) invalidated_code_[i] = NULL;
3358   }
3359 }
3360
3361
3362 void MarkCompactCollector::ProcessInvalidatedCode(ObjectVisitor* visitor) {
3363   int length = invalidated_code_.length();
3364   for (int i = 0; i < length; i++) {
3365     Code* code = invalidated_code_[i];
3366     if (code != NULL) {
3367       code->Iterate(visitor);
3368       SetMarkBitsUnderInvalidatedCode(code, false);
3369     }
3370   }
3371   invalidated_code_.Rewind(0);
3372 }
3373
3374
3375 void MarkCompactCollector::EvacuateNewSpaceAndCandidates() {
3376   Heap::RelocationLock relocation_lock(heap());
3377
3378   bool code_slots_filtering_required;
3379   {
3380     GCTracer::Scope gc_scope(heap()->tracer(),
3381                              GCTracer::Scope::MC_SWEEP_NEWSPACE);
3382     code_slots_filtering_required = MarkInvalidatedCode();
3383     EvacuateNewSpace();
3384   }
3385
3386   {
3387     GCTracer::Scope gc_scope(heap()->tracer(),
3388                              GCTracer::Scope::MC_EVACUATE_PAGES);
3389     EvacuationScope evacuation_scope(this);
3390     EvacuatePages();
3391   }
3392
3393   // Second pass: find pointers to new space and update them.
3394   PointersUpdatingVisitor updating_visitor(heap());
3395
3396   {
3397     GCTracer::Scope gc_scope(heap()->tracer(),
3398                              GCTracer::Scope::MC_UPDATE_NEW_TO_NEW_POINTERS);
3399     // Update pointers in to space.
3400     SemiSpaceIterator to_it(heap()->new_space()->bottom(),
3401                             heap()->new_space()->top());
3402     for (HeapObject* object = to_it.Next(); object != NULL;
3403          object = to_it.Next()) {
3404       Map* map = object->map();
3405       object->IterateBody(map->instance_type(), object->SizeFromMap(map),
3406                           &updating_visitor);
3407     }
3408   }
3409
3410   {
3411     GCTracer::Scope gc_scope(heap()->tracer(),
3412                              GCTracer::Scope::MC_UPDATE_ROOT_TO_NEW_POINTERS);
3413     // Update roots.
3414     heap_->IterateRoots(&updating_visitor, VISIT_ALL_IN_SWEEP_NEWSPACE);
3415   }
3416
3417   {
3418     GCTracer::Scope gc_scope(heap()->tracer(),
3419                              GCTracer::Scope::MC_UPDATE_OLD_TO_NEW_POINTERS);
3420     StoreBufferRebuildScope scope(heap_, heap_->store_buffer(),
3421                                   &Heap::ScavengeStoreBufferCallback);
3422     heap_->store_buffer()->IteratePointersToNewSpaceAndClearMaps(
3423         &UpdatePointer);
3424   }
3425
3426   {
3427     GCTracer::Scope gc_scope(heap()->tracer(),
3428                              GCTracer::Scope::MC_UPDATE_POINTERS_TO_EVACUATED);
3429     SlotsBuffer::UpdateSlotsRecordedIn(heap_, migration_slots_buffer_,
3430                                        code_slots_filtering_required);
3431     if (FLAG_trace_fragmentation) {
3432       PrintF("  migration slots buffer: %d\n",
3433              SlotsBuffer::SizeOfChain(migration_slots_buffer_));
3434     }
3435
3436     if (compacting_ && was_marked_incrementally_) {
3437       // It's difficult to filter out slots recorded for large objects.
3438       LargeObjectIterator it(heap_->lo_space());
3439       for (HeapObject* obj = it.Next(); obj != NULL; obj = it.Next()) {
3440         // LargeObjectSpace is not swept yet thus we have to skip
3441         // dead objects explicitly.
3442         if (!IsMarked(obj)) continue;
3443
3444         Page* p = Page::FromAddress(obj->address());
3445         if (p->IsFlagSet(Page::RESCAN_ON_EVACUATION)) {
3446           obj->Iterate(&updating_visitor);
3447           p->ClearFlag(Page::RESCAN_ON_EVACUATION);
3448         }
3449       }
3450     }
3451   }
3452
3453   int npages = evacuation_candidates_.length();
3454   {
3455     GCTracer::Scope gc_scope(
3456         heap()->tracer(),
3457         GCTracer::Scope::MC_UPDATE_POINTERS_BETWEEN_EVACUATED);
3458     for (int i = 0; i < npages; i++) {
3459       Page* p = evacuation_candidates_[i];
3460       DCHECK(p->IsEvacuationCandidate() ||
3461              p->IsFlagSet(Page::RESCAN_ON_EVACUATION));
3462
3463       if (p->IsEvacuationCandidate()) {
3464         SlotsBuffer::UpdateSlotsRecordedIn(heap_, p->slots_buffer(),
3465                                            code_slots_filtering_required);
3466         if (FLAG_trace_fragmentation) {
3467           PrintF("  page %p slots buffer: %d\n", reinterpret_cast<void*>(p),
3468                  SlotsBuffer::SizeOfChain(p->slots_buffer()));
3469         }
3470
3471         // Important: skip list should be cleared only after roots were updated
3472         // because root iteration traverses the stack and might have to find
3473         // code objects from non-updated pc pointing into evacuation candidate.
3474         SkipList* list = p->skip_list();
3475         if (list != NULL) list->Clear();
3476       } else {
3477         if (FLAG_gc_verbose) {
3478           PrintF("Sweeping 0x%" V8PRIxPTR " during evacuation.\n",
3479                  reinterpret_cast<intptr_t>(p));
3480         }
3481         PagedSpace* space = static_cast<PagedSpace*>(p->owner());
3482         p->ClearFlag(MemoryChunk::RESCAN_ON_EVACUATION);
3483
3484         switch (space->identity()) {
3485           case OLD_DATA_SPACE:
3486             Sweep<SWEEP_AND_VISIT_LIVE_OBJECTS, SWEEP_ON_MAIN_THREAD,
3487                   IGNORE_SKIP_LIST, IGNORE_FREE_SPACE>(space, NULL, p,
3488                                                        &updating_visitor);
3489             break;
3490           case OLD_POINTER_SPACE:
3491             Sweep<SWEEP_AND_VISIT_LIVE_OBJECTS, SWEEP_ON_MAIN_THREAD,
3492                   IGNORE_SKIP_LIST, IGNORE_FREE_SPACE>(space, NULL, p,
3493                                                        &updating_visitor);
3494             break;
3495           case CODE_SPACE:
3496             if (FLAG_zap_code_space) {
3497               Sweep<SWEEP_AND_VISIT_LIVE_OBJECTS, SWEEP_ON_MAIN_THREAD,
3498                     REBUILD_SKIP_LIST, ZAP_FREE_SPACE>(space, NULL, p,
3499                                                        &updating_visitor);
3500             } else {
3501               Sweep<SWEEP_AND_VISIT_LIVE_OBJECTS, SWEEP_ON_MAIN_THREAD,
3502                     REBUILD_SKIP_LIST, IGNORE_FREE_SPACE>(space, NULL, p,
3503                                                           &updating_visitor);
3504             }
3505             break;
3506           default:
3507             UNREACHABLE();
3508             break;
3509         }
3510       }
3511     }
3512   }
3513
3514   GCTracer::Scope gc_scope(heap()->tracer(),
3515                            GCTracer::Scope::MC_UPDATE_MISC_POINTERS);
3516
3517   // Update pointers from cells.
3518   HeapObjectIterator cell_iterator(heap_->cell_space());
3519   for (HeapObject* cell = cell_iterator.Next(); cell != NULL;
3520        cell = cell_iterator.Next()) {
3521     if (cell->IsCell()) {
3522       Cell::BodyDescriptor::IterateBody(cell, &updating_visitor);
3523     }
3524   }
3525
3526   HeapObjectIterator js_global_property_cell_iterator(
3527       heap_->property_cell_space());
3528   for (HeapObject* cell = js_global_property_cell_iterator.Next(); cell != NULL;
3529        cell = js_global_property_cell_iterator.Next()) {
3530     if (cell->IsPropertyCell()) {
3531       PropertyCell::BodyDescriptor::IterateBody(cell, &updating_visitor);
3532     }
3533   }
3534
3535   heap_->string_table()->Iterate(&updating_visitor);
3536   updating_visitor.VisitPointer(heap_->weak_object_to_code_table_address());
3537   if (heap_->weak_object_to_code_table()->IsHashTable()) {
3538     WeakHashTable* table =
3539         WeakHashTable::cast(heap_->weak_object_to_code_table());
3540     table->Iterate(&updating_visitor);
3541     table->Rehash(heap_->isolate()->factory()->undefined_value());
3542   }
3543
3544   // Update pointers from external string table.
3545   heap_->UpdateReferencesInExternalStringTable(
3546       &UpdateReferenceInExternalStringTableEntry);
3547
3548   EvacuationWeakObjectRetainer evacuation_object_retainer;
3549   heap()->ProcessWeakReferences(&evacuation_object_retainer);
3550
3551   // Visit invalidated code (we ignored all slots on it) and clear mark-bits
3552   // under it.
3553   ProcessInvalidatedCode(&updating_visitor);
3554
3555   heap_->isolate()->inner_pointer_to_code_cache()->Flush();
3556
3557   slots_buffer_allocator_.DeallocateChain(&migration_slots_buffer_);
3558   DCHECK(migration_slots_buffer_ == NULL);
3559 }
3560
3561
3562 void MarkCompactCollector::MoveEvacuationCandidatesToEndOfPagesList() {
3563   int npages = evacuation_candidates_.length();
3564   for (int i = 0; i < npages; i++) {
3565     Page* p = evacuation_candidates_[i];
3566     if (!p->IsEvacuationCandidate()) continue;
3567     p->Unlink();
3568     PagedSpace* space = static_cast<PagedSpace*>(p->owner());
3569     p->InsertAfter(space->LastPage());
3570   }
3571 }
3572
3573
3574 void MarkCompactCollector::ReleaseEvacuationCandidates() {
3575   int npages = evacuation_candidates_.length();
3576   for (int i = 0; i < npages; i++) {
3577     Page* p = evacuation_candidates_[i];
3578     if (!p->IsEvacuationCandidate()) continue;
3579     PagedSpace* space = static_cast<PagedSpace*>(p->owner());
3580     space->Free(p->area_start(), p->area_size());
3581     p->set_scan_on_scavenge(false);
3582     slots_buffer_allocator_.DeallocateChain(p->slots_buffer_address());
3583     p->ResetLiveBytes();
3584     space->ReleasePage(p);
3585   }
3586   evacuation_candidates_.Rewind(0);
3587   compacting_ = false;
3588   heap()->FreeQueuedChunks();
3589 }
3590
3591
3592 static const int kStartTableEntriesPerLine = 5;
3593 static const int kStartTableLines = 171;
3594 static const int kStartTableInvalidLine = 127;
3595 static const int kStartTableUnusedEntry = 126;
3596
3597 #define _ kStartTableUnusedEntry
3598 #define X kStartTableInvalidLine
3599 // Mark-bit to object start offset table.
3600 //
3601 // The line is indexed by the mark bits in a byte.  The first number on
3602 // the line describes the number of live object starts for the line and the
3603 // other numbers on the line describe the offsets (in words) of the object
3604 // starts.
3605 //
3606 // Since objects are at least 2 words large we don't have entries for two
3607 // consecutive 1 bits.  All entries after 170 have at least 2 consecutive bits.
3608 char kStartTable[kStartTableLines * kStartTableEntriesPerLine] = {
3609     0, _, _,
3610     _, _,  // 0
3611     1, 0, _,
3612     _, _,  // 1
3613     1, 1, _,
3614     _, _,  // 2
3615     X, _, _,
3616     _, _,  // 3
3617     1, 2, _,
3618     _, _,  // 4
3619     2, 0, 2,
3620     _, _,  // 5
3621     X, _, _,
3622     _, _,  // 6
3623     X, _, _,
3624     _, _,  // 7
3625     1, 3, _,
3626     _, _,  // 8
3627     2, 0, 3,
3628     _, _,  // 9
3629     2, 1, 3,
3630     _, _,  // 10
3631     X, _, _,
3632     _, _,  // 11
3633     X, _, _,
3634     _, _,  // 12
3635     X, _, _,
3636     _, _,  // 13
3637     X, _, _,
3638     _, _,  // 14
3639     X, _, _,
3640     _, _,  // 15
3641     1, 4, _,
3642     _, _,  // 16
3643     2, 0, 4,
3644     _, _,  // 17
3645     2, 1, 4,
3646     _, _,  // 18
3647     X, _, _,
3648     _, _,  // 19
3649     2, 2, 4,
3650     _, _,  // 20
3651     3, 0, 2,
3652     4, _,  // 21
3653     X, _, _,
3654     _, _,  // 22
3655     X, _, _,
3656     _, _,  // 23
3657     X, _, _,
3658     _, _,  // 24
3659     X, _, _,
3660     _, _,  // 25
3661     X, _, _,
3662     _, _,  // 26
3663     X, _, _,
3664     _, _,  // 27
3665     X, _, _,
3666     _, _,  // 28
3667     X, _, _,
3668     _, _,  // 29
3669     X, _, _,
3670     _, _,  // 30
3671     X, _, _,
3672     _, _,  // 31
3673     1, 5, _,
3674     _, _,  // 32
3675     2, 0, 5,
3676     _, _,  // 33
3677     2, 1, 5,
3678     _, _,  // 34
3679     X, _, _,
3680     _, _,  // 35
3681     2, 2, 5,
3682     _, _,  // 36
3683     3, 0, 2,
3684     5, _,  // 37
3685     X, _, _,
3686     _, _,  // 38
3687     X, _, _,
3688     _, _,  // 39
3689     2, 3, 5,
3690     _, _,  // 40
3691     3, 0, 3,
3692     5, _,  // 41
3693     3, 1, 3,
3694     5, _,  // 42
3695     X, _, _,
3696     _, _,  // 43
3697     X, _, _,
3698     _, _,  // 44
3699     X, _, _,
3700     _, _,  // 45
3701     X, _, _,
3702     _, _,  // 46
3703     X, _, _,
3704     _, _,  // 47
3705     X, _, _,
3706     _, _,  // 48
3707     X, _, _,
3708     _, _,  // 49
3709     X, _, _,
3710     _, _,  // 50
3711     X, _, _,
3712     _, _,  // 51
3713     X, _, _,
3714     _, _,  // 52
3715     X, _, _,
3716     _, _,  // 53
3717     X, _, _,
3718     _, _,  // 54
3719     X, _, _,
3720     _, _,  // 55
3721     X, _, _,
3722     _, _,  // 56
3723     X, _, _,
3724     _, _,  // 57
3725     X, _, _,
3726     _, _,  // 58
3727     X, _, _,
3728     _, _,  // 59
3729     X, _, _,
3730     _, _,  // 60
3731     X, _, _,
3732     _, _,  // 61
3733     X, _, _,
3734     _, _,  // 62
3735     X, _, _,
3736     _, _,  // 63
3737     1, 6, _,
3738     _, _,  // 64
3739     2, 0, 6,
3740     _, _,  // 65
3741     2, 1, 6,
3742     _, _,  // 66
3743     X, _, _,
3744     _, _,  // 67
3745     2, 2, 6,
3746     _, _,  // 68
3747     3, 0, 2,
3748     6, _,  // 69
3749     X, _, _,
3750     _, _,  // 70
3751     X, _, _,
3752     _, _,  // 71
3753     2, 3, 6,
3754     _, _,  // 72
3755     3, 0, 3,
3756     6, _,  // 73
3757     3, 1, 3,
3758     6, _,  // 74
3759     X, _, _,
3760     _, _,  // 75
3761     X, _, _,
3762     _, _,  // 76
3763     X, _, _,
3764     _, _,  // 77
3765     X, _, _,
3766     _, _,  // 78
3767     X, _, _,
3768     _, _,  // 79
3769     2, 4, 6,
3770     _, _,  // 80
3771     3, 0, 4,
3772     6, _,  // 81
3773     3, 1, 4,
3774     6, _,  // 82
3775     X, _, _,
3776     _, _,  // 83
3777     3, 2, 4,
3778     6, _,  // 84
3779     4, 0, 2,
3780     4, 6,  // 85
3781     X, _, _,
3782     _, _,  // 86
3783     X, _, _,
3784     _, _,  // 87
3785     X, _, _,
3786     _, _,  // 88
3787     X, _, _,
3788     _, _,  // 89
3789     X, _, _,
3790     _, _,  // 90
3791     X, _, _,
3792     _, _,  // 91
3793     X, _, _,
3794     _, _,  // 92
3795     X, _, _,
3796     _, _,  // 93
3797     X, _, _,
3798     _, _,  // 94
3799     X, _, _,
3800     _, _,  // 95
3801     X, _, _,
3802     _, _,  // 96
3803     X, _, _,
3804     _, _,  // 97
3805     X, _, _,
3806     _, _,  // 98
3807     X, _, _,
3808     _, _,  // 99
3809     X, _, _,
3810     _, _,  // 100
3811     X, _, _,
3812     _, _,  // 101
3813     X, _, _,
3814     _, _,  // 102
3815     X, _, _,
3816     _, _,  // 103
3817     X, _, _,
3818     _, _,  // 104
3819     X, _, _,
3820     _, _,  // 105
3821     X, _, _,
3822     _, _,  // 106
3823     X, _, _,
3824     _, _,  // 107
3825     X, _, _,
3826     _, _,  // 108
3827     X, _, _,
3828     _, _,  // 109
3829     X, _, _,
3830     _, _,  // 110
3831     X, _, _,
3832     _, _,  // 111
3833     X, _, _,
3834     _, _,  // 112
3835     X, _, _,
3836     _, _,  // 113
3837     X, _, _,
3838     _, _,  // 114
3839     X, _, _,
3840     _, _,  // 115
3841     X, _, _,
3842     _, _,  // 116
3843     X, _, _,
3844     _, _,  // 117
3845     X, _, _,
3846     _, _,  // 118
3847     X, _, _,
3848     _, _,  // 119
3849     X, _, _,
3850     _, _,  // 120
3851     X, _, _,
3852     _, _,  // 121
3853     X, _, _,
3854     _, _,  // 122
3855     X, _, _,
3856     _, _,  // 123
3857     X, _, _,
3858     _, _,  // 124
3859     X, _, _,
3860     _, _,  // 125
3861     X, _, _,
3862     _, _,  // 126
3863     X, _, _,
3864     _, _,  // 127
3865     1, 7, _,
3866     _, _,  // 128
3867     2, 0, 7,
3868     _, _,  // 129
3869     2, 1, 7,
3870     _, _,  // 130
3871     X, _, _,
3872     _, _,  // 131
3873     2, 2, 7,
3874     _, _,  // 132
3875     3, 0, 2,
3876     7, _,  // 133
3877     X, _, _,
3878     _, _,  // 134
3879     X, _, _,
3880     _, _,  // 135
3881     2, 3, 7,
3882     _, _,  // 136
3883     3, 0, 3,
3884     7, _,  // 137
3885     3, 1, 3,
3886     7, _,  // 138
3887     X, _, _,
3888     _, _,  // 139
3889     X, _, _,
3890     _, _,  // 140
3891     X, _, _,
3892     _, _,  // 141
3893     X, _, _,
3894     _, _,  // 142
3895     X, _, _,
3896     _, _,  // 143
3897     2, 4, 7,
3898     _, _,  // 144
3899     3, 0, 4,
3900     7, _,  // 145
3901     3, 1, 4,
3902     7, _,  // 146
3903     X, _, _,
3904     _, _,  // 147
3905     3, 2, 4,
3906     7, _,  // 148
3907     4, 0, 2,
3908     4, 7,  // 149
3909     X, _, _,
3910     _, _,  // 150
3911     X, _, _,
3912     _, _,  // 151
3913     X, _, _,
3914     _, _,  // 152
3915     X, _, _,
3916     _, _,  // 153
3917     X, _, _,
3918     _, _,  // 154
3919     X, _, _,
3920     _, _,  // 155
3921     X, _, _,
3922     _, _,  // 156
3923     X, _, _,
3924     _, _,  // 157
3925     X, _, _,
3926     _, _,  // 158
3927     X, _, _,
3928     _, _,  // 159
3929     2, 5, 7,
3930     _, _,  // 160
3931     3, 0, 5,
3932     7, _,  // 161
3933     3, 1, 5,
3934     7, _,  // 162
3935     X, _, _,
3936     _, _,  // 163
3937     3, 2, 5,
3938     7, _,  // 164
3939     4, 0, 2,
3940     5, 7,  // 165
3941     X, _, _,
3942     _, _,  // 166
3943     X, _, _,
3944     _, _,  // 167
3945     3, 3, 5,
3946     7, _,  // 168
3947     4, 0, 3,
3948     5, 7,  // 169
3949     4, 1, 3,
3950     5, 7  // 170
3951 };
3952 #undef _
3953 #undef X
3954
3955
3956 // Takes a word of mark bits.  Returns the number of objects that start in the
3957 // range.  Puts the offsets of the words in the supplied array.
3958 static inline int MarkWordToObjectStarts(uint32_t mark_bits, int* starts) {
3959   int objects = 0;
3960   int offset = 0;
3961
3962   // No consecutive 1 bits.
3963   DCHECK((mark_bits & 0x180) != 0x180);
3964   DCHECK((mark_bits & 0x18000) != 0x18000);
3965   DCHECK((mark_bits & 0x1800000) != 0x1800000);
3966
3967   while (mark_bits != 0) {
3968     int byte = (mark_bits & 0xff);
3969     mark_bits >>= 8;
3970     if (byte != 0) {
3971       DCHECK(byte < kStartTableLines);  // No consecutive 1 bits.
3972       char* table = kStartTable + byte * kStartTableEntriesPerLine;
3973       int objects_in_these_8_words = table[0];
3974       DCHECK(objects_in_these_8_words != kStartTableInvalidLine);
3975       DCHECK(objects_in_these_8_words < kStartTableEntriesPerLine);
3976       for (int i = 0; i < objects_in_these_8_words; i++) {
3977         starts[objects++] = offset + table[1 + i];
3978       }
3979     }
3980     offset += 8;
3981   }
3982   return objects;
3983 }
3984
3985
3986 int MarkCompactCollector::SweepInParallel(PagedSpace* space,
3987                                           int required_freed_bytes) {
3988   int max_freed = 0;
3989   int max_freed_overall = 0;
3990   PageIterator it(space);
3991   while (it.has_next()) {
3992     Page* p = it.next();
3993     max_freed = SweepInParallel(p, space);
3994     DCHECK(max_freed >= 0);
3995     if (required_freed_bytes > 0 && max_freed >= required_freed_bytes) {
3996       return max_freed;
3997     }
3998     max_freed_overall = Max(max_freed, max_freed_overall);
3999     if (p == space->end_of_unswept_pages()) break;
4000   }
4001   return max_freed_overall;
4002 }
4003
4004
4005 int MarkCompactCollector::SweepInParallel(Page* page, PagedSpace* space) {
4006   int max_freed = 0;
4007   if (page->TryParallelSweeping()) {
4008     FreeList* free_list = space == heap()->old_pointer_space()
4009                               ? free_list_old_pointer_space_.get()
4010                               : free_list_old_data_space_.get();
4011     FreeList private_free_list(space);
4012     max_freed = Sweep<SWEEP_ONLY, SWEEP_IN_PARALLEL, IGNORE_SKIP_LIST,
4013                       IGNORE_FREE_SPACE>(space, &private_free_list, page, NULL);
4014     free_list->Concatenate(&private_free_list);
4015   }
4016   return max_freed;
4017 }
4018
4019
4020 void MarkCompactCollector::SweepSpace(PagedSpace* space, SweeperType sweeper) {
4021   space->ClearStats();
4022
4023   // We defensively initialize end_of_unswept_pages_ here with the first page
4024   // of the pages list.
4025   space->set_end_of_unswept_pages(space->FirstPage());
4026
4027   PageIterator it(space);
4028
4029   int pages_swept = 0;
4030   bool unused_page_present = false;
4031   bool parallel_sweeping_active = false;
4032
4033   while (it.has_next()) {
4034     Page* p = it.next();
4035     DCHECK(p->parallel_sweeping() == MemoryChunk::SWEEPING_DONE);
4036
4037     // Clear sweeping flags indicating that marking bits are still intact.
4038     p->ClearWasSwept();
4039
4040     if (p->IsFlagSet(Page::RESCAN_ON_EVACUATION) ||
4041         p->IsEvacuationCandidate()) {
4042       // Will be processed in EvacuateNewSpaceAndCandidates.
4043       DCHECK(evacuation_candidates_.length() > 0);
4044       continue;
4045     }
4046
4047     // One unused page is kept, all further are released before sweeping them.
4048     if (p->LiveBytes() == 0) {
4049       if (unused_page_present) {
4050         if (FLAG_gc_verbose) {
4051           PrintF("Sweeping 0x%" V8PRIxPTR " released page.\n",
4052                  reinterpret_cast<intptr_t>(p));
4053         }
4054         // Adjust unswept free bytes because releasing a page expects said
4055         // counter to be accurate for unswept pages.
4056         space->IncreaseUnsweptFreeBytes(p);
4057         space->ReleasePage(p);
4058         continue;
4059       }
4060       unused_page_present = true;
4061     }
4062
4063     switch (sweeper) {
4064       case CONCURRENT_SWEEPING:
4065         if (!parallel_sweeping_active) {
4066           if (FLAG_gc_verbose) {
4067             PrintF("Sweeping 0x%" V8PRIxPTR ".\n",
4068                    reinterpret_cast<intptr_t>(p));
4069           }
4070           Sweep<SWEEP_ONLY, SWEEP_ON_MAIN_THREAD, IGNORE_SKIP_LIST,
4071                 IGNORE_FREE_SPACE>(space, NULL, p, NULL);
4072           pages_swept++;
4073           parallel_sweeping_active = true;
4074         } else {
4075           if (FLAG_gc_verbose) {
4076             PrintF("Sweeping 0x%" V8PRIxPTR " in parallel.\n",
4077                    reinterpret_cast<intptr_t>(p));
4078           }
4079           p->set_parallel_sweeping(MemoryChunk::SWEEPING_PENDING);
4080           space->IncreaseUnsweptFreeBytes(p);
4081         }
4082         space->set_end_of_unswept_pages(p);
4083         break;
4084       case SEQUENTIAL_SWEEPING: {
4085         if (FLAG_gc_verbose) {
4086           PrintF("Sweeping 0x%" V8PRIxPTR ".\n", reinterpret_cast<intptr_t>(p));
4087         }
4088         if (space->identity() == CODE_SPACE && FLAG_zap_code_space) {
4089           Sweep<SWEEP_ONLY, SWEEP_ON_MAIN_THREAD, REBUILD_SKIP_LIST,
4090                 ZAP_FREE_SPACE>(space, NULL, p, NULL);
4091         } else if (space->identity() == CODE_SPACE) {
4092           Sweep<SWEEP_ONLY, SWEEP_ON_MAIN_THREAD, REBUILD_SKIP_LIST,
4093                 IGNORE_FREE_SPACE>(space, NULL, p, NULL);
4094         } else {
4095           Sweep<SWEEP_ONLY, SWEEP_ON_MAIN_THREAD, IGNORE_SKIP_LIST,
4096                 IGNORE_FREE_SPACE>(space, NULL, p, NULL);
4097         }
4098         pages_swept++;
4099         break;
4100       }
4101       default: { UNREACHABLE(); }
4102     }
4103   }
4104
4105   if (FLAG_gc_verbose) {
4106     PrintF("SweepSpace: %s (%d pages swept)\n",
4107            AllocationSpaceName(space->identity()), pages_swept);
4108   }
4109
4110   // Give pages that are queued to be freed back to the OS.
4111   heap()->FreeQueuedChunks();
4112 }
4113
4114
4115 void MarkCompactCollector::SweepSpaces() {
4116   GCTracer::Scope gc_scope(heap()->tracer(), GCTracer::Scope::MC_SWEEP);
4117   double start_time = 0.0;
4118   if (FLAG_print_cumulative_gc_stat) {
4119     start_time = base::OS::TimeCurrentMillis();
4120   }
4121
4122 #ifdef DEBUG
4123   state_ = SWEEP_SPACES;
4124 #endif
4125   MoveEvacuationCandidatesToEndOfPagesList();
4126
4127   // Noncompacting collections simply sweep the spaces to clear the mark
4128   // bits and free the nonlive blocks (for old and map spaces).  We sweep
4129   // the map space last because freeing non-live maps overwrites them and
4130   // the other spaces rely on possibly non-live maps to get the sizes for
4131   // non-live objects.
4132   {
4133     GCTracer::Scope sweep_scope(heap()->tracer(),
4134                                 GCTracer::Scope::MC_SWEEP_OLDSPACE);
4135     {
4136       SweepSpace(heap()->old_pointer_space(), CONCURRENT_SWEEPING);
4137       SweepSpace(heap()->old_data_space(), CONCURRENT_SWEEPING);
4138     }
4139     sweeping_in_progress_ = true;
4140     if (FLAG_concurrent_sweeping) {
4141       StartSweeperThreads();
4142     }
4143   }
4144   RemoveDeadInvalidatedCode();
4145
4146   {
4147     GCTracer::Scope sweep_scope(heap()->tracer(),
4148                                 GCTracer::Scope::MC_SWEEP_CODE);
4149     SweepSpace(heap()->code_space(), SEQUENTIAL_SWEEPING);
4150   }
4151
4152   {
4153     GCTracer::Scope sweep_scope(heap()->tracer(),
4154                                 GCTracer::Scope::MC_SWEEP_CELL);
4155     SweepSpace(heap()->cell_space(), SEQUENTIAL_SWEEPING);
4156     SweepSpace(heap()->property_cell_space(), SEQUENTIAL_SWEEPING);
4157   }
4158
4159   EvacuateNewSpaceAndCandidates();
4160
4161   // ClearNonLiveTransitions depends on precise sweeping of map space to
4162   // detect whether unmarked map became dead in this collection or in one
4163   // of the previous ones.
4164   {
4165     GCTracer::Scope sweep_scope(heap()->tracer(),
4166                                 GCTracer::Scope::MC_SWEEP_MAP);
4167     SweepSpace(heap()->map_space(), SEQUENTIAL_SWEEPING);
4168   }
4169
4170   // Deallocate unmarked objects and clear marked bits for marked objects.
4171   heap_->lo_space()->FreeUnmarkedObjects();
4172
4173   // Deallocate evacuated candidate pages.
4174   ReleaseEvacuationCandidates();
4175   CodeRange* code_range = heap()->isolate()->code_range();
4176   if (code_range != NULL && code_range->valid()) {
4177     code_range->ReserveEmergencyBlock();
4178   }
4179
4180   if (FLAG_print_cumulative_gc_stat) {
4181     heap_->tracer()->AddSweepingTime(base::OS::TimeCurrentMillis() -
4182                                      start_time);
4183   }
4184 }
4185
4186
4187 void MarkCompactCollector::ParallelSweepSpaceComplete(PagedSpace* space) {
4188   PageIterator it(space);
4189   while (it.has_next()) {
4190     Page* p = it.next();
4191     if (p->parallel_sweeping() == MemoryChunk::SWEEPING_FINALIZE) {
4192       p->set_parallel_sweeping(MemoryChunk::SWEEPING_DONE);
4193       p->SetWasSwept();
4194     }
4195     DCHECK(p->parallel_sweeping() == MemoryChunk::SWEEPING_DONE);
4196   }
4197 }
4198
4199
4200 void MarkCompactCollector::ParallelSweepSpacesComplete() {
4201   ParallelSweepSpaceComplete(heap()->old_pointer_space());
4202   ParallelSweepSpaceComplete(heap()->old_data_space());
4203 }
4204
4205
4206 void MarkCompactCollector::EnableCodeFlushing(bool enable) {
4207   if (isolate()->debug()->is_loaded() ||
4208       isolate()->debug()->has_break_points()) {
4209     enable = false;
4210   }
4211
4212   if (enable) {
4213     if (code_flusher_ != NULL) return;
4214     code_flusher_ = new CodeFlusher(isolate());
4215   } else {
4216     if (code_flusher_ == NULL) return;
4217     code_flusher_->EvictAllCandidates();
4218     delete code_flusher_;
4219     code_flusher_ = NULL;
4220   }
4221
4222   if (FLAG_trace_code_flushing) {
4223     PrintF("[code-flushing is now %s]\n", enable ? "on" : "off");
4224   }
4225 }
4226
4227
4228 // TODO(1466) ReportDeleteIfNeeded is not called currently.
4229 // Our profiling tools do not expect intersections between
4230 // code objects. We should either reenable it or change our tools.
4231 void MarkCompactCollector::ReportDeleteIfNeeded(HeapObject* obj,
4232                                                 Isolate* isolate) {
4233   if (obj->IsCode()) {
4234     PROFILE(isolate, CodeDeleteEvent(obj->address()));
4235   }
4236 }
4237
4238
4239 Isolate* MarkCompactCollector::isolate() const { return heap_->isolate(); }
4240
4241
4242 void MarkCompactCollector::Initialize() {
4243   MarkCompactMarkingVisitor::Initialize();
4244   IncrementalMarking::Initialize();
4245 }
4246
4247
4248 bool SlotsBuffer::IsTypedSlot(ObjectSlot slot) {
4249   return reinterpret_cast<uintptr_t>(slot) < NUMBER_OF_SLOT_TYPES;
4250 }
4251
4252
4253 bool SlotsBuffer::AddTo(SlotsBufferAllocator* allocator,
4254                         SlotsBuffer** buffer_address, SlotType type,
4255                         Address addr, AdditionMode mode) {
4256   SlotsBuffer* buffer = *buffer_address;
4257   if (buffer == NULL || !buffer->HasSpaceForTypedSlot()) {
4258     if (mode == FAIL_ON_OVERFLOW && ChainLengthThresholdReached(buffer)) {
4259       allocator->DeallocateChain(buffer_address);
4260       return false;
4261     }
4262     buffer = allocator->AllocateBuffer(buffer);
4263     *buffer_address = buffer;
4264   }
4265   DCHECK(buffer->HasSpaceForTypedSlot());
4266   buffer->Add(reinterpret_cast<ObjectSlot>(type));
4267   buffer->Add(reinterpret_cast<ObjectSlot>(addr));
4268   return true;
4269 }
4270
4271
4272 static inline SlotsBuffer::SlotType SlotTypeForRMode(RelocInfo::Mode rmode) {
4273   if (RelocInfo::IsCodeTarget(rmode)) {
4274     return SlotsBuffer::CODE_TARGET_SLOT;
4275   } else if (RelocInfo::IsEmbeddedObject(rmode)) {
4276     return SlotsBuffer::EMBEDDED_OBJECT_SLOT;
4277   } else if (RelocInfo::IsDebugBreakSlot(rmode)) {
4278     return SlotsBuffer::DEBUG_TARGET_SLOT;
4279   } else if (RelocInfo::IsJSReturn(rmode)) {
4280     return SlotsBuffer::JS_RETURN_SLOT;
4281   }
4282   UNREACHABLE();
4283   return SlotsBuffer::NUMBER_OF_SLOT_TYPES;
4284 }
4285
4286
4287 void MarkCompactCollector::RecordRelocSlot(RelocInfo* rinfo, Object* target) {
4288   Page* target_page = Page::FromAddress(reinterpret_cast<Address>(target));
4289   RelocInfo::Mode rmode = rinfo->rmode();
4290   if (target_page->IsEvacuationCandidate() &&
4291       (rinfo->host() == NULL ||
4292        !ShouldSkipEvacuationSlotRecording(rinfo->host()))) {
4293     bool success;
4294     if (RelocInfo::IsEmbeddedObject(rmode) && rinfo->IsInConstantPool()) {
4295       // This doesn't need to be typed since it is just a normal heap pointer.
4296       Object** target_pointer =
4297           reinterpret_cast<Object**>(rinfo->constant_pool_entry_address());
4298       success = SlotsBuffer::AddTo(
4299           &slots_buffer_allocator_, target_page->slots_buffer_address(),
4300           target_pointer, SlotsBuffer::FAIL_ON_OVERFLOW);
4301     } else if (RelocInfo::IsCodeTarget(rmode) && rinfo->IsInConstantPool()) {
4302       success = SlotsBuffer::AddTo(
4303           &slots_buffer_allocator_, target_page->slots_buffer_address(),
4304           SlotsBuffer::CODE_ENTRY_SLOT, rinfo->constant_pool_entry_address(),
4305           SlotsBuffer::FAIL_ON_OVERFLOW);
4306     } else {
4307       success = SlotsBuffer::AddTo(
4308           &slots_buffer_allocator_, target_page->slots_buffer_address(),
4309           SlotTypeForRMode(rmode), rinfo->pc(), SlotsBuffer::FAIL_ON_OVERFLOW);
4310     }
4311     if (!success) {
4312       EvictEvacuationCandidate(target_page);
4313     }
4314   }
4315 }
4316
4317
4318 void MarkCompactCollector::RecordCodeEntrySlot(Address slot, Code* target) {
4319   Page* target_page = Page::FromAddress(reinterpret_cast<Address>(target));
4320   if (target_page->IsEvacuationCandidate() &&
4321       !ShouldSkipEvacuationSlotRecording(reinterpret_cast<Object**>(slot))) {
4322     if (!SlotsBuffer::AddTo(&slots_buffer_allocator_,
4323                             target_page->slots_buffer_address(),
4324                             SlotsBuffer::CODE_ENTRY_SLOT, slot,
4325                             SlotsBuffer::FAIL_ON_OVERFLOW)) {
4326       EvictEvacuationCandidate(target_page);
4327     }
4328   }
4329 }
4330
4331
4332 void MarkCompactCollector::RecordCodeTargetPatch(Address pc, Code* target) {
4333   DCHECK(heap()->gc_state() == Heap::MARK_COMPACT);
4334   if (is_compacting()) {
4335     Code* host =
4336         isolate()->inner_pointer_to_code_cache()->GcSafeFindCodeForInnerPointer(
4337             pc);
4338     MarkBit mark_bit = Marking::MarkBitFrom(host);
4339     if (Marking::IsBlack(mark_bit)) {
4340       RelocInfo rinfo(pc, RelocInfo::CODE_TARGET, 0, host);
4341       RecordRelocSlot(&rinfo, target);
4342     }
4343   }
4344 }
4345
4346
4347 static inline SlotsBuffer::SlotType DecodeSlotType(
4348     SlotsBuffer::ObjectSlot slot) {
4349   return static_cast<SlotsBuffer::SlotType>(reinterpret_cast<intptr_t>(slot));
4350 }
4351
4352
4353 void SlotsBuffer::UpdateSlots(Heap* heap) {
4354   PointersUpdatingVisitor v(heap);
4355
4356   for (int slot_idx = 0; slot_idx < idx_; ++slot_idx) {
4357     ObjectSlot slot = slots_[slot_idx];
4358     if (!IsTypedSlot(slot)) {
4359       PointersUpdatingVisitor::UpdateSlot(heap, slot);
4360     } else {
4361       ++slot_idx;
4362       DCHECK(slot_idx < idx_);
4363       UpdateSlot(heap->isolate(), &v, DecodeSlotType(slot),
4364                  reinterpret_cast<Address>(slots_[slot_idx]));
4365     }
4366   }
4367 }
4368
4369
4370 void SlotsBuffer::UpdateSlotsWithFilter(Heap* heap) {
4371   PointersUpdatingVisitor v(heap);
4372
4373   for (int slot_idx = 0; slot_idx < idx_; ++slot_idx) {
4374     ObjectSlot slot = slots_[slot_idx];
4375     if (!IsTypedSlot(slot)) {
4376       if (!IsOnInvalidatedCodeObject(reinterpret_cast<Address>(slot))) {
4377         PointersUpdatingVisitor::UpdateSlot(heap, slot);
4378       }
4379     } else {
4380       ++slot_idx;
4381       DCHECK(slot_idx < idx_);
4382       Address pc = reinterpret_cast<Address>(slots_[slot_idx]);
4383       if (!IsOnInvalidatedCodeObject(pc)) {
4384         UpdateSlot(heap->isolate(), &v, DecodeSlotType(slot),
4385                    reinterpret_cast<Address>(slots_[slot_idx]));
4386       }
4387     }
4388   }
4389 }
4390
4391
4392 SlotsBuffer* SlotsBufferAllocator::AllocateBuffer(SlotsBuffer* next_buffer) {
4393   return new SlotsBuffer(next_buffer);
4394 }
4395
4396
4397 void SlotsBufferAllocator::DeallocateBuffer(SlotsBuffer* buffer) {
4398   delete buffer;
4399 }
4400
4401
4402 void SlotsBufferAllocator::DeallocateChain(SlotsBuffer** buffer_address) {
4403   SlotsBuffer* buffer = *buffer_address;
4404   while (buffer != NULL) {
4405     SlotsBuffer* next_buffer = buffer->next();
4406     DeallocateBuffer(buffer);
4407     buffer = next_buffer;
4408   }
4409   *buffer_address = NULL;
4410 }
4411 }
4412 }  // namespace v8::internal