blob: ab488d66486421cbd19a9d98089b7441ee8bbae6 [file] [log] [blame]
Mathieu Chartier590fee92013-09-13 13:46:47 -07001/*
2 * Copyright (C) 2013 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Mathieu Chartier590fee92013-09-13 13:46:47 -070017#include "semi_space.h"
18
19#include <functional>
20#include <numeric>
21#include <climits>
22#include <vector>
23
24#include "base/logging.h"
25#include "base/macros.h"
26#include "base/mutex-inl.h"
27#include "base/timing_logger.h"
28#include "gc/accounting/heap_bitmap.h"
29#include "gc/accounting/mod_union_table.h"
30#include "gc/accounting/space_bitmap-inl.h"
31#include "gc/heap.h"
32#include "gc/space/bump_pointer_space.h"
33#include "gc/space/bump_pointer_space-inl.h"
34#include "gc/space/image_space.h"
35#include "gc/space/large_object_space.h"
36#include "gc/space/space-inl.h"
37#include "indirect_reference_table.h"
38#include "intern_table.h"
39#include "jni_internal.h"
40#include "mark_sweep-inl.h"
41#include "monitor.h"
42#include "mirror/art_field.h"
43#include "mirror/art_field-inl.h"
44#include "mirror/class-inl.h"
45#include "mirror/class_loader.h"
46#include "mirror/dex_cache.h"
47#include "mirror/object-inl.h"
48#include "mirror/object_array.h"
49#include "mirror/object_array-inl.h"
50#include "runtime.h"
51#include "semi_space-inl.h"
52#include "thread-inl.h"
53#include "thread_list.h"
54#include "verifier/method_verifier.h"
55
56using ::art::mirror::Class;
57using ::art::mirror::Object;
58
59namespace art {
60namespace gc {
61namespace collector {
62
63static constexpr bool kProtectFromSpace = true;
64static constexpr bool kResetFromSpace = true;
65
66// TODO: Unduplicate logic.
67void SemiSpace::ImmuneSpace(space::ContinuousSpace* space) {
68 // Bind live to mark bitmap if necessary.
69 if (space->GetLiveBitmap() != space->GetMarkBitmap()) {
Mathieu Chartiera1602f22014-01-13 17:19:19 -080070 CHECK(space->IsContinuousMemMapAllocSpace());
71 space->AsContinuousMemMapAllocSpace()->BindLiveToMarkBitmap();
Mathieu Chartier590fee92013-09-13 13:46:47 -070072 }
73 // Add the space to the immune region.
74 if (immune_begin_ == nullptr) {
75 DCHECK(immune_end_ == nullptr);
76 immune_begin_ = reinterpret_cast<Object*>(space->Begin());
77 immune_end_ = reinterpret_cast<Object*>(space->End());
78 } else {
79 const space::ContinuousSpace* prev_space = nullptr;
80 // Find out if the previous space is immune.
81 for (space::ContinuousSpace* cur_space : GetHeap()->GetContinuousSpaces()) {
82 if (cur_space == space) {
83 break;
84 }
85 prev_space = cur_space;
86 }
87 // If previous space was immune, then extend the immune region. Relies on continuous spaces
88 // being sorted by Heap::AddContinuousSpace.
89 if (prev_space != nullptr && IsImmuneSpace(prev_space)) {
90 immune_begin_ = std::min(reinterpret_cast<Object*>(space->Begin()), immune_begin_);
Hiroshi Yamauchi6f4ffe42014-01-13 12:30:44 -080091 // Use Limit() instead of End() because otherwise if the
92 // generational mode is enabled, the alloc space might expand
93 // due to promotion and the sense of immunity may change in the
94 // middle of a GC.
Hiroshi Yamauchi05e713a2014-01-09 13:24:51 -080095 immune_end_ = std::max(reinterpret_cast<Object*>(space->Limit()), immune_end_);
Mathieu Chartier590fee92013-09-13 13:46:47 -070096 }
97 }
98}
99
100void SemiSpace::BindBitmaps() {
101 timings_.StartSplit("BindBitmaps");
Mathieu Chartiera1602f22014-01-13 17:19:19 -0800102 WriterMutexLock mu(self_, *Locks::heap_bitmap_lock_);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700103 // Mark all of the spaces we never collect as immune.
104 for (const auto& space : GetHeap()->GetContinuousSpaces()) {
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800105 if (space->GetLiveBitmap() != nullptr) {
106 if (space == to_space_) {
Mathieu Chartiera1602f22014-01-13 17:19:19 -0800107 CHECK(to_space_->IsContinuousMemMapAllocSpace());
108 to_space_->AsContinuousMemMapAllocSpace()->BindLiveToMarkBitmap();
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800109 } else if (space->GetGcRetentionPolicy() == space::kGcRetentionPolicyNeverCollect
Hiroshi Yamauchi05e713a2014-01-09 13:24:51 -0800110 || space->GetGcRetentionPolicy() == space::kGcRetentionPolicyFullCollect
111 // Add the main free list space and the non-moving
112 // space to the immune space if a bump pointer space
113 // only collection.
Hiroshi Yamauchi6f4ffe42014-01-13 12:30:44 -0800114 || (generational_ && !whole_heap_collection_ &&
115 (space == GetHeap()->GetNonMovingSpace() ||
116 space == GetHeap()->GetPrimaryFreeListSpace()))) {
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800117 ImmuneSpace(space);
118 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700119 }
120 }
Hiroshi Yamauchi6f4ffe42014-01-13 12:30:44 -0800121 if (generational_ && !whole_heap_collection_) {
Hiroshi Yamauchi05e713a2014-01-09 13:24:51 -0800122 // We won't collect the large object space if a bump pointer space only collection.
123 is_large_object_space_immune_ = true;
124 GetHeap()->GetLargeObjectsSpace()->CopyLiveToMarked();
125 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700126 timings_.EndSplit();
127}
128
Hiroshi Yamauchi6f4ffe42014-01-13 12:30:44 -0800129SemiSpace::SemiSpace(Heap* heap, bool generational, const std::string& name_prefix)
Mathieu Chartier590fee92013-09-13 13:46:47 -0700130 : GarbageCollector(heap,
131 name_prefix + (name_prefix.empty() ? "" : " ") + "marksweep + semispace"),
132 mark_stack_(nullptr),
133 immune_begin_(nullptr),
134 immune_end_(nullptr),
Hiroshi Yamauchi05e713a2014-01-09 13:24:51 -0800135 is_large_object_space_immune_(false),
Mathieu Chartier590fee92013-09-13 13:46:47 -0700136 to_space_(nullptr),
137 from_space_(nullptr),
Hiroshi Yamauchi4b1782f2013-12-05 16:46:22 -0800138 self_(nullptr),
Hiroshi Yamauchi6f4ffe42014-01-13 12:30:44 -0800139 generational_(generational),
Hiroshi Yamauchi4b1782f2013-12-05 16:46:22 -0800140 last_gc_to_space_end_(nullptr),
Hiroshi Yamauchi05e713a2014-01-09 13:24:51 -0800141 bytes_promoted_(0),
142 whole_heap_collection_(true),
143 whole_heap_collection_interval_counter_(0) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700144}
145
146void SemiSpace::InitializePhase() {
147 timings_.Reset();
Ian Rogers5fe9af72013-11-14 00:17:20 -0800148 TimingLogger::ScopedSplit split("InitializePhase", &timings_);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700149 mark_stack_ = heap_->mark_stack_.get();
150 DCHECK(mark_stack_ != nullptr);
151 immune_begin_ = nullptr;
152 immune_end_ = nullptr;
Hiroshi Yamauchi05e713a2014-01-09 13:24:51 -0800153 is_large_object_space_immune_ = false;
Mathieu Chartier590fee92013-09-13 13:46:47 -0700154 self_ = Thread::Current();
155 // Do any pre GC verification.
156 timings_.NewSplit("PreGcVerification");
157 heap_->PreGcVerification(this);
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800158 // Set the initial bitmap.
159 to_space_live_bitmap_ = to_space_->GetLiveBitmap();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700160}
161
162void SemiSpace::ProcessReferences(Thread* self) {
Ian Rogers5fe9af72013-11-14 00:17:20 -0800163 TimingLogger::ScopedSplit split("ProcessReferences", &timings_);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700164 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier39e32612013-11-12 16:28:05 -0800165 GetHeap()->ProcessReferences(timings_, clear_soft_references_, &MarkedForwardingAddressCallback,
166 &RecursiveMarkObjectCallback, this);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700167}
168
169void SemiSpace::MarkingPhase() {
Hiroshi Yamauchi6f4ffe42014-01-13 12:30:44 -0800170 if (generational_) {
171 if (gc_cause_ == kGcCauseExplicit || gc_cause_ == kGcCauseForNativeAlloc ||
172 clear_soft_references_) {
173 // If an explicit, native allocation-triggered, or last attempt
174 // collection, collect the whole heap (and reset the interval
175 // counter to be consistent.)
Hiroshi Yamauchi05e713a2014-01-09 13:24:51 -0800176 whole_heap_collection_ = true;
177 whole_heap_collection_interval_counter_ = 0;
178 }
179 if (whole_heap_collection_) {
180 VLOG(heap) << "Whole heap collection";
181 } else {
182 VLOG(heap) << "Bump pointer space only collection";
183 }
184 }
Mathieu Chartiera1602f22014-01-13 17:19:19 -0800185 Locks::mutator_lock_->AssertExclusiveHeld(self_);
Ian Rogers5fe9af72013-11-14 00:17:20 -0800186 TimingLogger::ScopedSplit split("MarkingPhase", &timings_);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700187 // Need to do this with mutators paused so that somebody doesn't accidentally allocate into the
188 // wrong space.
189 heap_->SwapSemiSpaces();
Hiroshi Yamauchi6f4ffe42014-01-13 12:30:44 -0800190 if (generational_) {
Hiroshi Yamauchi4b1782f2013-12-05 16:46:22 -0800191 // If last_gc_to_space_end_ is out of the bounds of the from-space
192 // (the to-space from last GC), then point it to the beginning of
193 // the from-space. For example, the very first GC or the
194 // pre-zygote compaction.
195 if (!from_space_->HasAddress(reinterpret_cast<mirror::Object*>(last_gc_to_space_end_))) {
196 last_gc_to_space_end_ = from_space_->Begin();
197 }
198 // Reset this before the marking starts below.
199 bytes_promoted_ = 0;
200 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700201 // Assume the cleared space is already empty.
202 BindBitmaps();
203 // Process dirty cards and add dirty cards to mod-union tables.
204 heap_->ProcessCards(timings_);
Mathieu Chartierc528dba2013-11-26 12:00:11 -0800205 // Clear the whole card table since we can not get any additional dirty cards during the
206 // paused GC. This saves memory but only works for pause the world collectors.
207 timings_.NewSplit("ClearCardTable");
208 heap_->GetCardTable()->ClearCardTable();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700209 // Need to do this before the checkpoint since we don't want any threads to add references to
210 // the live stack during the recursive mark.
211 timings_.NewSplit("SwapStacks");
212 heap_->SwapStacks();
Mathieu Chartiera1602f22014-01-13 17:19:19 -0800213 WriterMutexLock mu(self_, *Locks::heap_bitmap_lock_);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700214 MarkRoots();
215 // Mark roots of immune spaces.
216 UpdateAndMarkModUnion();
217 // Recursively mark remaining objects.
218 MarkReachableObjects();
219}
220
221bool SemiSpace::IsImmuneSpace(const space::ContinuousSpace* space) const {
222 return
223 immune_begin_ <= reinterpret_cast<Object*>(space->Begin()) &&
224 immune_end_ >= reinterpret_cast<Object*>(space->End());
225}
226
227void SemiSpace::UpdateAndMarkModUnion() {
228 for (auto& space : heap_->GetContinuousSpaces()) {
229 // If the space is immune then we need to mark the references to other spaces.
230 if (IsImmuneSpace(space)) {
231 accounting::ModUnionTable* table = heap_->FindModUnionTableFromSpace(space);
Hiroshi Yamauchi05e713a2014-01-09 13:24:51 -0800232 if (table != nullptr) {
233 // TODO: Improve naming.
234 TimingLogger::ScopedSplit split(
235 space->IsZygoteSpace() ? "UpdateAndMarkZygoteModUnionTable" :
236 "UpdateAndMarkImageModUnionTable",
237 &timings_);
238 table->UpdateAndMarkReferences(MarkRootCallback, this);
239 } else {
240 // If a bump pointer space only collection, the non-moving
241 // space is added to the immune space. But the non-moving
242 // space doesn't have a mod union table. Instead, its live
243 // bitmap will be scanned later in MarkReachableObjects().
Hiroshi Yamauchi6f4ffe42014-01-13 12:30:44 -0800244 DCHECK(generational_ && !whole_heap_collection_ &&
Hiroshi Yamauchi05e713a2014-01-09 13:24:51 -0800245 (space == heap_->GetNonMovingSpace() || space == heap_->GetPrimaryFreeListSpace()));
246 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700247 }
248 }
249}
250
Hiroshi Yamauchi05e713a2014-01-09 13:24:51 -0800251class SemiSpaceScanObjectVisitor {
252 public:
253 explicit SemiSpaceScanObjectVisitor(SemiSpace* ss) : semi_space_(ss) {}
254 void operator()(Object* obj) const NO_THREAD_SAFETY_ANALYSIS {
255 // TODO: fix NO_THREAD_SAFETY_ANALYSIS. ScanObject() requires an
256 // exclusive lock on the mutator lock, but
257 // SpaceBitmap::VisitMarkedRange() only requires the shared lock.
258 DCHECK(obj != nullptr);
259 semi_space_->ScanObject(obj);
260 }
261 private:
262 SemiSpace* semi_space_;
263};
264
Mathieu Chartier590fee92013-09-13 13:46:47 -0700265void SemiSpace::MarkReachableObjects() {
266 timings_.StartSplit("MarkStackAsLive");
267 accounting::ObjectStack* live_stack = heap_->GetLiveStack();
268 heap_->MarkAllocStackAsLive(live_stack);
269 live_stack->Reset();
270 timings_.EndSplit();
Hiroshi Yamauchi05e713a2014-01-09 13:24:51 -0800271
272 for (auto& space : heap_->GetContinuousSpaces()) {
273 // If the space is immune and has no mod union table (the
274 // non-moving space when the bump pointer space only collection is
275 // enabled,) then we need to scan its live bitmap as roots
276 // (including the objects on the live stack which have just marked
277 // in the live bitmap above in MarkAllocStackAsLive().)
278 if (IsImmuneSpace(space) && heap_->FindModUnionTableFromSpace(space) == nullptr) {
Hiroshi Yamauchi6f4ffe42014-01-13 12:30:44 -0800279 DCHECK(generational_ && !whole_heap_collection_ &&
Hiroshi Yamauchi05e713a2014-01-09 13:24:51 -0800280 (space == GetHeap()->GetNonMovingSpace() || space == GetHeap()->GetPrimaryFreeListSpace()));
281 accounting::SpaceBitmap* live_bitmap = space->GetLiveBitmap();
282 SemiSpaceScanObjectVisitor visitor(this);
283 live_bitmap->VisitMarkedRange(reinterpret_cast<uintptr_t>(space->Begin()),
284 reinterpret_cast<uintptr_t>(space->End()),
285 visitor);
286 }
287 }
288
289 if (is_large_object_space_immune_) {
Hiroshi Yamauchi6f4ffe42014-01-13 12:30:44 -0800290 DCHECK(generational_ && !whole_heap_collection_);
Hiroshi Yamauchi05e713a2014-01-09 13:24:51 -0800291 // When the large object space is immune, we need to scan the
292 // large object space as roots as they contain references to their
293 // classes (primitive array classes) that could move though they
294 // don't contain any other references.
295 space::LargeObjectSpace* large_object_space = GetHeap()->GetLargeObjectsSpace();
296 accounting::ObjectSet* large_live_objects = large_object_space->GetLiveObjects();
297 SemiSpaceScanObjectVisitor visitor(this);
298 for (const Object* obj : large_live_objects->GetObjects()) {
299 visitor(const_cast<Object*>(obj));
300 }
301 }
302
Mathieu Chartier590fee92013-09-13 13:46:47 -0700303 // Recursively process the mark stack.
304 ProcessMarkStack(true);
305}
306
307void SemiSpace::ReclaimPhase() {
Ian Rogers5fe9af72013-11-14 00:17:20 -0800308 TimingLogger::ScopedSplit split("ReclaimPhase", &timings_);
Mathieu Chartiera1602f22014-01-13 17:19:19 -0800309 ProcessReferences(self_);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700310 {
Mathieu Chartiera1602f22014-01-13 17:19:19 -0800311 ReaderMutexLock mu(self_, *Locks::heap_bitmap_lock_);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700312 SweepSystemWeaks();
313 }
314 // Record freed memory.
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800315 uint64_t from_bytes = from_space_->GetBytesAllocated();
316 uint64_t to_bytes = to_space_->GetBytesAllocated();
317 uint64_t from_objects = from_space_->GetObjectsAllocated();
318 uint64_t to_objects = to_space_->GetObjectsAllocated();
319 CHECK_LE(to_objects, from_objects);
320 int64_t freed_bytes = from_bytes - to_bytes;
321 int64_t freed_objects = from_objects - to_objects;
Ian Rogersb122a4b2013-11-19 18:00:50 -0800322 freed_bytes_.FetchAndAdd(freed_bytes);
323 freed_objects_.FetchAndAdd(freed_objects);
Mathieu Chartiere6da9af2013-12-16 11:54:42 -0800324 // Note: Freed bytes can be negative if we copy form a compacted space to a free-list backed
325 // space.
326 heap_->RecordFree(freed_objects, freed_bytes);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700327 timings_.StartSplit("PreSweepingGcVerification");
328 heap_->PreSweepingGcVerification(this);
329 timings_.EndSplit();
330
331 {
Mathieu Chartiera1602f22014-01-13 17:19:19 -0800332 WriterMutexLock mu(self_, *Locks::heap_bitmap_lock_);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700333 // Reclaim unmarked objects.
334 Sweep(false);
335 // Swap the live and mark bitmaps for each space which we modified space. This is an
336 // optimization that enables us to not clear live bits inside of the sweep. Only swaps unbound
337 // bitmaps.
338 timings_.StartSplit("SwapBitmaps");
339 SwapBitmaps();
340 timings_.EndSplit();
341 // Unbind the live and mark bitmaps.
Mathieu Chartiera1602f22014-01-13 17:19:19 -0800342 TimingLogger::ScopedSplit split("UnBindBitmaps", &timings_);
343 GetHeap()->UnBindBitmaps();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700344 }
345 // Release the memory used by the from space.
346 if (kResetFromSpace) {
347 // Clearing from space.
348 from_space_->Clear();
349 }
350 // Protect the from space.
351 VLOG(heap)
352 << "mprotect region " << reinterpret_cast<void*>(from_space_->Begin()) << " - "
353 << reinterpret_cast<void*>(from_space_->Limit());
354 if (kProtectFromSpace) {
355 mprotect(from_space_->Begin(), from_space_->Capacity(), PROT_NONE);
356 } else {
357 mprotect(from_space_->Begin(), from_space_->Capacity(), PROT_READ);
358 }
Hiroshi Yamauchi4b1782f2013-12-05 16:46:22 -0800359
Hiroshi Yamauchi6f4ffe42014-01-13 12:30:44 -0800360 if (generational_) {
Hiroshi Yamauchi4b1782f2013-12-05 16:46:22 -0800361 // Record the end (top) of the to space so we can distinguish
362 // between objects that were allocated since the last GC and the
363 // older objects.
364 last_gc_to_space_end_ = to_space_->End();
365 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700366}
367
368void SemiSpace::ResizeMarkStack(size_t new_size) {
369 std::vector<Object*> temp(mark_stack_->Begin(), mark_stack_->End());
370 CHECK_LE(mark_stack_->Size(), new_size);
371 mark_stack_->Resize(new_size);
372 for (const auto& obj : temp) {
373 mark_stack_->PushBack(obj);
374 }
375}
376
377inline void SemiSpace::MarkStackPush(Object* obj) {
378 if (UNLIKELY(mark_stack_->Size() >= mark_stack_->Capacity())) {
379 ResizeMarkStack(mark_stack_->Capacity() * 2);
380 }
381 // The object must be pushed on to the mark stack.
382 mark_stack_->PushBack(obj);
383}
384
385// Rare case, probably not worth inlining since it will increase instruction cache miss rate.
386bool SemiSpace::MarkLargeObject(const Object* obj) {
387 // TODO: support >1 discontinuous space.
388 space::LargeObjectSpace* large_object_space = GetHeap()->GetLargeObjectsSpace();
Hiroshi Yamauchi05e713a2014-01-09 13:24:51 -0800389 DCHECK(large_object_space->Contains(obj));
Mathieu Chartierdb7f37d2014-01-10 11:09:06 -0800390 accounting::ObjectSet* large_objects = large_object_space->GetMarkObjects();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700391 if (UNLIKELY(!large_objects->Test(obj))) {
392 large_objects->Set(obj);
393 return true;
394 }
395 return false;
396}
397
Mathieu Chartier85a43c02014-01-07 17:59:00 -0800398mirror::Object* SemiSpace::MarkNonForwardedObject(mirror::Object* obj) {
399 size_t object_size = obj->SizeOf();
Mathieu Chartier5dc08a62014-01-10 10:10:23 -0800400 size_t bytes_allocated;
Mathieu Chartier85a43c02014-01-07 17:59:00 -0800401 mirror::Object* forward_address = nullptr;
Hiroshi Yamauchi6f4ffe42014-01-13 12:30:44 -0800402 if (generational_ && reinterpret_cast<byte*>(obj) < last_gc_to_space_end_) {
Hiroshi Yamauchi05e713a2014-01-09 13:24:51 -0800403 // If it's allocated before the last GC (older), move
404 // (pseudo-promote) it to the main free list space (as sort
405 // of an old generation.)
Mathieu Chartier85a43c02014-01-07 17:59:00 -0800406 size_t bytes_promoted;
Hiroshi Yamauchi05e713a2014-01-09 13:24:51 -0800407 space::MallocSpace* promo_dest_space = GetHeap()->GetPrimaryFreeListSpace();
408 forward_address = promo_dest_space->Alloc(self_, object_size, &bytes_promoted);
Mathieu Chartier85a43c02014-01-07 17:59:00 -0800409 if (forward_address == nullptr) {
410 // If out of space, fall back to the to-space.
411 forward_address = to_space_->Alloc(self_, object_size, &bytes_allocated);
412 } else {
413 GetHeap()->num_bytes_allocated_.FetchAndAdd(bytes_promoted);
414 bytes_promoted_ += bytes_promoted;
Hiroshi Yamauchi05e713a2014-01-09 13:24:51 -0800415 // Handle the bitmaps marking.
416 accounting::SpaceBitmap* live_bitmap = promo_dest_space->GetLiveBitmap();
Mathieu Chartier85a43c02014-01-07 17:59:00 -0800417 DCHECK(live_bitmap != nullptr);
Hiroshi Yamauchi05e713a2014-01-09 13:24:51 -0800418 accounting::SpaceBitmap* mark_bitmap = promo_dest_space->GetMarkBitmap();
Mathieu Chartier85a43c02014-01-07 17:59:00 -0800419 DCHECK(mark_bitmap != nullptr);
Hiroshi Yamauchi05e713a2014-01-09 13:24:51 -0800420 DCHECK(!live_bitmap->Test(forward_address));
Hiroshi Yamauchi6f4ffe42014-01-13 12:30:44 -0800421 if (!whole_heap_collection_) {
Hiroshi Yamauchi05e713a2014-01-09 13:24:51 -0800422 // If collecting the bump pointer spaces only, live_bitmap == mark_bitmap.
423 DCHECK_EQ(live_bitmap, mark_bitmap);
424
Hiroshi Yamauchi6f4ffe42014-01-13 12:30:44 -0800425 // If a bump pointer space only collection, delay the live
426 // bitmap marking of the promoted object until it's popped off
427 // the mark stack (ProcessMarkStack()). The rationale: we may
428 // be in the middle of scanning the objects in the promo
429 // destination space for
Hiroshi Yamauchi05e713a2014-01-09 13:24:51 -0800430 // non-moving-space-to-bump-pointer-space references by
431 // iterating over the marked bits of the live bitmap
Hiroshi Yamauchi6f4ffe42014-01-13 12:30:44 -0800432 // (MarkReachableObjects()). If we don't delay it (and instead
433 // mark the promoted object here), the above promo destination
434 // space scan could encounter the just-promoted object and
435 // forward the references in the promoted object's fields even
436 // through it is pushed onto the mark stack. If this happens,
437 // the promoted object would be in an inconsistent state, that
438 // is, it's on the mark stack (gray) but its fields are
439 // already forwarded (black), which would cause a
Hiroshi Yamauchi05e713a2014-01-09 13:24:51 -0800440 // DCHECK(!to_space_->HasAddress(obj)) failure below.
441 } else {
442 // Mark forward_address on the live bit map.
443 live_bitmap->Set(forward_address);
444 // Mark forward_address on the mark bit map.
445 DCHECK(!mark_bitmap->Test(forward_address));
446 mark_bitmap->Set(forward_address);
447 }
Mathieu Chartier85a43c02014-01-07 17:59:00 -0800448 }
449 DCHECK(forward_address != nullptr);
450 } else {
451 // If it's allocated after the last GC (younger), copy it to the to-space.
452 forward_address = to_space_->Alloc(self_, object_size, &bytes_allocated);
453 }
454 // Copy over the object and add it to the mark stack since we still need to update its
455 // references.
456 memcpy(reinterpret_cast<void*>(forward_address), obj, object_size);
457 if (to_space_live_bitmap_ != nullptr) {
458 to_space_live_bitmap_->Set(forward_address);
459 }
Mathieu Chartier5dc08a62014-01-10 10:10:23 -0800460 DCHECK(to_space_->HasAddress(forward_address) ||
Hiroshi Yamauchi6f4ffe42014-01-13 12:30:44 -0800461 (generational_ && GetHeap()->GetPrimaryFreeListSpace()->HasAddress(forward_address)));
Mathieu Chartier85a43c02014-01-07 17:59:00 -0800462 return forward_address;
463}
464
Mathieu Chartier590fee92013-09-13 13:46:47 -0700465// Used to mark and copy objects. Any newly-marked objects who are in the from space get moved to
466// the to-space and have their forward address updated. Objects which have been newly marked are
467// pushed on the mark stack.
468Object* SemiSpace::MarkObject(Object* obj) {
Mathieu Chartier85a43c02014-01-07 17:59:00 -0800469 Object* forward_address = obj;
Mathieu Chartier590fee92013-09-13 13:46:47 -0700470 if (obj != nullptr && !IsImmune(obj)) {
471 if (from_space_->HasAddress(obj)) {
Mathieu Chartier85a43c02014-01-07 17:59:00 -0800472 forward_address = GetForwardingAddressInFromSpace(obj);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700473 // If the object has already been moved, return the new forward address.
Hiroshi Yamauchi4b1782f2013-12-05 16:46:22 -0800474 if (forward_address == nullptr) {
Mathieu Chartier85a43c02014-01-07 17:59:00 -0800475 forward_address = MarkNonForwardedObject(obj);
476 DCHECK(forward_address != nullptr);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700477 // Make sure to only update the forwarding address AFTER you copy the object so that the
478 // monitor word doesn't get stomped over.
Mathieu Chartier85a43c02014-01-07 17:59:00 -0800479 obj->SetLockWord(LockWord::FromForwardingAddress(
480 reinterpret_cast<size_t>(forward_address)));
481 // Push the object onto the mark stack for later processing.
Mathieu Chartier590fee92013-09-13 13:46:47 -0700482 MarkStackPush(forward_address);
483 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700484 // TODO: Do we need this if in the else statement?
485 } else {
486 accounting::SpaceBitmap* object_bitmap = heap_->GetMarkBitmap()->GetContinuousSpaceBitmap(obj);
487 if (LIKELY(object_bitmap != nullptr)) {
Hiroshi Yamauchi6f4ffe42014-01-13 12:30:44 -0800488 if (generational_) {
Hiroshi Yamauchi05e713a2014-01-09 13:24:51 -0800489 // If a bump pointer space only collection, we should not
490 // reach here as we don't/won't mark the objects in the
491 // non-moving space (except for the promoted objects.) Note
492 // the non-moving space is added to the immune space.
493 DCHECK(whole_heap_collection_);
494 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700495 // This object was not previously marked.
496 if (!object_bitmap->Test(obj)) {
497 object_bitmap->Set(obj);
498 MarkStackPush(obj);
499 }
500 } else {
501 DCHECK(!to_space_->HasAddress(obj)) << "Marking object in to_space_";
502 if (MarkLargeObject(obj)) {
503 MarkStackPush(obj);
504 }
505 }
506 }
507 }
Mathieu Chartier85a43c02014-01-07 17:59:00 -0800508 return forward_address;
Mathieu Chartier590fee92013-09-13 13:46:47 -0700509}
510
Mathieu Chartier39e32612013-11-12 16:28:05 -0800511Object* SemiSpace::RecursiveMarkObjectCallback(Object* root, void* arg) {
512 DCHECK(root != nullptr);
513 DCHECK(arg != nullptr);
514 SemiSpace* semi_space = reinterpret_cast<SemiSpace*>(arg);
515 mirror::Object* ret = semi_space->MarkObject(root);
516 semi_space->ProcessMarkStack(true);
517 return ret;
518}
519
Mathieu Chartier590fee92013-09-13 13:46:47 -0700520Object* SemiSpace::MarkRootCallback(Object* root, void* arg) {
521 DCHECK(root != nullptr);
522 DCHECK(arg != nullptr);
523 return reinterpret_cast<SemiSpace*>(arg)->MarkObject(root);
524}
525
526// Marks all objects in the root set.
527void SemiSpace::MarkRoots() {
528 timings_.StartSplit("MarkRoots");
529 // TODO: Visit up image roots as well?
530 Runtime::Current()->VisitRoots(MarkRootCallback, this, false, true);
531 timings_.EndSplit();
532}
533
Mathieu Chartier39e32612013-11-12 16:28:05 -0800534mirror::Object* SemiSpace::MarkedForwardingAddressCallback(Object* object, void* arg) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700535 return reinterpret_cast<SemiSpace*>(arg)->GetMarkedForwardAddress(object);
536}
537
538void SemiSpace::SweepSystemWeaks() {
539 timings_.StartSplit("SweepSystemWeaks");
Mathieu Chartier39e32612013-11-12 16:28:05 -0800540 Runtime::Current()->SweepSystemWeaks(MarkedForwardingAddressCallback, this);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700541 timings_.EndSplit();
542}
543
Mathieu Chartiera1602f22014-01-13 17:19:19 -0800544bool SemiSpace::ShouldSweepSpace(space::ContinuousSpace* space) const {
Hiroshi Yamauchi05e713a2014-01-09 13:24:51 -0800545 return space != from_space_ && space != to_space_ && !IsImmuneSpace(space);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700546}
547
548void SemiSpace::Sweep(bool swap_bitmaps) {
549 DCHECK(mark_stack_->IsEmpty());
Ian Rogers5fe9af72013-11-14 00:17:20 -0800550 TimingLogger::ScopedSplit("Sweep", &timings_);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700551 for (const auto& space : GetHeap()->GetContinuousSpaces()) {
Mathieu Chartiera1602f22014-01-13 17:19:19 -0800552 if (space->IsContinuousMemMapAllocSpace()) {
553 space::ContinuousMemMapAllocSpace* alloc_space = space->AsContinuousMemMapAllocSpace();
554 if (!ShouldSweepSpace(alloc_space)) {
Mathieu Chartier85a43c02014-01-07 17:59:00 -0800555 continue;
556 }
Mathieu Chartierec050072014-01-07 16:00:07 -0800557 TimingLogger::ScopedSplit split(
Mathieu Chartiera1602f22014-01-13 17:19:19 -0800558 alloc_space->IsZygoteSpace() ? "SweepZygoteSpace" : "SweepAllocSpace", &timings_);
Mathieu Chartierec050072014-01-07 16:00:07 -0800559 size_t freed_objects = 0;
560 size_t freed_bytes = 0;
Mathieu Chartiera1602f22014-01-13 17:19:19 -0800561 alloc_space->Sweep(swap_bitmaps, &freed_objects, &freed_bytes);
Mathieu Chartierec050072014-01-07 16:00:07 -0800562 heap_->RecordFree(freed_objects, freed_bytes);
563 freed_objects_.FetchAndAdd(freed_objects);
564 freed_bytes_.FetchAndAdd(freed_bytes);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700565 }
566 }
Hiroshi Yamauchi05e713a2014-01-09 13:24:51 -0800567 if (!is_large_object_space_immune_) {
568 SweepLargeObjects(swap_bitmaps);
569 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700570}
571
572void SemiSpace::SweepLargeObjects(bool swap_bitmaps) {
Hiroshi Yamauchi05e713a2014-01-09 13:24:51 -0800573 DCHECK(!is_large_object_space_immune_);
Ian Rogers5fe9af72013-11-14 00:17:20 -0800574 TimingLogger::ScopedSplit("SweepLargeObjects", &timings_);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700575 size_t freed_objects = 0;
576 size_t freed_bytes = 0;
Mathieu Chartierdb7f37d2014-01-10 11:09:06 -0800577 GetHeap()->GetLargeObjectsSpace()->Sweep(swap_bitmaps, &freed_objects, &freed_bytes);
Ian Rogersb122a4b2013-11-19 18:00:50 -0800578 freed_large_objects_.FetchAndAdd(freed_objects);
579 freed_large_object_bytes_.FetchAndAdd(freed_bytes);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700580 GetHeap()->RecordFree(freed_objects, freed_bytes);
581}
582
583// Process the "referent" field in a java.lang.ref.Reference. If the referent has not yet been
584// marked, put it on the appropriate list in the heap for later processing.
585void SemiSpace::DelayReferenceReferent(mirror::Class* klass, Object* obj) {
Mathieu Chartier39e32612013-11-12 16:28:05 -0800586 heap_->DelayReferenceReferent(klass, obj, MarkedForwardingAddressCallback, this);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700587}
588
589// Visit all of the references of an object and update.
590void SemiSpace::ScanObject(Object* obj) {
591 DCHECK(obj != NULL);
592 DCHECK(!from_space_->HasAddress(obj)) << "Scanning object " << obj << " in from space";
593 MarkSweep::VisitObjectReferences(obj, [this](Object* obj, Object* ref, const MemberOffset& offset,
Bernhard Rosenkränzer46053622013-12-12 02:15:52 +0100594 bool /* is_static */) ALWAYS_INLINE_LAMBDA NO_THREAD_SAFETY_ANALYSIS {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700595 mirror::Object* new_address = MarkObject(ref);
596 if (new_address != ref) {
597 DCHECK(new_address != nullptr);
Mathieu Chartierc528dba2013-11-26 12:00:11 -0800598 // Don't need to mark the card since we updating the object address and not changing the
599 // actual objects its pointing to. Using SetFieldPtr is better in this case since it does not
600 // dirty cards and use additional memory.
601 obj->SetFieldPtr(offset, new_address, false);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700602 }
603 }, kMovingClasses);
604 mirror::Class* klass = obj->GetClass();
605 if (UNLIKELY(klass->IsReferenceClass())) {
606 DelayReferenceReferent(klass, obj);
607 }
608}
609
610// Scan anything that's on the mark stack.
611void SemiSpace::ProcessMarkStack(bool paused) {
Hiroshi Yamauchi05e713a2014-01-09 13:24:51 -0800612 space::MallocSpace* promo_dest_space = NULL;
613 accounting::SpaceBitmap* live_bitmap = NULL;
Hiroshi Yamauchi6f4ffe42014-01-13 12:30:44 -0800614 if (generational_ && !whole_heap_collection_) {
Hiroshi Yamauchi05e713a2014-01-09 13:24:51 -0800615 // If a bump pointer space only collection (and the promotion is
616 // enabled,) we delay the live-bitmap marking of promoted objects
617 // from MarkObject() until this function.
618 promo_dest_space = GetHeap()->GetPrimaryFreeListSpace();
619 live_bitmap = promo_dest_space->GetLiveBitmap();
620 DCHECK(live_bitmap != nullptr);
621 accounting::SpaceBitmap* mark_bitmap = promo_dest_space->GetMarkBitmap();
622 DCHECK(mark_bitmap != nullptr);
623 DCHECK_EQ(live_bitmap, mark_bitmap);
624 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700625 timings_.StartSplit(paused ? "(paused)ProcessMarkStack" : "ProcessMarkStack");
626 while (!mark_stack_->IsEmpty()) {
Hiroshi Yamauchi05e713a2014-01-09 13:24:51 -0800627 Object* obj = mark_stack_->PopBack();
Hiroshi Yamauchi6f4ffe42014-01-13 12:30:44 -0800628 if (generational_ && !whole_heap_collection_ && promo_dest_space->HasAddress(obj)) {
Hiroshi Yamauchi05e713a2014-01-09 13:24:51 -0800629 // obj has just been promoted. Mark the live bitmap for it,
630 // which is delayed from MarkObject().
631 DCHECK(!live_bitmap->Test(obj));
632 live_bitmap->Set(obj);
633 }
634 ScanObject(obj);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700635 }
636 timings_.EndSplit();
637}
638
Mathieu Chartier590fee92013-09-13 13:46:47 -0700639inline Object* SemiSpace::GetMarkedForwardAddress(mirror::Object* obj) const
640 SHARED_LOCKS_REQUIRED(Locks::heap_bitmap_lock_) {
641 // All immune objects are assumed marked.
642 if (IsImmune(obj)) {
643 return obj;
644 }
645 if (from_space_->HasAddress(obj)) {
646 mirror::Object* forwarding_address = GetForwardingAddressInFromSpace(const_cast<Object*>(obj));
Mathieu Chartier85a43c02014-01-07 17:59:00 -0800647 return forwarding_address; // Returns either the forwarding address or nullptr.
Mathieu Chartier590fee92013-09-13 13:46:47 -0700648 } else if (to_space_->HasAddress(obj)) {
Mathieu Chartier85a43c02014-01-07 17:59:00 -0800649 // Should be unlikely.
Mathieu Chartier590fee92013-09-13 13:46:47 -0700650 // Already forwarded, must be marked.
651 return obj;
652 }
653 return heap_->GetMarkBitmap()->Test(obj) ? obj : nullptr;
654}
655
Mathieu Chartier590fee92013-09-13 13:46:47 -0700656void SemiSpace::SetToSpace(space::ContinuousMemMapAllocSpace* to_space) {
657 DCHECK(to_space != nullptr);
658 to_space_ = to_space;
659}
660
661void SemiSpace::SetFromSpace(space::ContinuousMemMapAllocSpace* from_space) {
662 DCHECK(from_space != nullptr);
663 from_space_ = from_space;
664}
665
666void SemiSpace::FinishPhase() {
Ian Rogers5fe9af72013-11-14 00:17:20 -0800667 TimingLogger::ScopedSplit split("FinishPhase", &timings_);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700668 Heap* heap = GetHeap();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700669 timings_.NewSplit("PostGcVerification");
670 heap->PostGcVerification(this);
671
672 // Null the "to" and "from" spaces since compacting from one to the other isn't valid until
673 // further action is done by the heap.
674 to_space_ = nullptr;
675 from_space_ = nullptr;
676
677 // Update the cumulative statistics
Mathieu Chartier590fee92013-09-13 13:46:47 -0700678 total_freed_objects_ += GetFreedObjects() + GetFreedLargeObjects();
679 total_freed_bytes_ += GetFreedBytes() + GetFreedLargeObjectBytes();
680
681 // Ensure that the mark stack is empty.
682 CHECK(mark_stack_->IsEmpty());
683
684 // Update the cumulative loggers.
685 cumulative_timings_.Start();
686 cumulative_timings_.AddLogger(timings_);
687 cumulative_timings_.End();
688
689 // Clear all of the spaces' mark bitmaps.
690 for (const auto& space : GetHeap()->GetContinuousSpaces()) {
691 accounting::SpaceBitmap* bitmap = space->GetMarkBitmap();
692 if (bitmap != nullptr &&
693 space->GetGcRetentionPolicy() != space::kGcRetentionPolicyNeverCollect) {
694 bitmap->Clear();
695 }
696 }
697 mark_stack_->Reset();
698
699 // Reset the marked large objects.
700 space::LargeObjectSpace* large_objects = GetHeap()->GetLargeObjectsSpace();
701 large_objects->GetMarkObjects()->Clear();
Hiroshi Yamauchi05e713a2014-01-09 13:24:51 -0800702
Hiroshi Yamauchi6f4ffe42014-01-13 12:30:44 -0800703 if (generational_) {
Hiroshi Yamauchi05e713a2014-01-09 13:24:51 -0800704 // Decide whether to do a whole heap collection or a bump pointer
705 // only space collection at the next collection by updating
706 // whole_heap_collection. Enable whole_heap_collection once every
707 // kDefaultWholeHeapCollectionInterval collections.
708 if (!whole_heap_collection_) {
709 --whole_heap_collection_interval_counter_;
710 DCHECK_GE(whole_heap_collection_interval_counter_, 0);
711 if (whole_heap_collection_interval_counter_ == 0) {
712 whole_heap_collection_ = true;
713 }
714 } else {
715 DCHECK_EQ(whole_heap_collection_interval_counter_, 0);
716 whole_heap_collection_interval_counter_ = kDefaultWholeHeapCollectionInterval;
717 whole_heap_collection_ = false;
718 }
719 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700720}
721
722} // namespace collector
723} // namespace gc
724} // namespace art