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