blob: c866346f01460c22867f31071ea2b0edb4edabd5 [file] [log] [blame]
Ben Murdoch592a9fc2012-03-05 11:04:45 +00001// Copyright 2011 the V8 project authors. All rights reserved.
2// Redistribution and use in source and binary forms, with or without
3// modification, are permitted provided that the following conditions are
4// met:
5//
6// * Redistributions of source code must retain the above copyright
7// notice, this list of conditions and the following disclaimer.
8// * Redistributions in binary form must reproduce the above
9// copyright notice, this list of conditions and the following
10// disclaimer in the documentation and/or other materials provided
11// with the distribution.
12// * Neither the name of Google Inc. nor the names of its
13// contributors may be used to endorse or promote products derived
14// from this software without specific prior written permission.
15//
16// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
17// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
18// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
19// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
20// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
26// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27
28#include "v8.h"
29
30#include "incremental-marking.h"
31
32#include "code-stubs.h"
33#include "compilation-cache.h"
34#include "v8conversions.h"
35
36namespace v8 {
37namespace internal {
38
39
40IncrementalMarking::IncrementalMarking(Heap* heap)
41 : heap_(heap),
42 state_(STOPPED),
43 marking_deque_memory_(NULL),
44 marking_deque_memory_committed_(false),
45 steps_count_(0),
46 steps_took_(0),
47 longest_step_(0.0),
48 old_generation_space_available_at_start_of_incremental_(0),
49 old_generation_space_used_at_start_of_incremental_(0),
50 steps_count_since_last_gc_(0),
51 steps_took_since_last_gc_(0),
52 should_hurry_(false),
53 allocation_marking_factor_(0),
54 allocated_(0),
55 no_marking_scope_depth_(0) {
56}
57
58
59void IncrementalMarking::TearDown() {
60 delete marking_deque_memory_;
61}
62
63
64void IncrementalMarking::RecordWriteSlow(HeapObject* obj,
65 Object** slot,
66 Object* value) {
67 if (BaseRecordWrite(obj, slot, value) && is_compacting_ && slot != NULL) {
68 MarkBit obj_bit = Marking::MarkBitFrom(obj);
69 if (Marking::IsBlack(obj_bit)) {
70 // Object is not going to be rescanned we need to record the slot.
71 heap_->mark_compact_collector()->RecordSlot(
72 HeapObject::RawField(obj, 0), slot, value);
73 }
74 }
75}
76
77
78void IncrementalMarking::RecordWriteFromCode(HeapObject* obj,
79 Object* value,
80 Isolate* isolate) {
81 ASSERT(obj->IsHeapObject());
82
83 // Fast cases should already be covered by RecordWriteStub.
84 ASSERT(value->IsHeapObject());
85 ASSERT(!value->IsHeapNumber());
86 ASSERT(!value->IsString() ||
87 value->IsConsString() ||
88 value->IsSlicedString());
89 ASSERT(Marking::IsWhite(Marking::MarkBitFrom(HeapObject::cast(value))));
90
91 IncrementalMarking* marking = isolate->heap()->incremental_marking();
92 ASSERT(!marking->is_compacting_);
93 marking->RecordWrite(obj, NULL, value);
94}
95
96
97void IncrementalMarking::RecordWriteForEvacuationFromCode(HeapObject* obj,
98 Object** slot,
99 Isolate* isolate) {
100 IncrementalMarking* marking = isolate->heap()->incremental_marking();
101 ASSERT(marking->is_compacting_);
102 marking->RecordWrite(obj, slot, *slot);
103}
104
105
106void IncrementalMarking::RecordCodeTargetPatch(Code* host,
107 Address pc,
108 HeapObject* value) {
109 if (IsMarking()) {
110 RelocInfo rinfo(pc, RelocInfo::CODE_TARGET, 0, host);
111 RecordWriteIntoCode(host, &rinfo, value);
112 }
113}
114
115
116void IncrementalMarking::RecordCodeTargetPatch(Address pc, HeapObject* value) {
117 if (IsMarking()) {
118 Code* host = heap_->isolate()->inner_pointer_to_code_cache()->
119 GcSafeFindCodeForInnerPointer(pc);
120 RelocInfo rinfo(pc, RelocInfo::CODE_TARGET, 0, host);
121 RecordWriteIntoCode(host, &rinfo, value);
122 }
123}
124
125
126void IncrementalMarking::RecordWriteOfCodeEntrySlow(JSFunction* host,
127 Object** slot,
128 Code* value) {
129 if (BaseRecordWrite(host, slot, value) && is_compacting_) {
130 ASSERT(slot != NULL);
131 heap_->mark_compact_collector()->
132 RecordCodeEntrySlot(reinterpret_cast<Address>(slot), value);
133 }
134}
135
136
137void IncrementalMarking::RecordWriteIntoCodeSlow(HeapObject* obj,
138 RelocInfo* rinfo,
139 Object* value) {
140 MarkBit value_bit = Marking::MarkBitFrom(HeapObject::cast(value));
141 if (Marking::IsWhite(value_bit)) {
142 MarkBit obj_bit = Marking::MarkBitFrom(obj);
143 if (Marking::IsBlack(obj_bit)) {
144 BlackToGreyAndUnshift(obj, obj_bit);
145 RestartIfNotMarking();
146 }
147 // Object is either grey or white. It will be scanned if survives.
148 return;
149 }
150
151 if (is_compacting_) {
152 MarkBit obj_bit = Marking::MarkBitFrom(obj);
153 if (Marking::IsBlack(obj_bit)) {
154 // Object is not going to be rescanned. We need to record the slot.
155 heap_->mark_compact_collector()->RecordRelocSlot(rinfo,
156 Code::cast(value));
157 }
158 }
159}
160
161
162class IncrementalMarkingMarkingVisitor : public ObjectVisitor {
163 public:
164 IncrementalMarkingMarkingVisitor(Heap* heap,
165 IncrementalMarking* incremental_marking)
166 : heap_(heap),
167 incremental_marking_(incremental_marking) {
168 }
169
170 void VisitEmbeddedPointer(RelocInfo* rinfo) {
171 ASSERT(rinfo->rmode() == RelocInfo::EMBEDDED_OBJECT);
172 Object* target = rinfo->target_object();
173 if (target->NonFailureIsHeapObject()) {
174 heap_->mark_compact_collector()->RecordRelocSlot(rinfo, target);
175 MarkObject(target);
176 }
177 }
178
179 void VisitCodeTarget(RelocInfo* rinfo) {
180 ASSERT(RelocInfo::IsCodeTarget(rinfo->rmode()));
181 Object* target = Code::GetCodeFromTargetAddress(rinfo->target_address());
182 heap_->mark_compact_collector()->RecordRelocSlot(rinfo, Code::cast(target));
183 MarkObject(target);
184 }
185
186 void VisitDebugTarget(RelocInfo* rinfo) {
187 ASSERT((RelocInfo::IsJSReturn(rinfo->rmode()) &&
188 rinfo->IsPatchedReturnSequence()) ||
189 (RelocInfo::IsDebugBreakSlot(rinfo->rmode()) &&
190 rinfo->IsPatchedDebugBreakSlotSequence()));
191 Object* target = Code::GetCodeFromTargetAddress(rinfo->call_address());
192 heap_->mark_compact_collector()->RecordRelocSlot(rinfo, Code::cast(target));
193 MarkObject(target);
194 }
195
196 void VisitCodeEntry(Address entry_address) {
197 Object* target = Code::GetObjectFromEntryAddress(entry_address);
198 heap_->mark_compact_collector()->
199 RecordCodeEntrySlot(entry_address, Code::cast(target));
200 MarkObject(target);
201 }
202
203 void VisitPointer(Object** p) {
204 Object* obj = *p;
205 if (obj->NonFailureIsHeapObject()) {
206 heap_->mark_compact_collector()->RecordSlot(p, p, obj);
207 MarkObject(obj);
208 }
209 }
210
211 void VisitPointers(Object** start, Object** end) {
212 for (Object** p = start; p < end; p++) {
213 Object* obj = *p;
214 if (obj->NonFailureIsHeapObject()) {
215 heap_->mark_compact_collector()->RecordSlot(start, p, obj);
216 MarkObject(obj);
217 }
218 }
219 }
220
221 private:
222 // Mark object pointed to by p.
223 INLINE(void MarkObject(Object* obj)) {
224 HeapObject* heap_object = HeapObject::cast(obj);
225 MarkBit mark_bit = Marking::MarkBitFrom(heap_object);
226 if (mark_bit.data_only()) {
227 if (incremental_marking_->MarkBlackOrKeepGrey(mark_bit)) {
228 MemoryChunk::IncrementLiveBytes(heap_object->address(),
229 heap_object->Size());
230 }
231 } else if (Marking::IsWhite(mark_bit)) {
232 incremental_marking_->WhiteToGreyAndPush(heap_object, mark_bit);
233 }
234 }
235
236 Heap* heap_;
237 IncrementalMarking* incremental_marking_;
238};
239
240
241class IncrementalMarkingRootMarkingVisitor : public ObjectVisitor {
242 public:
243 IncrementalMarkingRootMarkingVisitor(Heap* heap,
244 IncrementalMarking* incremental_marking)
245 : heap_(heap),
246 incremental_marking_(incremental_marking) {
247 }
248
249 void VisitPointer(Object** p) {
250 MarkObjectByPointer(p);
251 }
252
253 void VisitPointers(Object** start, Object** end) {
254 for (Object** p = start; p < end; p++) MarkObjectByPointer(p);
255 }
256
257 private:
258 void MarkObjectByPointer(Object** p) {
259 Object* obj = *p;
260 if (!obj->IsHeapObject()) return;
261
262 HeapObject* heap_object = HeapObject::cast(obj);
263 MarkBit mark_bit = Marking::MarkBitFrom(heap_object);
264 if (mark_bit.data_only()) {
265 if (incremental_marking_->MarkBlackOrKeepGrey(mark_bit)) {
266 MemoryChunk::IncrementLiveBytes(heap_object->address(),
267 heap_object->Size());
268 }
269 } else {
270 if (Marking::IsWhite(mark_bit)) {
271 incremental_marking_->WhiteToGreyAndPush(heap_object, mark_bit);
272 }
273 }
274 }
275
276 Heap* heap_;
277 IncrementalMarking* incremental_marking_;
278};
279
280
281void IncrementalMarking::SetOldSpacePageFlags(MemoryChunk* chunk,
282 bool is_marking,
283 bool is_compacting) {
284 if (is_marking) {
285 chunk->SetFlag(MemoryChunk::POINTERS_TO_HERE_ARE_INTERESTING);
286 chunk->SetFlag(MemoryChunk::POINTERS_FROM_HERE_ARE_INTERESTING);
287
288 // It's difficult to filter out slots recorded for large objects.
289 if (chunk->owner()->identity() == LO_SPACE &&
290 chunk->size() > static_cast<size_t>(Page::kPageSize) &&
291 is_compacting) {
292 chunk->SetFlag(MemoryChunk::RESCAN_ON_EVACUATION);
293 }
294 } else if (chunk->owner()->identity() == CELL_SPACE ||
295 chunk->scan_on_scavenge()) {
296 chunk->ClearFlag(MemoryChunk::POINTERS_TO_HERE_ARE_INTERESTING);
297 chunk->ClearFlag(MemoryChunk::POINTERS_FROM_HERE_ARE_INTERESTING);
298 } else {
299 chunk->ClearFlag(MemoryChunk::POINTERS_TO_HERE_ARE_INTERESTING);
300 chunk->SetFlag(MemoryChunk::POINTERS_FROM_HERE_ARE_INTERESTING);
301 }
302}
303
304
305void IncrementalMarking::SetNewSpacePageFlags(NewSpacePage* chunk,
306 bool is_marking) {
307 chunk->SetFlag(MemoryChunk::POINTERS_TO_HERE_ARE_INTERESTING);
308 if (is_marking) {
309 chunk->SetFlag(MemoryChunk::POINTERS_FROM_HERE_ARE_INTERESTING);
310 } else {
311 chunk->ClearFlag(MemoryChunk::POINTERS_FROM_HERE_ARE_INTERESTING);
312 }
313 chunk->SetFlag(MemoryChunk::SCAN_ON_SCAVENGE);
314}
315
316
317void IncrementalMarking::DeactivateIncrementalWriteBarrierForSpace(
318 PagedSpace* space) {
319 PageIterator it(space);
320 while (it.has_next()) {
321 Page* p = it.next();
322 SetOldSpacePageFlags(p, false, false);
323 }
324}
325
326
327void IncrementalMarking::DeactivateIncrementalWriteBarrierForSpace(
328 NewSpace* space) {
329 NewSpacePageIterator it(space);
330 while (it.has_next()) {
331 NewSpacePage* p = it.next();
332 SetNewSpacePageFlags(p, false);
333 }
334}
335
336
337void IncrementalMarking::DeactivateIncrementalWriteBarrier() {
338 DeactivateIncrementalWriteBarrierForSpace(heap_->old_pointer_space());
339 DeactivateIncrementalWriteBarrierForSpace(heap_->old_data_space());
340 DeactivateIncrementalWriteBarrierForSpace(heap_->cell_space());
341 DeactivateIncrementalWriteBarrierForSpace(heap_->map_space());
342 DeactivateIncrementalWriteBarrierForSpace(heap_->code_space());
343 DeactivateIncrementalWriteBarrierForSpace(heap_->new_space());
344
345 LargePage* lop = heap_->lo_space()->first_page();
346 while (lop->is_valid()) {
347 SetOldSpacePageFlags(lop, false, false);
348 lop = lop->next_page();
349 }
350}
351
352
353void IncrementalMarking::ActivateIncrementalWriteBarrier(PagedSpace* space) {
354 PageIterator it(space);
355 while (it.has_next()) {
356 Page* p = it.next();
357 SetOldSpacePageFlags(p, true, is_compacting_);
358 }
359}
360
361
362void IncrementalMarking::ActivateIncrementalWriteBarrier(NewSpace* space) {
363 NewSpacePageIterator it(space->ToSpaceStart(), space->ToSpaceEnd());
364 while (it.has_next()) {
365 NewSpacePage* p = it.next();
366 SetNewSpacePageFlags(p, true);
367 }
368}
369
370
371void IncrementalMarking::ActivateIncrementalWriteBarrier() {
372 ActivateIncrementalWriteBarrier(heap_->old_pointer_space());
373 ActivateIncrementalWriteBarrier(heap_->old_data_space());
374 ActivateIncrementalWriteBarrier(heap_->cell_space());
375 ActivateIncrementalWriteBarrier(heap_->map_space());
376 ActivateIncrementalWriteBarrier(heap_->code_space());
377 ActivateIncrementalWriteBarrier(heap_->new_space());
378
379 LargePage* lop = heap_->lo_space()->first_page();
380 while (lop->is_valid()) {
381 SetOldSpacePageFlags(lop, true, is_compacting_);
382 lop = lop->next_page();
383 }
384}
385
386
387bool IncrementalMarking::WorthActivating() {
388#ifndef DEBUG
389 static const intptr_t kActivationThreshold = 8 * MB;
390#else
391 // TODO(gc) consider setting this to some low level so that some
392 // debug tests run with incremental marking and some without.
393 static const intptr_t kActivationThreshold = 0;
394#endif
395
396 return !FLAG_expose_gc &&
397 FLAG_incremental_marking &&
398 !Serializer::enabled() &&
399 heap_->PromotedSpaceSize() > kActivationThreshold;
400}
401
402
403void IncrementalMarking::ActivateGeneratedStub(Code* stub) {
404 ASSERT(RecordWriteStub::GetMode(stub) ==
405 RecordWriteStub::STORE_BUFFER_ONLY);
406
407 if (!IsMarking()) {
408 // Initially stub is generated in STORE_BUFFER_ONLY mode thus
409 // we don't need to do anything if incremental marking is
410 // not active.
411 } else if (IsCompacting()) {
412 RecordWriteStub::Patch(stub, RecordWriteStub::INCREMENTAL_COMPACTION);
413 } else {
414 RecordWriteStub::Patch(stub, RecordWriteStub::INCREMENTAL);
415 }
416}
417
418
419static void PatchIncrementalMarkingRecordWriteStubs(
420 Heap* heap, RecordWriteStub::Mode mode) {
421 NumberDictionary* stubs = heap->code_stubs();
422
423 int capacity = stubs->Capacity();
424 for (int i = 0; i < capacity; i++) {
425 Object* k = stubs->KeyAt(i);
426 if (stubs->IsKey(k)) {
427 uint32_t key = NumberToUint32(k);
428
429 if (CodeStub::MajorKeyFromKey(key) ==
430 CodeStub::RecordWrite) {
431 Object* e = stubs->ValueAt(i);
432 if (e->IsCode()) {
433 RecordWriteStub::Patch(Code::cast(e), mode);
434 }
435 }
436 }
437 }
438}
439
440
441void IncrementalMarking::EnsureMarkingDequeIsCommitted() {
442 if (marking_deque_memory_ == NULL) {
443 marking_deque_memory_ = new VirtualMemory(4 * MB);
444 }
445 if (!marking_deque_memory_committed_) {
446 bool success = marking_deque_memory_->Commit(
447 reinterpret_cast<Address>(marking_deque_memory_->address()),
448 marking_deque_memory_->size(),
449 false); // Not executable.
450 CHECK(success);
451 marking_deque_memory_committed_ = true;
452 }
453}
454
455void IncrementalMarking::UncommitMarkingDeque() {
456 if (state_ == STOPPED && marking_deque_memory_committed_) {
457 bool success = marking_deque_memory_->Uncommit(
458 reinterpret_cast<Address>(marking_deque_memory_->address()),
459 marking_deque_memory_->size());
460 CHECK(success);
461 marking_deque_memory_committed_ = false;
462 }
463}
464
465
466void IncrementalMarking::Start() {
467 if (FLAG_trace_incremental_marking) {
468 PrintF("[IncrementalMarking] Start\n");
469 }
470 ASSERT(FLAG_incremental_marking);
471 ASSERT(state_ == STOPPED);
472
473 ResetStepCounters();
474
475 if (heap_->old_pointer_space()->IsSweepingComplete() &&
476 heap_->old_data_space()->IsSweepingComplete()) {
477 StartMarking(ALLOW_COMPACTION);
478 } else {
479 if (FLAG_trace_incremental_marking) {
480 PrintF("[IncrementalMarking] Start sweeping.\n");
481 }
482 state_ = SWEEPING;
483 }
484
485 heap_->new_space()->LowerInlineAllocationLimit(kAllocatedThreshold);
486}
487
488
489static void MarkObjectGreyDoNotEnqueue(Object* obj) {
490 if (obj->IsHeapObject()) {
491 HeapObject* heap_obj = HeapObject::cast(obj);
492 MarkBit mark_bit = Marking::MarkBitFrom(HeapObject::cast(obj));
493 if (Marking::IsBlack(mark_bit)) {
494 MemoryChunk::IncrementLiveBytes(heap_obj->address(),
495 -heap_obj->Size());
496 }
497 Marking::AnyToGrey(mark_bit);
498 }
499}
500
501
502void IncrementalMarking::StartMarking(CompactionFlag flag) {
503 if (FLAG_trace_incremental_marking) {
504 PrintF("[IncrementalMarking] Start marking\n");
505 }
506
507 is_compacting_ = !FLAG_never_compact && (flag == ALLOW_COMPACTION) &&
508 heap_->mark_compact_collector()->StartCompaction();
509
510 state_ = MARKING;
511
512 RecordWriteStub::Mode mode = is_compacting_ ?
513 RecordWriteStub::INCREMENTAL_COMPACTION : RecordWriteStub::INCREMENTAL;
514
515 PatchIncrementalMarkingRecordWriteStubs(heap_, mode);
516
517 EnsureMarkingDequeIsCommitted();
518
519 // Initialize marking stack.
520 Address addr = static_cast<Address>(marking_deque_memory_->address());
521 size_t size = marking_deque_memory_->size();
522 if (FLAG_force_marking_deque_overflows) size = 64 * kPointerSize;
523 marking_deque_.Initialize(addr, addr + size);
524
525 ActivateIncrementalWriteBarrier();
526
527#ifdef DEBUG
528 // Marking bits are cleared by the sweeper.
529 if (FLAG_verify_heap) {
530 heap_->mark_compact_collector()->VerifyMarkbitsAreClean();
531 }
532#endif
533
534 heap_->CompletelyClearInstanceofCache();
535 heap_->isolate()->compilation_cache()->MarkCompactPrologue();
536
537 if (FLAG_cleanup_code_caches_at_gc) {
538 // We will mark cache black with a separate pass
539 // when we finish marking.
540 MarkObjectGreyDoNotEnqueue(heap_->polymorphic_code_cache());
541 }
542
543 // Mark strong roots grey.
544 IncrementalMarkingRootMarkingVisitor visitor(heap_, this);
545 heap_->IterateStrongRoots(&visitor, VISIT_ONLY_STRONG);
546
547 // Ready to start incremental marking.
548 if (FLAG_trace_incremental_marking) {
549 PrintF("[IncrementalMarking] Running\n");
550 }
551}
552
553
554void IncrementalMarking::PrepareForScavenge() {
555 if (!IsMarking()) return;
556 NewSpacePageIterator it(heap_->new_space()->FromSpaceStart(),
557 heap_->new_space()->FromSpaceEnd());
558 while (it.has_next()) {
559 Bitmap::Clear(it.next());
560 }
561}
562
563
564void IncrementalMarking::UpdateMarkingDequeAfterScavenge() {
565 if (!IsMarking()) return;
566
567 int current = marking_deque_.bottom();
568 int mask = marking_deque_.mask();
569 int limit = marking_deque_.top();
570 HeapObject** array = marking_deque_.array();
571 int new_top = current;
572
573 Map* filler_map = heap_->one_pointer_filler_map();
574
575 while (current != limit) {
576 HeapObject* obj = array[current];
577 ASSERT(obj->IsHeapObject());
578 current = ((current + 1) & mask);
579 if (heap_->InNewSpace(obj)) {
580 MapWord map_word = obj->map_word();
581 if (map_word.IsForwardingAddress()) {
582 HeapObject* dest = map_word.ToForwardingAddress();
583 array[new_top] = dest;
584 new_top = ((new_top + 1) & mask);
585 ASSERT(new_top != marking_deque_.bottom());
586#ifdef DEBUG
587 MarkBit mark_bit = Marking::MarkBitFrom(obj);
588 ASSERT(Marking::IsGrey(mark_bit) ||
589 (obj->IsFiller() && Marking::IsWhite(mark_bit)));
590#endif
591 }
592 } else if (obj->map() != filler_map) {
593 // Skip one word filler objects that appear on the
594 // stack when we perform in place array shift.
595 array[new_top] = obj;
596 new_top = ((new_top + 1) & mask);
597 ASSERT(new_top != marking_deque_.bottom());
598#ifdef DEBUG
599 MarkBit mark_bit = Marking::MarkBitFrom(obj);
600 ASSERT(Marking::IsGrey(mark_bit) ||
601 (obj->IsFiller() && Marking::IsWhite(mark_bit)));
602#endif
603 }
604 }
605 marking_deque_.set_top(new_top);
606
607 steps_took_since_last_gc_ = 0;
608 steps_count_since_last_gc_ = 0;
609 longest_step_ = 0.0;
610}
611
612
613void IncrementalMarking::VisitGlobalContext(Context* ctx, ObjectVisitor* v) {
614 v->VisitPointers(
615 HeapObject::RawField(
616 ctx, Context::MarkCompactBodyDescriptor::kStartOffset),
617 HeapObject::RawField(
618 ctx, Context::MarkCompactBodyDescriptor::kEndOffset));
619
620 MarkCompactCollector* collector = heap_->mark_compact_collector();
621 for (int idx = Context::FIRST_WEAK_SLOT;
622 idx < Context::GLOBAL_CONTEXT_SLOTS;
623 ++idx) {
624 Object** slot =
625 HeapObject::RawField(ctx, FixedArray::OffsetOfElementAt(idx));
626 collector->RecordSlot(slot, slot, *slot);
627 }
628}
629
630
631void IncrementalMarking::Hurry() {
632 if (state() == MARKING) {
633 double start = 0.0;
634 if (FLAG_trace_incremental_marking) {
635 PrintF("[IncrementalMarking] Hurry\n");
636 start = OS::TimeCurrentMillis();
637 }
638 // TODO(gc) hurry can mark objects it encounters black as mutator
639 // was stopped.
640 Map* filler_map = heap_->one_pointer_filler_map();
641 Map* global_context_map = heap_->global_context_map();
642 IncrementalMarkingMarkingVisitor marking_visitor(heap_, this);
643 while (!marking_deque_.IsEmpty()) {
644 HeapObject* obj = marking_deque_.Pop();
645
646 // Explicitly skip one word fillers. Incremental markbit patterns are
647 // correct only for objects that occupy at least two words.
648 Map* map = obj->map();
649 if (map == filler_map) {
650 continue;
651 } else if (map == global_context_map) {
652 // Global contexts have weak fields.
653 VisitGlobalContext(Context::cast(obj), &marking_visitor);
654 } else {
655 obj->Iterate(&marking_visitor);
656 }
657
658 MarkBit mark_bit = Marking::MarkBitFrom(obj);
659 ASSERT(!Marking::IsBlack(mark_bit));
660 Marking::MarkBlack(mark_bit);
661 MemoryChunk::IncrementLiveBytes(obj->address(), obj->Size());
662 }
663 state_ = COMPLETE;
664 if (FLAG_trace_incremental_marking) {
665 double end = OS::TimeCurrentMillis();
666 PrintF("[IncrementalMarking] Complete (hurry), spent %d ms.\n",
667 static_cast<int>(end - start));
668 }
669 }
670
671 if (FLAG_cleanup_code_caches_at_gc) {
672 PolymorphicCodeCache* poly_cache = heap_->polymorphic_code_cache();
673 Marking::GreyToBlack(Marking::MarkBitFrom(poly_cache));
674 MemoryChunk::IncrementLiveBytes(poly_cache->address(),
675 PolymorphicCodeCache::kSize);
676 }
677
678 Object* context = heap_->global_contexts_list();
679 while (!context->IsUndefined()) {
680 // GC can happen when the context is not fully initialized,
681 // so the cache can be undefined.
682 HeapObject* cache = HeapObject::cast(
683 Context::cast(context)->get(Context::NORMALIZED_MAP_CACHE_INDEX));
684 if (!cache->IsUndefined()) {
685 MarkBit mark_bit = Marking::MarkBitFrom(cache);
686 if (Marking::IsGrey(mark_bit)) {
687 Marking::GreyToBlack(mark_bit);
688 MemoryChunk::IncrementLiveBytes(cache->address(), cache->Size());
689 }
690 }
691 context = Context::cast(context)->get(Context::NEXT_CONTEXT_LINK);
692 }
693}
694
695
696void IncrementalMarking::Abort() {
697 if (IsStopped()) return;
698 if (FLAG_trace_incremental_marking) {
699 PrintF("[IncrementalMarking] Aborting.\n");
700 }
701 heap_->new_space()->LowerInlineAllocationLimit(0);
702 IncrementalMarking::set_should_hurry(false);
703 ResetStepCounters();
704 if (IsMarking()) {
705 PatchIncrementalMarkingRecordWriteStubs(heap_,
706 RecordWriteStub::STORE_BUFFER_ONLY);
707 DeactivateIncrementalWriteBarrier();
708
709 if (is_compacting_) {
710 LargeObjectIterator it(heap_->lo_space());
711 for (HeapObject* obj = it.Next(); obj != NULL; obj = it.Next()) {
712 Page* p = Page::FromAddress(obj->address());
713 if (p->IsFlagSet(Page::RESCAN_ON_EVACUATION)) {
714 p->ClearFlag(Page::RESCAN_ON_EVACUATION);
715 }
716 }
717 }
718 }
719 heap_->isolate()->stack_guard()->Continue(GC_REQUEST);
720 state_ = STOPPED;
721 is_compacting_ = false;
722}
723
724
725void IncrementalMarking::Finalize() {
726 Hurry();
727 state_ = STOPPED;
728 is_compacting_ = false;
729 heap_->new_space()->LowerInlineAllocationLimit(0);
730 IncrementalMarking::set_should_hurry(false);
731 ResetStepCounters();
732 PatchIncrementalMarkingRecordWriteStubs(heap_,
733 RecordWriteStub::STORE_BUFFER_ONLY);
734 DeactivateIncrementalWriteBarrier();
735 ASSERT(marking_deque_.IsEmpty());
736 heap_->isolate()->stack_guard()->Continue(GC_REQUEST);
737}
738
739
740void IncrementalMarking::MarkingComplete() {
741 state_ = COMPLETE;
742 // We will set the stack guard to request a GC now. This will mean the rest
743 // of the GC gets performed as soon as possible (we can't do a GC here in a
744 // record-write context). If a few things get allocated between now and then
745 // that shouldn't make us do a scavenge and keep being incremental, so we set
746 // the should-hurry flag to indicate that there can't be much work left to do.
747 set_should_hurry(true);
748 if (FLAG_trace_incremental_marking) {
749 PrintF("[IncrementalMarking] Complete (normal).\n");
750 }
751 heap_->isolate()->stack_guard()->RequestGC();
752}
753
754
755void IncrementalMarking::Step(intptr_t allocated_bytes) {
756 if (heap_->gc_state() != Heap::NOT_IN_GC ||
757 !FLAG_incremental_marking ||
758 !FLAG_incremental_marking_steps ||
759 (state_ != SWEEPING && state_ != MARKING)) {
760 return;
761 }
762
763 allocated_ += allocated_bytes;
764
765 if (allocated_ < kAllocatedThreshold) return;
766
767 if (state_ == MARKING && no_marking_scope_depth_ > 0) return;
768
769 intptr_t bytes_to_process = allocated_ * allocation_marking_factor_;
770 bytes_scanned_ += bytes_to_process;
771
772 double start = 0;
773
774 if (FLAG_trace_incremental_marking || FLAG_trace_gc) {
775 start = OS::TimeCurrentMillis();
776 }
777
778 if (state_ == SWEEPING) {
779 if (heap_->old_pointer_space()->AdvanceSweeper(bytes_to_process) &&
780 heap_->old_data_space()->AdvanceSweeper(bytes_to_process)) {
781 bytes_scanned_ = 0;
782 StartMarking(PREVENT_COMPACTION);
783 }
784 } else if (state_ == MARKING) {
785 Map* filler_map = heap_->one_pointer_filler_map();
786 Map* global_context_map = heap_->global_context_map();
787 IncrementalMarkingMarkingVisitor marking_visitor(heap_, this);
788 while (!marking_deque_.IsEmpty() && bytes_to_process > 0) {
789 HeapObject* obj = marking_deque_.Pop();
790
791 // Explicitly skip one word fillers. Incremental markbit patterns are
792 // correct only for objects that occupy at least two words.
793 Map* map = obj->map();
794 if (map == filler_map) continue;
795
796 int size = obj->SizeFromMap(map);
797 bytes_to_process -= size;
798 MarkBit map_mark_bit = Marking::MarkBitFrom(map);
799 if (Marking::IsWhite(map_mark_bit)) {
800 WhiteToGreyAndPush(map, map_mark_bit);
801 }
802
803 // TODO(gc) switch to static visitor instead of normal visitor.
804 if (map == global_context_map) {
805 // Global contexts have weak fields.
806 Context* ctx = Context::cast(obj);
807
808 // We will mark cache black with a separate pass
809 // when we finish marking.
810 MarkObjectGreyDoNotEnqueue(ctx->normalized_map_cache());
811
812 VisitGlobalContext(ctx, &marking_visitor);
813 } else {
814 obj->IterateBody(map->instance_type(), size, &marking_visitor);
815 }
816
817 MarkBit obj_mark_bit = Marking::MarkBitFrom(obj);
818 SLOW_ASSERT(Marking::IsGrey(obj_mark_bit) ||
819 (obj->IsFiller() && Marking::IsWhite(obj_mark_bit)));
820 Marking::MarkBlack(obj_mark_bit);
821 MemoryChunk::IncrementLiveBytes(obj->address(), size);
822 }
823 if (marking_deque_.IsEmpty()) MarkingComplete();
824 }
825
826 allocated_ = 0;
827
828 steps_count_++;
829 steps_count_since_last_gc_++;
830
831 bool speed_up = false;
832
833 if ((steps_count_ % kAllocationMarkingFactorSpeedupInterval) == 0) {
834 if (FLAG_trace_gc) {
835 PrintF("Speed up marking after %d steps\n",
836 static_cast<int>(kAllocationMarkingFactorSpeedupInterval));
837 }
838 speed_up = true;
839 }
840
841 bool space_left_is_very_small =
842 (old_generation_space_available_at_start_of_incremental_ < 10 * MB);
843
844 bool only_1_nth_of_space_that_was_available_still_left =
845 (SpaceLeftInOldSpace() * (allocation_marking_factor_ + 1) <
846 old_generation_space_available_at_start_of_incremental_);
847
848 if (space_left_is_very_small ||
849 only_1_nth_of_space_that_was_available_still_left) {
850 if (FLAG_trace_gc) PrintF("Speed up marking because of low space left\n");
851 speed_up = true;
852 }
853
854 bool size_of_old_space_multiplied_by_n_during_marking =
855 (heap_->PromotedTotalSize() >
856 (allocation_marking_factor_ + 1) *
857 old_generation_space_used_at_start_of_incremental_);
858 if (size_of_old_space_multiplied_by_n_during_marking) {
859 speed_up = true;
860 if (FLAG_trace_gc) {
861 PrintF("Speed up marking because of heap size increase\n");
862 }
863 }
864
865 int64_t promoted_during_marking = heap_->PromotedTotalSize()
866 - old_generation_space_used_at_start_of_incremental_;
867 intptr_t delay = allocation_marking_factor_ * MB;
868 intptr_t scavenge_slack = heap_->MaxSemiSpaceSize();
869
870 // We try to scan at at least twice the speed that we are allocating.
871 if (promoted_during_marking > bytes_scanned_ / 2 + scavenge_slack + delay) {
872 if (FLAG_trace_gc) {
873 PrintF("Speed up marking because marker was not keeping up\n");
874 }
875 speed_up = true;
876 }
877
878 if (speed_up) {
879 if (state_ != MARKING) {
880 if (FLAG_trace_gc) {
881 PrintF("Postponing speeding up marking until marking starts\n");
882 }
883 } else {
884 allocation_marking_factor_ += kAllocationMarkingFactorSpeedup;
885 allocation_marking_factor_ = static_cast<int>(
886 Min(kMaxAllocationMarkingFactor,
887 static_cast<intptr_t>(allocation_marking_factor_ * 1.3)));
888 if (FLAG_trace_gc) {
889 PrintF("Marking speed increased to %d\n", allocation_marking_factor_);
890 }
891 }
892 }
893
894 if (FLAG_trace_incremental_marking || FLAG_trace_gc) {
895 double end = OS::TimeCurrentMillis();
896 double delta = (end - start);
897 longest_step_ = Max(longest_step_, delta);
898 steps_took_ += delta;
899 steps_took_since_last_gc_ += delta;
900 }
901}
902
903
904void IncrementalMarking::ResetStepCounters() {
905 steps_count_ = 0;
906 steps_took_ = 0;
907 longest_step_ = 0.0;
908 old_generation_space_available_at_start_of_incremental_ =
909 SpaceLeftInOldSpace();
910 old_generation_space_used_at_start_of_incremental_ =
911 heap_->PromotedTotalSize();
912 steps_count_since_last_gc_ = 0;
913 steps_took_since_last_gc_ = 0;
914 bytes_rescanned_ = 0;
915 allocation_marking_factor_ = kInitialAllocationMarkingFactor;
916 bytes_scanned_ = 0;
917}
918
919
920int64_t IncrementalMarking::SpaceLeftInOldSpace() {
921 return heap_->MaxOldGenerationSize() - heap_->PromotedSpaceSize();
922}
923
924} } // namespace v8::internal