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