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