1 /*
   2  * Copyright (c) 2014, 2021, Red Hat, Inc. All rights reserved.
   3  * Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
   4  * Copyright (c) 2025, Oracle and/or its affiliates. All rights reserved.
   5  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   6  *
   7  * This code is free software; you can redistribute it and/or modify it
   8  * under the terms of the GNU General Public License version 2 only, as
   9  * published by the Free Software Foundation.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  *
  25  */
  26 
  27 
  28 #include "compiler/oopMap.hpp"
  29 #include "gc/shared/continuationGCSupport.hpp"
  30 #include "gc/shared/fullGCForwarding.inline.hpp"
  31 #include "gc/shared/gcTraceTime.inline.hpp"
  32 #include "gc/shared/preservedMarks.inline.hpp"
  33 #include "gc/shared/tlab_globals.hpp"
  34 #include "gc/shared/workerThread.hpp"
  35 #include "gc/shenandoah/heuristics/shenandoahHeuristics.hpp"
  36 #include "gc/shenandoah/shenandoahClosures.inline.hpp"
  37 #include "gc/shenandoah/shenandoahCollectionSet.hpp"
  38 #include "gc/shenandoah/shenandoahCollectorPolicy.hpp"
  39 #include "gc/shenandoah/shenandoahConcurrentGC.hpp"
  40 #include "gc/shenandoah/shenandoahFreeSet.hpp"
  41 #include "gc/shenandoah/shenandoahFullGC.hpp"
  42 #include "gc/shenandoah/shenandoahGenerationalFullGC.hpp"
  43 #include "gc/shenandoah/shenandoahGlobalGeneration.hpp"
  44 #include "gc/shenandoah/shenandoahHeap.inline.hpp"
  45 #include "gc/shenandoah/shenandoahHeapRegion.inline.hpp"
  46 #include "gc/shenandoah/shenandoahHeapRegionClosures.hpp"
  47 #include "gc/shenandoah/shenandoahHeapRegionSet.hpp"
  48 #include "gc/shenandoah/shenandoahMark.inline.hpp"
  49 #include "gc/shenandoah/shenandoahMarkingContext.inline.hpp"
  50 #include "gc/shenandoah/shenandoahMetrics.hpp"
  51 #include "gc/shenandoah/shenandoahMonitoringSupport.hpp"
  52 #include "gc/shenandoah/shenandoahPhaseTimings.hpp"
  53 #include "gc/shenandoah/shenandoahReferenceProcessor.hpp"
  54 #include "gc/shenandoah/shenandoahRootProcessor.inline.hpp"
  55 #include "gc/shenandoah/shenandoahStackWatermark.hpp"
  56 #include "gc/shenandoah/shenandoahSTWMark.hpp"
  57 #include "gc/shenandoah/shenandoahUtils.hpp"
  58 #include "gc/shenandoah/shenandoahVerifier.hpp"
  59 #include "gc/shenandoah/shenandoahVMOperations.hpp"
  60 #include "gc/shenandoah/shenandoahWorkerPolicy.hpp"
  61 #include "memory/metaspaceUtils.hpp"
  62 #include "memory/universe.hpp"
  63 #include "oops/compressedOops.inline.hpp"
  64 #include "oops/oop.inline.hpp"
  65 #include "runtime/orderAccess.hpp"
  66 #include "runtime/vmThread.hpp"
  67 #include "utilities/copy.hpp"
  68 #include "utilities/events.hpp"
  69 #include "utilities/growableArray.hpp"
  70 
  71 ShenandoahFullGC::ShenandoahFullGC() :
  72   ShenandoahGC(ShenandoahHeap::heap()->global_generation()),
  73   _gc_timer(ShenandoahHeap::heap()->gc_timer()),
  74   _preserved_marks(new PreservedMarksSet(true)) {}
  75 
  76 ShenandoahFullGC::~ShenandoahFullGC() {
  77   delete _preserved_marks;
  78 }
  79 
  80 bool ShenandoahFullGC::collect(GCCause::Cause cause) {
  81   vmop_entry_full(cause);
  82   // Always success
  83   return true;
  84 }
  85 
  86 void ShenandoahFullGC::vmop_entry_full(GCCause::Cause cause) {
  87   ShenandoahHeap* const heap = ShenandoahHeap::heap();
  88   TraceCollectorStats tcs(heap->monitoring_support()->full_stw_collection_counters());
  89   ShenandoahTimingsTracker timing(ShenandoahPhaseTimings::full_gc_gross);
  90 
  91   heap->try_inject_alloc_failure();
  92   VM_ShenandoahFullGC op(cause, this);
  93   VMThread::execute(&op);
  94 }
  95 
  96 void ShenandoahFullGC::entry_full(GCCause::Cause cause) {
  97   static const char* msg = "Pause Full";
  98   ShenandoahPausePhase gc_phase(msg, ShenandoahPhaseTimings::full_gc, true /* log_heap_usage */);
  99   EventMark em("%s", msg);
 100 
 101   ShenandoahWorkerScope scope(ShenandoahHeap::heap()->workers(),
 102                               ShenandoahWorkerPolicy::calc_workers_for_fullgc(),
 103                               "full gc");
 104 
 105   op_full(cause);
 106 }
 107 
 108 void ShenandoahFullGC::op_full(GCCause::Cause cause) {
 109   ShenandoahHeap* const heap = ShenandoahHeap::heap();
 110 
 111   ShenandoahMetricsSnapshot metrics(heap->free_set());
 112 
 113   // Perform full GC
 114   do_it(cause);
 115 
 116   if (heap->mode()->is_generational()) {
 117     ShenandoahGenerationalFullGC::handle_completion(heap);
 118   }
 119 
 120   if (metrics.is_good_progress()) {
 121     heap->notify_gc_progress();
 122   } else {
 123     // Nothing to do. Tell the allocation path that we have failed to make
 124     // progress, and it can finally fail.
 125     heap->notify_gc_no_progress();
 126   }
 127 
 128   // Regardless if progress was made, we record that we completed a "successful" full GC.
 129   _generation->heuristics()->record_success_full();
 130   heap->shenandoah_policy()->record_success_full();
 131 
 132   if (ShenandoahGCStateCheckHotpatch) {
 133     // Leaving full GC, we need to flip barriers back to idle.
 134     ShenandoahCodeRoots::arm_nmethods();
 135     ShenandoahStackWatermark::change_epoch_id();
 136   }
 137 
 138   {
 139     ShenandoahTimingsTracker timing(ShenandoahPhaseTimings::full_gc_propagate_gc_state);
 140     heap->propagate_gc_state_to_all_threads();
 141   }
 142 }
 143 
 144 void ShenandoahFullGC::do_it(GCCause::Cause gc_cause) {
 145   ShenandoahHeap* heap = ShenandoahHeap::heap();
 146 
 147   if (heap->mode()->is_generational()) {
 148     ShenandoahGenerationalFullGC::prepare();
 149   }
 150 
 151   if (ShenandoahVerify) {
 152     heap->verifier()->verify_before_fullgc(_generation);
 153   }
 154 
 155   if (VerifyBeforeGC) {
 156     Universe::verify();
 157   }
 158 
 159   // Degenerated GC may carry concurrent root flags when upgrading to
 160   // full GC. We need to reset it before mutators resume.
 161   heap->set_concurrent_strong_root_in_progress(false);
 162   heap->set_concurrent_weak_root_in_progress(false);
 163 
 164   heap->set_full_gc_in_progress(true);
 165 
 166   assert(ShenandoahSafepoint::is_at_shenandoah_safepoint(), "must be at a safepoint");
 167   assert(Thread::current()->is_VM_thread(), "Do full GC only while world is stopped");
 168 
 169   {
 170     ShenandoahGCPhase phase(ShenandoahPhaseTimings::full_gc_heapdump_pre);
 171     heap->pre_full_gc_dump(_gc_timer);
 172   }
 173 
 174   {
 175     ShenandoahGCPhase prepare_phase(ShenandoahPhaseTimings::full_gc_prepare);
 176     // Full GC is supposed to recover from any GC state:
 177 
 178     // a0. Remember if we have forwarded objects
 179     bool has_forwarded_objects = heap->has_forwarded_objects();
 180 
 181     // a1. Cancel evacuation, if in progress
 182     if (heap->is_evacuation_in_progress()) {
 183       heap->set_evacuation_in_progress(false);
 184     }
 185     assert(!heap->is_evacuation_in_progress(), "sanity");
 186 
 187     // a2. Cancel update-refs, if in progress
 188     if (heap->is_update_refs_in_progress()) {
 189       heap->set_update_refs_in_progress(false);
 190     }
 191     assert(!heap->is_update_refs_in_progress(), "sanity");
 192 
 193     // b. Cancel all concurrent marks, if in progress
 194     if (heap->is_concurrent_mark_in_progress()) {
 195       heap->cancel_concurrent_mark();
 196     }
 197     assert(!heap->is_concurrent_mark_in_progress(), "sanity");
 198 
 199     // c. Update roots if this full GC is due to evac-oom, which may carry from-space pointers in roots.
 200     if (has_forwarded_objects) {
 201       update_roots(true /*full_gc*/);
 202     }
 203 
 204     // d. Abandon reference discovery and clear all discovered references.
 205     ShenandoahReferenceProcessor* rp = _generation->ref_processor();
 206     rp->abandon_partial_discovery();
 207 
 208     // e. Sync pinned region status from the CP marks
 209     heap->sync_pinned_region_status();
 210 
 211     if (heap->mode()->is_generational()) {
 212       ShenandoahGenerationalFullGC::restore_top_before_promote(heap);
 213     }
 214 
 215     // The rest of prologue:
 216     _preserved_marks->init(heap->workers()->active_workers());
 217 
 218     assert(heap->has_forwarded_objects() == has_forwarded_objects, "This should not change");
 219   }
 220 
 221   if (UseTLAB) {
 222     // Note: PLABs are also retired with GCLABs in generational mode.
 223     heap->gclabs_retire(ResizeTLAB);
 224     heap->tlabs_retire(ResizeTLAB);
 225   }
 226 
 227   OrderAccess::fence();
 228 
 229   phase1_mark_heap();
 230 
 231   // Once marking is done, which may have fixed up forwarded objects, we can drop it.
 232   // Coming out of Full GC, we would not have any forwarded objects.
 233   // This also prevents resolves with fwdptr from kicking in while adjusting pointers in phase3.
 234   heap->set_has_forwarded_objects(false);
 235 
 236   heap->set_full_gc_move_in_progress(true);
 237 
 238   // Setup workers for the rest
 239   OrderAccess::fence();
 240 
 241   // Initialize worker slices
 242   ShenandoahHeapRegionSet** worker_slices = NEW_C_HEAP_ARRAY(ShenandoahHeapRegionSet*, heap->max_workers(), mtGC);
 243   for (uint i = 0; i < heap->max_workers(); i++) {
 244     worker_slices[i] = new ShenandoahHeapRegionSet();
 245   }
 246 
 247   {
 248     // The rest of code performs region moves, where region status is undefined
 249     // until all phases run together.
 250     ShenandoahHeapLocker lock(heap->lock());
 251 
 252     phase2_calculate_target_addresses(worker_slices);
 253 
 254     OrderAccess::fence();
 255 
 256     phase3_update_references();
 257 
 258     phase4_compact_objects(worker_slices);
 259 
 260     phase5_epilog();
 261   }
 262   heap->start_idle_span();
 263 
 264   // Resize metaspace
 265   MetaspaceGC::compute_new_size();
 266 
 267   // Free worker slices
 268   for (uint i = 0; i < heap->max_workers(); i++) {
 269     delete worker_slices[i];
 270   }
 271   FREE_C_HEAP_ARRAY(ShenandoahHeapRegionSet*, worker_slices);
 272 
 273   heap->set_full_gc_move_in_progress(false);
 274   heap->set_full_gc_in_progress(false);
 275 
 276   if (ShenandoahVerify) {
 277     heap->verifier()->verify_after_fullgc(_generation);
 278   }
 279 
 280   if (VerifyAfterGC) {
 281     Universe::verify();
 282   }
 283 
 284   {
 285     ShenandoahGCPhase phase(ShenandoahPhaseTimings::full_gc_heapdump_post);
 286     heap->post_full_gc_dump(_gc_timer);
 287   }
 288 }
 289 
 290 void ShenandoahFullGC::phase1_mark_heap() {
 291   GCTraceTime(Info, gc, phases) time("Phase 1: Mark live objects", _gc_timer);
 292   ShenandoahGCPhase mark_phase(ShenandoahPhaseTimings::full_gc_mark);
 293 
 294   ShenandoahHeap* heap = ShenandoahHeap::heap();
 295 
 296   _generation->reset_mark_bitmap<true, true>();
 297   assert(heap->marking_context()->is_bitmap_clear(), "sanity");
 298   assert(!_generation->is_mark_complete(), "sanity");
 299 
 300   heap->set_unload_classes(_generation->heuristics()->can_unload_classes());
 301 
 302   ShenandoahReferenceProcessor* rp = _generation->ref_processor();
 303   // enable ("weak") refs discovery
 304   rp->set_soft_reference_policy(true); // forcefully purge all soft references
 305 
 306   ShenandoahSTWMark mark(_generation, true /*full_gc*/);
 307   mark.mark();
 308   heap->parallel_cleaning(_generation, true /* full_gc */);
 309 
 310   if (ShenandoahHeap::heap()->mode()->is_generational()) {
 311     ShenandoahGenerationalFullGC::log_live_in_old(heap);
 312   }
 313 }
 314 
 315 class ShenandoahPrepareForCompactionObjectClosure : public ObjectClosure {
 316 private:
 317   PreservedMarks*          const _preserved_marks;
 318   ShenandoahHeap*          const _heap;
 319   GrowableArray<ShenandoahHeapRegion*>& _empty_regions;
 320   int _empty_regions_pos;
 321   ShenandoahHeapRegion*          _to_region;
 322   ShenandoahHeapRegion*          _from_region;
 323   HeapWord* _compact_point;
 324 
 325 public:
 326   ShenandoahPrepareForCompactionObjectClosure(PreservedMarks* preserved_marks,
 327                                               GrowableArray<ShenandoahHeapRegion*>& empty_regions,
 328                                               ShenandoahHeapRegion* to_region) :
 329     _preserved_marks(preserved_marks),
 330     _heap(ShenandoahHeap::heap()),
 331     _empty_regions(empty_regions),
 332     _empty_regions_pos(0),
 333     _to_region(to_region),
 334     _from_region(nullptr),
 335     _compact_point(to_region->bottom()) {}
 336 
 337   void set_from_region(ShenandoahHeapRegion* from_region) {
 338     _from_region = from_region;
 339   }
 340 
 341   void finish() {
 342     assert(_to_region != nullptr, "should not happen");
 343     _to_region->set_new_top(_compact_point);
 344   }
 345 
 346   bool is_compact_same_region() {
 347     return _from_region == _to_region;
 348   }
 349 
 350   int empty_regions_pos() {
 351     return _empty_regions_pos;
 352   }
 353 
 354   void do_object(oop p) override {
 355     shenandoah_assert_mark_complete(cast_from_oop<HeapWord*>(p));
 356     assert(_from_region != nullptr, "must set before work");
 357     assert(_heap->global_generation()->is_mark_complete(), "marking must be finished");
 358     assert(_heap->marking_context()->is_marked(p), "must be marked");
 359     assert(!_heap->marking_context()->allocated_after_mark_start(p), "must be truly marked");
 360 
 361     size_t obj_size = p->size();
 362     if (_compact_point + obj_size > _to_region->end()) {
 363       finish();
 364 
 365       // Object doesn't fit. Pick next empty region and start compacting there.
 366       ShenandoahHeapRegion* new_to_region;
 367       if (_empty_regions_pos < _empty_regions.length()) {
 368         new_to_region = _empty_regions.at(_empty_regions_pos);
 369         _empty_regions_pos++;
 370       } else {
 371         // Out of empty region? Compact within the same region.
 372         new_to_region = _from_region;
 373       }
 374 
 375       assert(new_to_region != _to_region, "must not reuse same to-region");
 376       assert(new_to_region != nullptr, "must not be null");
 377       _to_region = new_to_region;
 378       _compact_point = _to_region->bottom();
 379     }
 380 
 381     // Object fits into current region, record new location, if object does not move:
 382     assert(_compact_point + obj_size <= _to_region->end(), "must fit");
 383     shenandoah_assert_not_forwarded(nullptr, p);
 384     if (_compact_point != cast_from_oop<HeapWord*>(p)) {
 385       _preserved_marks->push_if_necessary(p, p->mark());
 386       FullGCForwarding::forward_to(p, cast_to_oop(_compact_point));
 387     }
 388     _compact_point += obj_size;
 389   }
 390 };
 391 
 392 class ShenandoahPrepareForCompactionTask : public WorkerTask {
 393 private:
 394   PreservedMarksSet*        const _preserved_marks;
 395   ShenandoahHeap*           const _heap;
 396   ShenandoahHeapRegionSet** const _worker_slices;
 397 
 398 public:
 399   ShenandoahPrepareForCompactionTask(PreservedMarksSet *preserved_marks, ShenandoahHeapRegionSet **worker_slices) :
 400     WorkerTask("Shenandoah Prepare For Compaction"),
 401     _preserved_marks(preserved_marks),
 402     _heap(ShenandoahHeap::heap()), _worker_slices(worker_slices) {
 403   }
 404 
 405   static bool is_candidate_region(ShenandoahHeapRegion* r) {
 406     // Empty region: get it into the slice to defragment the slice itself.
 407     // We could have skipped this without violating correctness, but we really
 408     // want to compact all live regions to the start of the heap, which sometimes
 409     // means moving them into the fully empty regions.
 410     if (r->is_empty()) return true;
 411 
 412     // Can move the region, and this is not the humongous region. Humongous
 413     // moves are special cased here, because their moves are handled separately.
 414     return r->is_stw_move_allowed() && !r->is_humongous();
 415   }
 416 
 417   void work(uint worker_id) override;
 418 private:
 419   template<typename ClosureType>
 420   void prepare_for_compaction(ClosureType& cl,
 421                               GrowableArray<ShenandoahHeapRegion*>& empty_regions,
 422                               ShenandoahHeapRegionSetIterator& it,
 423                               ShenandoahHeapRegion* from_region);
 424 };
 425 
 426 void ShenandoahPrepareForCompactionTask::work(uint worker_id) {
 427   ShenandoahParallelWorkerSession worker_session(worker_id);
 428   ShenandoahHeapRegionSet* slice = _worker_slices[worker_id];
 429   ShenandoahHeapRegionSetIterator it(slice);
 430   ShenandoahHeapRegion* from_region = it.next();
 431   // No work?
 432   if (from_region == nullptr) {
 433     return;
 434   }
 435 
 436   // Sliding compaction. Walk all regions in the slice, and compact them.
 437   // Remember empty regions and reuse them as needed.
 438   ResourceMark rm;
 439 
 440   GrowableArray<ShenandoahHeapRegion*> empty_regions((int)_heap->num_regions());
 441 
 442   if (_heap->mode()->is_generational()) {
 443     ShenandoahPrepareForGenerationalCompactionObjectClosure cl(_preserved_marks->get(worker_id),
 444                                                                empty_regions, from_region, worker_id);
 445     prepare_for_compaction(cl, empty_regions, it, from_region);
 446   } else {
 447     ShenandoahPrepareForCompactionObjectClosure cl(_preserved_marks->get(worker_id), empty_regions, from_region);
 448     prepare_for_compaction(cl, empty_regions, it, from_region);
 449   }
 450 }
 451 
 452 template<typename ClosureType>
 453 void ShenandoahPrepareForCompactionTask::prepare_for_compaction(ClosureType& cl,
 454                                                                 GrowableArray<ShenandoahHeapRegion*>& empty_regions,
 455                                                                 ShenandoahHeapRegionSetIterator& it,
 456                                                                 ShenandoahHeapRegion* from_region) {
 457   while (from_region != nullptr) {
 458     assert(is_candidate_region(from_region), "Sanity");
 459     cl.set_from_region(from_region);
 460     if (from_region->has_live()) {
 461       _heap->marked_object_iterate(from_region, &cl);
 462     }
 463 
 464     // Compacted the region to somewhere else? From-region is empty then.
 465     if (!cl.is_compact_same_region()) {
 466       empty_regions.append(from_region);
 467     }
 468     from_region = it.next();
 469   }
 470   cl.finish();
 471 
 472   // Mark all remaining regions as empty
 473   for (int pos = cl.empty_regions_pos(); pos < empty_regions.length(); ++pos) {
 474     ShenandoahHeapRegion* r = empty_regions.at(pos);
 475     r->set_new_top(r->bottom());
 476   }
 477 }
 478 
 479 void ShenandoahFullGC::calculate_target_humongous_objects() {
 480   ShenandoahHeap* heap = ShenandoahHeap::heap();
 481 
 482   // Compute the new addresses for humongous objects. We need to do this after addresses
 483   // for regular objects are calculated, and we know what regions in heap suffix are
 484   // available for humongous moves.
 485   //
 486   // Scan the heap backwards, because we are compacting humongous regions towards the end.
 487   // Maintain the contiguous compaction window in [to_begin; to_end), so that we can slide
 488   // humongous start there.
 489   //
 490   // The complication is potential non-movable regions during the scan. If such region is
 491   // detected, then sliding restarts towards that non-movable region.
 492 
 493   size_t to_begin = heap->num_regions();
 494   size_t to_end = heap->num_regions();
 495 
 496   log_debug(gc)("Full GC calculating target humongous objects from end %zu", to_end);
 497   for (size_t c = heap->num_regions(); c > 0; c--) {
 498     ShenandoahHeapRegion *r = heap->get_region(c - 1);
 499     if (r->is_humongous_continuation() || (r->new_top() == r->bottom())) {
 500       // To-region candidate: record this, and continue scan
 501       to_begin = r->index();
 502       continue;
 503     }
 504 
 505     if (r->is_humongous_start() && r->is_stw_move_allowed()) {
 506       // From-region candidate: movable humongous region
 507       oop old_obj = cast_to_oop(r->bottom());
 508       size_t words_size = old_obj->size();
 509       size_t num_regions = ShenandoahHeapRegion::required_regions(words_size * HeapWordSize);
 510 
 511       size_t start = to_end - num_regions;
 512 
 513       if (start >= to_begin && start != r->index()) {
 514         // Fits into current window, and the move is non-trivial. Record the move then, and continue scan.
 515         _preserved_marks->get(0)->push_if_necessary(old_obj, old_obj->mark());
 516         FullGCForwarding::forward_to(old_obj, cast_to_oop(heap->get_region(start)->bottom()));
 517         to_end = start;
 518         continue;
 519       }
 520     }
 521 
 522     // Failed to fit. Scan starting from current region.
 523     to_begin = r->index();
 524     to_end = r->index();
 525   }
 526 }
 527 
 528 class ShenandoahEnsureHeapActiveClosure: public ShenandoahHeapRegionClosure {
 529 public:
 530   void heap_region_do(ShenandoahHeapRegion* r) override {
 531     if (r->is_trash()) {
 532       r->try_recycle_under_lock();
 533       // No need to adjust_interval_for_recycled_old_region.  That will be taken care of during freeset rebuild.
 534     }
 535     if (r->is_cset()) {
 536       // Leave affiliation unchanged
 537       r->make_regular_bypass();
 538     }
 539     if (r->is_empty_uncommitted()) {
 540       r->make_committed_bypass();
 541     }
 542     assert (r->is_committed(), "only committed regions in heap now, see region %zu", r->index());
 543 
 544     // Record current region occupancy: this communicates empty regions are free
 545     // to the rest of Full GC code.
 546     r->set_new_top(r->top());
 547   }
 548 };
 549 
 550 class ShenandoahTrashImmediateGarbageClosure: public ShenandoahHeapRegionClosure {
 551 private:
 552   ShenandoahHeap* const _heap;
 553   ShenandoahMarkingContext* const _ctx;
 554 
 555 public:
 556   ShenandoahTrashImmediateGarbageClosure() :
 557     _heap(ShenandoahHeap::heap()),
 558     _ctx(ShenandoahHeap::heap()->global_generation()->complete_marking_context()) {}
 559 
 560   void heap_region_do(ShenandoahHeapRegion* r) override {
 561     if (r->is_humongous_start()) {
 562       oop humongous_obj = cast_to_oop(r->bottom());
 563       if (!_ctx->is_marked(humongous_obj)) {
 564         assert(!r->has_live(), "Region %zu is not marked, should not have live", r->index());
 565         _heap->trash_humongous_region_at(r);
 566       } else {
 567         assert(r->has_live(), "Region %zu should have live", r->index());
 568       }
 569     } else if (r->is_humongous_continuation()) {
 570       // If we hit continuation, the non-live humongous starts should have been trashed already
 571       assert(r->humongous_start_region()->has_live(), "Region %zu should have live", r->index());
 572     } else if (r->is_regular()) {
 573       if (!r->has_live()) {
 574         r->make_trash_immediate();
 575       }
 576     }
 577   }
 578 };
 579 
 580 void ShenandoahFullGC::distribute_slices(ShenandoahHeapRegionSet** worker_slices) {
 581   ShenandoahHeap* heap = ShenandoahHeap::heap();
 582 
 583   uint n_workers = heap->workers()->active_workers();
 584   size_t n_regions = heap->num_regions();
 585 
 586   // What we want to accomplish: have the dense prefix of data, while still balancing
 587   // out the parallel work.
 588   //
 589   // Assuming the amount of work is driven by the live data that needs moving, we can slice
 590   // the entire heap into equal-live-sized prefix slices, and compact into them. So, each
 591   // thread takes all regions in its prefix subset, and then it takes some regions from
 592   // the tail.
 593   //
 594   // Tail region selection becomes interesting.
 595   //
 596   // First, we want to distribute the regions fairly between the workers, and those regions
 597   // might have different amount of live data. So, until we sure no workers need live data,
 598   // we need to only take what the worker needs.
 599   //
 600   // Second, since we slide everything to the left in each slice, the most busy regions
 601   // would be the ones on the left. Which means we want to have all workers have their after-tail
 602   // regions as close to the left as possible.
 603   //
 604   // The easiest way to do this is to distribute after-tail regions in round-robin between
 605   // workers that still need live data.
 606   //
 607   // Consider parallel workers A, B, C, then the target slice layout would be:
 608   //
 609   //  AAAAAAAABBBBBBBBCCCCCCCC|ABCABCABCABCABCABCABCABABABABABABABABABABAAAAA
 610   //
 611   //  (.....dense-prefix.....) (.....................tail...................)
 612   //  [all regions fully live] [left-most regions are fuller that right-most]
 613   //
 614 
 615   // Compute how much live data is there. This would approximate the size of dense prefix
 616   // we target to create.
 617   size_t total_live = 0;
 618   for (size_t idx = 0; idx < n_regions; idx++) {
 619     ShenandoahHeapRegion *r = heap->get_region(idx);
 620     if (ShenandoahPrepareForCompactionTask::is_candidate_region(r)) {
 621       total_live += r->get_live_data_words();
 622     }
 623   }
 624 
 625   // Estimate the size for the dense prefix. Note that we specifically count only the
 626   // "full" regions, so there would be some non-full regions in the slice tail.
 627   size_t live_per_worker = total_live / n_workers;
 628   size_t prefix_regions_per_worker = live_per_worker / ShenandoahHeapRegion::region_size_words();
 629   size_t prefix_regions_total = prefix_regions_per_worker * n_workers;
 630   prefix_regions_total = MIN2(prefix_regions_total, n_regions);
 631   assert(prefix_regions_total <= n_regions, "Sanity");
 632 
 633   // There might be non-candidate regions in the prefix. To compute where the tail actually
 634   // ends up being, we need to account those as well.
 635   size_t prefix_end = prefix_regions_total;
 636   for (size_t idx = 0; idx < prefix_regions_total; idx++) {
 637     ShenandoahHeapRegion *r = heap->get_region(idx);
 638     if (!ShenandoahPrepareForCompactionTask::is_candidate_region(r)) {
 639       prefix_end++;
 640     }
 641   }
 642   prefix_end = MIN2(prefix_end, n_regions);
 643   assert(prefix_end <= n_regions, "Sanity");
 644 
 645   // Distribute prefix regions per worker: each thread definitely gets its own same-sized
 646   // subset of dense prefix.
 647   size_t prefix_idx = 0;
 648 
 649   size_t* live = NEW_C_HEAP_ARRAY(size_t, n_workers, mtGC);
 650 
 651   for (size_t wid = 0; wid < n_workers; wid++) {
 652     ShenandoahHeapRegionSet* slice = worker_slices[wid];
 653 
 654     live[wid] = 0;
 655     size_t regs = 0;
 656 
 657     // Add all prefix regions for this worker
 658     while (prefix_idx < prefix_end && regs < prefix_regions_per_worker) {
 659       ShenandoahHeapRegion *r = heap->get_region(prefix_idx);
 660       if (ShenandoahPrepareForCompactionTask::is_candidate_region(r)) {
 661         slice->add_region(r);
 662         live[wid] += r->get_live_data_words();
 663         regs++;
 664       }
 665       prefix_idx++;
 666     }
 667   }
 668 
 669   // Distribute the tail among workers in round-robin fashion.
 670   size_t wid = n_workers - 1;
 671 
 672   for (size_t tail_idx = prefix_end; tail_idx < n_regions; tail_idx++) {
 673     ShenandoahHeapRegion *r = heap->get_region(tail_idx);
 674     if (ShenandoahPrepareForCompactionTask::is_candidate_region(r)) {
 675       assert(wid < n_workers, "Sanity");
 676 
 677       size_t live_region = r->get_live_data_words();
 678 
 679       // Select next worker that still needs live data.
 680       size_t old_wid = wid;
 681       do {
 682         wid++;
 683         if (wid == n_workers) wid = 0;
 684       } while (live[wid] + live_region >= live_per_worker && old_wid != wid);
 685 
 686       if (old_wid == wid) {
 687         // Circled back to the same worker? This means liveness data was
 688         // miscalculated. Bump the live_per_worker limit so that
 689         // everyone gets a piece of the leftover work.
 690         live_per_worker += ShenandoahHeapRegion::region_size_words();
 691       }
 692 
 693       worker_slices[wid]->add_region(r);
 694       live[wid] += live_region;
 695     }
 696   }
 697 
 698   FREE_C_HEAP_ARRAY(size_t, live);
 699 
 700 #ifdef ASSERT
 701   ResourceBitMap map(n_regions);
 702   for (size_t wid = 0; wid < n_workers; wid++) {
 703     ShenandoahHeapRegionSetIterator it(worker_slices[wid]);
 704     ShenandoahHeapRegion* r = it.next();
 705     while (r != nullptr) {
 706       size_t idx = r->index();
 707       assert(ShenandoahPrepareForCompactionTask::is_candidate_region(r), "Sanity: %zu", idx);
 708       assert(!map.at(idx), "No region distributed twice: %zu", idx);
 709       map.at_put(idx, true);
 710       r = it.next();
 711     }
 712   }
 713 
 714   for (size_t rid = 0; rid < n_regions; rid++) {
 715     bool is_candidate = ShenandoahPrepareForCompactionTask::is_candidate_region(heap->get_region(rid));
 716     bool is_distributed = map.at(rid);
 717     assert(is_distributed || !is_candidate, "All candidates are distributed: %zu", rid);
 718   }
 719 #endif
 720 }
 721 
 722 void ShenandoahFullGC::phase2_calculate_target_addresses(ShenandoahHeapRegionSet** worker_slices) {
 723   GCTraceTime(Info, gc, phases) time("Phase 2: Compute new object addresses", _gc_timer);
 724   ShenandoahGCPhase calculate_address_phase(ShenandoahPhaseTimings::full_gc_calculate_addresses);
 725 
 726   ShenandoahHeap* heap = ShenandoahHeap::heap();
 727 
 728   // About to figure out which regions can be compacted, make sure pinning status
 729   // had been updated in GC prologue.
 730   heap->assert_pinned_region_status();
 731 
 732   {
 733     // Trash the immediately collectible regions before computing addresses
 734     ShenandoahTrashImmediateGarbageClosure trash_immediate_garbage;
 735     ShenandoahExcludeRegionClosure<FREE> cl(&trash_immediate_garbage);
 736     heap->heap_region_iterate(&cl);
 737 
 738     // Make sure regions are in good state: committed, active, clean.
 739     // This is needed because we are potentially sliding the data through them.
 740     ShenandoahEnsureHeapActiveClosure ecl;
 741     heap->heap_region_iterate(&ecl);
 742   }
 743 
 744   // Compute the new addresses for regular objects
 745   {
 746     ShenandoahGCPhase phase(ShenandoahPhaseTimings::full_gc_calculate_addresses_regular);
 747 
 748     distribute_slices(worker_slices);
 749 
 750     ShenandoahPrepareForCompactionTask task(_preserved_marks, worker_slices);
 751     heap->workers()->run_task(&task);
 752   }
 753 
 754   // Compute the new addresses for humongous objects
 755   {
 756     ShenandoahGCPhase phase(ShenandoahPhaseTimings::full_gc_calculate_addresses_humong);
 757     calculate_target_humongous_objects();
 758   }
 759 }
 760 
 761 class ShenandoahAdjustPointersClosure : public MetadataVisitingOopIterateClosure {
 762 private:
 763   ShenandoahMarkingContext* const _ctx;
 764 
 765   template <class T>
 766   inline void do_oop_work(T* p) {
 767     T o = RawAccess<>::oop_load(p);
 768     if (!CompressedOops::is_null(o)) {
 769       oop obj = CompressedOops::decode_not_null(o);
 770       assert(_ctx->is_marked(obj), "must be marked");
 771       if (FullGCForwarding::is_forwarded(obj)) {
 772         oop forw = FullGCForwarding::forwardee(obj);
 773         RawAccess<IS_NOT_NULL>::oop_store(p, forw);
 774       }
 775     }
 776   }
 777 
 778 public:
 779   ShenandoahAdjustPointersClosure() :
 780     _ctx(ShenandoahHeap::heap()->global_generation()->complete_marking_context()) {}
 781 
 782   void do_oop(oop* p)       { do_oop_work(p); }
 783   void do_oop(narrowOop* p) { do_oop_work(p); }
 784   void do_method(Method* m) {}
 785   void do_nmethod(nmethod* nm) {}
 786 };
 787 
 788 class ShenandoahAdjustPointersObjectClosure : public ObjectClosure {
 789 private:
 790   ShenandoahAdjustPointersClosure _cl;
 791 
 792 public:
 793   void do_object(oop p) override {
 794     assert(ShenandoahHeap::heap()->global_generation()->is_mark_complete(), "marking must be complete");
 795     assert(ShenandoahHeap::heap()->marking_context()->is_marked(p), "must be marked");
 796     p->oop_iterate(&_cl);
 797   }
 798 };
 799 
 800 class ShenandoahAdjustPointersTask : public WorkerTask {
 801 private:
 802   ShenandoahHeap*          const _heap;
 803   ShenandoahRegionIterator       _regions;
 804 
 805 public:
 806   ShenandoahAdjustPointersTask() :
 807     WorkerTask("Shenandoah Adjust Pointers"),
 808     _heap(ShenandoahHeap::heap()) {
 809   }
 810 
 811   void work(uint worker_id) override {
 812     ShenandoahParallelWorkerSession worker_session(worker_id);
 813     ShenandoahAdjustPointersObjectClosure obj_cl;
 814     ShenandoahHeapRegion* r = _regions.next();
 815     while (r != nullptr) {
 816       if (!r->is_humongous_continuation() && r->has_live()) {
 817         _heap->marked_object_iterate(r, &obj_cl);
 818       }
 819       if (_heap->mode()->is_generational()) {
 820         ShenandoahGenerationalFullGC::maybe_coalesce_and_fill_region(r);
 821       }
 822       r = _regions.next();
 823     }
 824   }
 825 };
 826 
 827 class ShenandoahAdjustRootPointersTask : public WorkerTask {
 828 private:
 829   ShenandoahRootAdjuster* _rp;
 830   PreservedMarksSet* _preserved_marks;
 831 public:
 832   ShenandoahAdjustRootPointersTask(ShenandoahRootAdjuster* rp, PreservedMarksSet* preserved_marks) :
 833     WorkerTask("Shenandoah Adjust Root Pointers"),
 834     _rp(rp),
 835     _preserved_marks(preserved_marks) {}
 836 
 837   void work(uint worker_id) override {
 838     ShenandoahParallelWorkerSession worker_session(worker_id);
 839     ShenandoahAdjustPointersClosure cl;
 840     _rp->roots_do(worker_id, &cl);
 841     _preserved_marks->get(worker_id)->adjust_during_full_gc();
 842   }
 843 };
 844 
 845 void ShenandoahFullGC::phase3_update_references() {
 846   GCTraceTime(Info, gc, phases) time("Phase 3: Adjust pointers", _gc_timer);
 847   ShenandoahGCPhase adjust_pointer_phase(ShenandoahPhaseTimings::full_gc_adjust_pointers);
 848 
 849   ShenandoahHeap* heap = ShenandoahHeap::heap();
 850 
 851   WorkerThreads* workers = heap->workers();
 852   uint nworkers = workers->active_workers();
 853   {
 854 #if COMPILER2_OR_JVMCI
 855     DerivedPointerTable::clear();
 856 #endif
 857     ShenandoahRootAdjuster rp(nworkers, ShenandoahPhaseTimings::full_gc_adjust_roots);
 858     ShenandoahAdjustRootPointersTask task(&rp, _preserved_marks);
 859     workers->run_task(&task);
 860 #if COMPILER2_OR_JVMCI
 861     DerivedPointerTable::update_pointers();
 862 #endif
 863   }
 864 
 865   ShenandoahAdjustPointersTask adjust_pointers_task;
 866   workers->run_task(&adjust_pointers_task);
 867 }
 868 
 869 class ShenandoahCompactObjectsClosure : public ObjectClosure {
 870 private:
 871   uint const _worker_id;
 872 
 873 public:
 874   explicit ShenandoahCompactObjectsClosure(uint worker_id) :
 875     _worker_id(worker_id) {}
 876 
 877   void do_object(oop p) override {
 878     assert(ShenandoahHeap::heap()->global_generation()->is_mark_complete(), "marking must be finished");
 879     assert(ShenandoahHeap::heap()->marking_context()->is_marked(p), "must be marked");
 880     size_t size = p->size();
 881     if (FullGCForwarding::is_forwarded(p)) {
 882       HeapWord* compact_from = cast_from_oop<HeapWord*>(p);
 883       HeapWord* compact_to = cast_from_oop<HeapWord*>(FullGCForwarding::forwardee(p));
 884       assert(compact_from != compact_to, "Forwarded object should move");
 885       Copy::aligned_conjoint_words(compact_from, compact_to, size);
 886       oop new_obj = cast_to_oop(compact_to);
 887 
 888       ContinuationGCSupport::relativize_stack_chunk(new_obj);
 889       new_obj->init_mark();
 890     }
 891   }
 892 };
 893 
 894 class ShenandoahCompactObjectsTask : public WorkerTask {
 895 private:
 896   ShenandoahHeap* const _heap;
 897   ShenandoahHeapRegionSet** const _worker_slices;
 898 
 899 public:
 900   ShenandoahCompactObjectsTask(ShenandoahHeapRegionSet** worker_slices) :
 901     WorkerTask("Shenandoah Compact Objects"),
 902     _heap(ShenandoahHeap::heap()),
 903     _worker_slices(worker_slices) {
 904   }
 905 
 906   void work(uint worker_id) override {
 907     ShenandoahParallelWorkerSession worker_session(worker_id);
 908     ShenandoahHeapRegionSetIterator slice(_worker_slices[worker_id]);
 909 
 910     ShenandoahCompactObjectsClosure cl(worker_id);
 911     ShenandoahHeapRegion* r = slice.next();
 912     while (r != nullptr) {
 913       assert(!r->is_humongous(), "must not get humongous regions here");
 914       if (r->has_live()) {
 915         _heap->marked_object_iterate(r, &cl);
 916       }
 917       r->set_top(r->new_top());
 918       r = slice.next();
 919     }
 920   }
 921 };
 922 
 923 class ShenandoahPostCompactClosure : public ShenandoahHeapRegionClosure {
 924 private:
 925   ShenandoahHeap* const _heap;
 926   bool _is_generational;
 927   size_t _young_regions, _young_usage, _young_humongous_waste;
 928   size_t _old_regions, _old_usage, _old_humongous_waste;
 929 
 930 public:
 931   ShenandoahPostCompactClosure() : _heap(ShenandoahHeap::heap()),
 932                                    _is_generational(_heap->mode()->is_generational()),
 933                                    _young_regions(0),
 934                                    _young_usage(0),
 935                                    _young_humongous_waste(0),
 936                                    _old_regions(0),
 937                                    _old_usage(0),
 938                                    _old_humongous_waste(0)
 939   {
 940     _heap->free_set()->clear();
 941   }
 942 
 943   void heap_region_do(ShenandoahHeapRegion* r) override {
 944     assert (!r->is_cset(), "cset regions should have been demoted already");
 945 
 946     // Need to reset the complete-top-at-mark-start pointer here because
 947     // the complete marking bitmap is no longer valid. This ensures
 948     // size-based iteration in marked_object_iterate().
 949     // NOTE: See blurb at ShenandoahMCResetCompleteBitmapTask on why we need to skip
 950     // pinned regions.
 951     if (!r->is_pinned()) {
 952       _heap->marking_context()->reset_top_at_mark_start(r);
 953     }
 954 
 955     size_t live = r->used();
 956 
 957     // Make empty regions that have been allocated into regular
 958     if (r->is_empty() && live > 0) {
 959       if (!_is_generational) {
 960         r->make_affiliated_maybe();
 961       }
 962       // else, generational mode compaction has already established affiliation.
 963       r->make_regular_bypass();
 964       if (ZapUnusedHeapArea) {
 965         SpaceMangler::mangle_region(MemRegion(r->top(), r->end()));
 966       }
 967     }
 968 
 969     // Reclaim regular regions that became empty
 970     if (r->is_regular() && live == 0) {
 971       r->make_trash();
 972     }
 973 
 974     // Recycle all trash regions
 975     if (r->is_trash()) {
 976       live = 0;
 977       r->try_recycle_under_lock();
 978       // No need to adjust_interval_for_recycled_old_region.  That will be taken care of during freeset rebuild.
 979     } else {
 980       if (r->is_old()) {
 981         ShenandoahGenerationalFullGC::account_for_region(r, _old_regions, _old_usage, _old_humongous_waste);
 982       } else if (r->is_young()) {
 983         ShenandoahGenerationalFullGC::account_for_region(r, _young_regions, _young_usage, _young_humongous_waste);
 984       }
 985     }
 986     r->set_live_data(live);
 987     r->reset_alloc_metadata();
 988   }
 989 };
 990 
 991 void ShenandoahFullGC::compact_humongous_objects() {
 992   // Compact humongous regions, based on their fwdptr objects.
 993   //
 994   // This code is serial, because doing the in-slice parallel sliding is tricky. In most cases,
 995   // humongous regions are already compacted, and do not require further moves, which alleviates
 996   // sliding costs. We may consider doing this in parallel in the future.
 997 
 998   ShenandoahHeap* heap = ShenandoahHeap::heap();
 999 
1000   for (size_t c = heap->num_regions(); c > 0; c--) {
1001     ShenandoahHeapRegion* r = heap->get_region(c - 1);
1002     if (r->is_humongous_start()) {
1003       oop old_obj = cast_to_oop(r->bottom());
1004       if (!FullGCForwarding::is_forwarded(old_obj)) {
1005         // No need to move the object, it stays at the same slot
1006         continue;
1007       }
1008       size_t words_size = old_obj->size();
1009       size_t num_regions = ShenandoahHeapRegion::required_regions(words_size * HeapWordSize);
1010 
1011       size_t old_start = r->index();
1012       size_t old_end   = old_start + num_regions - 1;
1013       size_t new_start = heap->heap_region_index_containing(FullGCForwarding::forwardee(old_obj));
1014       size_t new_end   = new_start + num_regions - 1;
1015       assert(old_start != new_start, "must be real move");
1016       assert(r->is_stw_move_allowed(), "Region %zu should be movable", r->index());
1017 
1018       log_debug(gc)("Full GC compaction moves humongous object from region %zu to region %zu", old_start, new_start);
1019       Copy::aligned_conjoint_words(r->bottom(), heap->get_region(new_start)->bottom(), words_size);
1020       ContinuationGCSupport::relativize_stack_chunk(cast_to_oop<HeapWord*>(r->bottom()));
1021 
1022       oop new_obj = cast_to_oop(heap->get_region(new_start)->bottom());
1023       new_obj->init_mark();
1024 
1025       {
1026         ShenandoahAffiliation original_affiliation = r->affiliation();
1027         for (size_t c = old_start; c <= old_end; c++) {
1028           ShenandoahHeapRegion* r = heap->get_region(c);
1029           // Leave humongous region affiliation unchanged.
1030           r->make_regular_bypass();
1031           r->set_top(r->bottom());
1032         }
1033 
1034         for (size_t c = new_start; c <= new_end; c++) {
1035           ShenandoahHeapRegion* r = heap->get_region(c);
1036           if (c == new_start) {
1037             r->make_humongous_start_bypass(original_affiliation);
1038           } else {
1039             r->make_humongous_cont_bypass(original_affiliation);
1040           }
1041 
1042           // Trailing region may be non-full, record the remainder there
1043           size_t remainder = words_size & ShenandoahHeapRegion::region_size_words_mask();
1044           if ((c == new_end) && (remainder != 0)) {
1045             r->set_top(r->bottom() + remainder);
1046           } else {
1047             r->set_top(r->end());
1048           }
1049 
1050           r->reset_alloc_metadata();
1051         }
1052       }
1053     }
1054   }
1055 }
1056 
1057 // This is slightly different to ShHeap::reset_next_mark_bitmap:
1058 // we need to remain able to walk pinned regions.
1059 // Since pinned region do not move and don't get compacted, we will get holes with
1060 // unreachable objects in them (which may have pointers to unloaded Klasses and thus
1061 // cannot be iterated over using oop->size()). The only way to safely iterate over those is using
1062 // a valid marking bitmap and valid TAMS pointer. This class only resets marking
1063 // bitmaps for un-pinned regions, and later we only reset TAMS for unpinned regions.
1064 class ShenandoahMCResetCompleteBitmapTask : public WorkerTask {
1065 private:
1066   ShenandoahRegionIterator _regions;
1067 
1068 public:
1069   ShenandoahMCResetCompleteBitmapTask() :
1070     WorkerTask("Shenandoah Reset Bitmap") {
1071   }
1072 
1073   void work(uint worker_id) override {
1074     ShenandoahParallelWorkerSession worker_session(worker_id);
1075     ShenandoahHeapRegion* region = _regions.next();
1076     ShenandoahHeap* heap = ShenandoahHeap::heap();
1077     ShenandoahMarkingContext* const ctx = heap->marking_context();
1078     assert(heap->global_generation()->is_mark_complete(), "Marking must be complete");
1079     while (region != nullptr) {
1080       if (heap->is_bitmap_slice_committed(region) && !region->is_pinned() && region->has_live()) {
1081         ctx->clear_bitmap(region);
1082       }
1083       region = _regions.next();
1084     }
1085   }
1086 };
1087 
1088 void ShenandoahFullGC::phase4_compact_objects(ShenandoahHeapRegionSet** worker_slices) {
1089   GCTraceTime(Info, gc, phases) time("Phase 4: Move objects", _gc_timer);
1090   ShenandoahGCPhase compaction_phase(ShenandoahPhaseTimings::full_gc_copy_objects);
1091 
1092   ShenandoahHeap* heap = ShenandoahHeap::heap();
1093 
1094   // Compact regular objects first
1095   {
1096     ShenandoahGCPhase phase(ShenandoahPhaseTimings::full_gc_copy_objects_regular);
1097     ShenandoahCompactObjectsTask compact_task(worker_slices);
1098     heap->workers()->run_task(&compact_task);
1099   }
1100 
1101   // Compact humongous objects after regular object moves
1102   {
1103     ShenandoahGCPhase phase(ShenandoahPhaseTimings::full_gc_copy_objects_humong);
1104     compact_humongous_objects();
1105   }
1106 }
1107 
1108 void ShenandoahFullGC::phase5_epilog() {
1109   GCTraceTime(Info, gc, phases) time("Phase 5: Full GC epilog", _gc_timer);
1110   ShenandoahHeap* heap = ShenandoahHeap::heap();
1111 
1112   // Reset complete bitmap. We're about to reset the complete-top-at-mark-start pointer
1113   // and must ensure the bitmap is in sync.
1114   {
1115     ShenandoahGCPhase phase(ShenandoahPhaseTimings::full_gc_copy_objects_reset_complete);
1116     ShenandoahMCResetCompleteBitmapTask task;
1117     heap->workers()->run_task(&task);
1118   }
1119 
1120   // Bring regions in proper states after the collection, and set heap properties.
1121   {
1122     ShenandoahGCPhase phase(ShenandoahPhaseTimings::full_gc_copy_objects_rebuild);
1123     ShenandoahPostCompactClosure post_compact;
1124     heap->heap_region_iterate(&post_compact);
1125     heap->collection_set()->clear();
1126     {
1127       ShenandoahFreeSet* free_set = heap->free_set();
1128       size_t young_trashed_regions, old_trashed_regions, first_old, last_old, num_old;
1129       free_set->prepare_to_rebuild(young_trashed_regions, old_trashed_regions, first_old, last_old, num_old);
1130       // We also do not expand old generation size following Full GC because we have scrambled age populations and
1131       // no longer have objects separated by age into distinct regions.
1132       if (heap->mode()->is_generational()) {
1133         ShenandoahGenerationalFullGC::compute_balances();
1134       }
1135       heap->free_set()->finish_rebuild(young_trashed_regions, old_trashed_regions, num_old);
1136     }
1137 
1138     // Set mark incomplete because the marking bitmaps have been reset except pinned regions.
1139     _generation->set_mark_incomplete();
1140 
1141     heap->clear_cancelled_gc();
1142   }
1143 
1144   _preserved_marks->restore(heap->workers());
1145   _preserved_marks->reclaim();
1146 
1147   if (heap->mode()->is_generational()) {
1148     ShenandoahGenerationalFullGC::rebuild_remembered_set(heap);
1149   }
1150 }