1 /*
   2  * Copyright (c) 2014, 2021, Red Hat, Inc. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #include "precompiled.hpp"
  26 
  27 #include "compiler/oopMap.hpp"
  28 #include "gc/shared/continuationGCSupport.hpp"
  29 #include "gc/shared/gcTraceTime.inline.hpp"
  30 #include "gc/shared/preservedMarks.inline.hpp"
  31 #include "gc/shared/tlab_globals.hpp"
  32 #include "gc/shared/workerThread.hpp"
  33 #include "gc/shenandoah/heuristics/shenandoahHeuristics.hpp"
  34 #include "gc/shenandoah/shenandoahConcurrentGC.hpp"
  35 #include "gc/shenandoah/shenandoahCollectionSet.hpp"
  36 #include "gc/shenandoah/shenandoahFreeSet.hpp"
  37 #include "gc/shenandoah/shenandoahFullGC.hpp"
  38 #include "gc/shenandoah/shenandoahGeneration.hpp"
  39 #include "gc/shenandoah/shenandoahPhaseTimings.hpp"
  40 #include "gc/shenandoah/shenandoahMark.inline.hpp"
  41 #include "gc/shenandoah/shenandoahMonitoringSupport.hpp"
  42 #include "gc/shenandoah/shenandoahHeapRegionSet.hpp"
  43 #include "gc/shenandoah/shenandoahHeap.inline.hpp"
  44 #include "gc/shenandoah/shenandoahHeapRegion.inline.hpp"
  45 #include "gc/shenandoah/shenandoahMarkingContext.inline.hpp"
  46 #include "gc/shenandoah/shenandoahMetrics.hpp"
  47 #include "gc/shenandoah/shenandoahOldGeneration.hpp"
  48 #include "gc/shenandoah/shenandoahOopClosures.inline.hpp"
  49 #include "gc/shenandoah/shenandoahReferenceProcessor.hpp"
  50 #include "gc/shenandoah/shenandoahRootProcessor.inline.hpp"
  51 #include "gc/shenandoah/shenandoahSTWMark.hpp"
  52 #include "gc/shenandoah/shenandoahUtils.hpp"
  53 #include "gc/shenandoah/shenandoahVerifier.hpp"
  54 #include "gc/shenandoah/shenandoahVMOperations.hpp"
  55 #include "gc/shenandoah/shenandoahWorkerPolicy.hpp"
  56 #include "gc/shenandoah/shenandoahYoungGeneration.hpp"
  57 #include "memory/metaspaceUtils.hpp"
  58 #include "memory/universe.hpp"
  59 #include "oops/compressedOops.inline.hpp"
  60 #include "oops/oop.inline.hpp"
  61 #include "runtime/javaThread.hpp"
  62 #include "runtime/orderAccess.hpp"
  63 #include "runtime/vmThread.hpp"
  64 #include "utilities/copy.hpp"
  65 #include "utilities/events.hpp"
  66 #include "utilities/growableArray.hpp"
  67 
  68 // After Full GC is done, reconstruct the remembered set by iterating over OLD regions,
  69 // registering all objects between bottom() and top(), and setting remembered set cards to
  70 // DIRTY if they hold interesting pointers.
  71 class ShenandoahReconstructRememberedSetTask : public WorkerTask {
  72 private:
  73   ShenandoahRegionIterator _regions;
  74 
  75 public:
  76   ShenandoahReconstructRememberedSetTask() :
  77     WorkerTask("Shenandoah Reset Bitmap") { }
  78 
  79   void work(uint worker_id) {
  80     ShenandoahParallelWorkerSession worker_session(worker_id);
  81     ShenandoahHeapRegion* r = _regions.next();
  82     ShenandoahHeap* heap = ShenandoahHeap::heap();
  83     RememberedScanner* scanner = heap->card_scan();
  84     ShenandoahSetRememberedCardsToDirtyClosure dirty_cards_for_interesting_pointers;
  85 
  86     while (r != NULL) {
  87       if (r->is_old() && r->is_active()) {
  88         HeapWord* obj_addr = r->bottom();
  89         if (r->is_humongous_start()) {
  90           // First, clear the remembered set
  91           oop obj = cast_to_oop(obj_addr);
  92           size_t size = obj->size();
  93           HeapWord* end_object = r->bottom() + size;
  94 
  95           // First, clear the remembered set for all spanned humongous regions
  96           size_t num_regions = (size + ShenandoahHeapRegion::region_size_words() - 1) / ShenandoahHeapRegion::region_size_words();
  97           size_t region_span = num_regions * ShenandoahHeapRegion::region_size_words();
  98           scanner->reset_remset(r->bottom(), region_span);
  99           size_t region_index = r->index();
 100           ShenandoahHeapRegion* humongous_region = heap->get_region(region_index);
 101           while (num_regions-- != 0) {
 102             scanner->reset_object_range(humongous_region->bottom(), humongous_region->end());
 103             region_index++;
 104             humongous_region = heap->get_region(region_index);
 105           }
 106 
 107           // Then register the humongous object and DIRTY relevant remembered set cards
 108           scanner->register_object_wo_lock(obj_addr);
 109           obj->oop_iterate(&dirty_cards_for_interesting_pointers);
 110         } else if (!r->is_humongous()) {
 111           // First, clear the remembered set
 112           scanner->reset_remset(r->bottom(), ShenandoahHeapRegion::region_size_words());
 113           scanner->reset_object_range(r->bottom(), r->end());
 114 
 115           // Then iterate over all objects, registering object and DIRTYing relevant remembered set cards
 116           HeapWord* t = r->top();
 117           while (obj_addr < t) {
 118             oop obj = cast_to_oop(obj_addr);
 119             size_t size = obj->size();
 120             scanner->register_object_wo_lock(obj_addr);
 121             obj_addr += obj->oop_iterate_size(&dirty_cards_for_interesting_pointers);
 122           }
 123         } // else, ignore humongous continuation region
 124       }
 125       // else, this region is FREE or YOUNG or inactive and we can ignore it.
 126       r = _regions.next();
 127     }
 128   }
 129 };
 130 
 131 ShenandoahFullGC::ShenandoahFullGC() :
 132   _gc_timer(ShenandoahHeap::heap()->gc_timer()),
 133   _preserved_marks(new PreservedMarksSet(true)) {}
 134 
 135 bool ShenandoahFullGC::collect(GCCause::Cause cause) {
 136   vmop_entry_full(cause);
 137   // Always success
 138   return true;
 139 }
 140 
 141 void ShenandoahFullGC::vmop_entry_full(GCCause::Cause cause) {
 142   ShenandoahHeap* const heap = ShenandoahHeap::heap();
 143   TraceCollectorStats tcs(heap->monitoring_support()->full_stw_collection_counters());
 144   ShenandoahTimingsTracker timing(ShenandoahPhaseTimings::full_gc_gross);
 145 
 146   heap->try_inject_alloc_failure();
 147   VM_ShenandoahFullGC op(cause, this);
 148   VMThread::execute(&op);
 149 }
 150 
 151 void ShenandoahFullGC::entry_full(GCCause::Cause cause) {
 152   static const char* msg = "Pause Full";
 153   ShenandoahPausePhase gc_phase(msg, ShenandoahPhaseTimings::full_gc, true /* log_heap_usage */);
 154   EventMark em("%s", msg);
 155 
 156   ShenandoahWorkerScope scope(ShenandoahHeap::heap()->workers(),
 157                               ShenandoahWorkerPolicy::calc_workers_for_fullgc(),
 158                               "full gc");
 159 
 160   op_full(cause);
 161 }
 162 
 163 void ShenandoahFullGC::op_full(GCCause::Cause cause) {
 164   ShenandoahHeap* const heap = ShenandoahHeap::heap();
 165   ShenandoahMetricsSnapshot metrics;
 166   metrics.snap_before();
 167 
 168   // Perform full GC
 169   do_it(cause);
 170 
 171   metrics.snap_after();
 172   if (heap->mode()->is_generational()) {
 173     size_t old_available = heap->old_generation()->available();
 174     size_t young_available = heap->young_generation()->available();
 175     log_info(gc, ergo)("At end of Full GC, old_available: " SIZE_FORMAT "%s, young_available: " SIZE_FORMAT "%s",
 176                        byte_size_in_proper_unit(old_available), proper_unit_for_byte_size(old_available),
 177                        byte_size_in_proper_unit(young_available), proper_unit_for_byte_size(young_available));
 178   }
 179   if (metrics.is_good_progress()) {
 180     ShenandoahHeap::heap()->notify_gc_progress();
 181   } else {
 182     // Nothing to do. Tell the allocation path that we have failed to make
 183     // progress, and it can finally fail.
 184     ShenandoahHeap::heap()->notify_gc_no_progress();
 185   }
 186 }
 187 
 188 void ShenandoahFullGC::do_it(GCCause::Cause gc_cause) {
 189   ShenandoahHeap* heap = ShenandoahHeap::heap();
 190   // Since we may arrive here from degenerated GC failure of either young or old, establish generation as GLOBAL.
 191   heap->set_gc_generation(heap->global_generation());
 192 
 193   if (heap->mode()->is_generational()) {
 194     // There will be no concurrent allocations during full GC so reset these coordination variables.
 195     heap->young_generation()->unadjust_available();
 196     heap->old_generation()->unadjust_available();
 197     // No need to old_gen->increase_used().  That was done when plabs were allocated, accounting for both old evacs and promotions.
 198 
 199     heap->set_alloc_supplement_reserve(0);
 200     heap->set_young_evac_reserve(0);
 201     heap->set_old_evac_reserve(0);
 202     heap->reset_old_evac_expended();
 203     heap->set_promoted_reserve(0);
 204 
 205     // Full GC supersedes any marking or coalescing in old generation.
 206     heap->cancel_old_gc();
 207   }
 208 
 209   if (ShenandoahVerify) {
 210     heap->verifier()->verify_before_fullgc();
 211   }
 212 
 213   if (VerifyBeforeGC) {
 214     Universe::verify();
 215   }
 216 
 217   // Degenerated GC may carry concurrent root flags when upgrading to
 218   // full GC. We need to reset it before mutators resume.
 219   heap->set_concurrent_strong_root_in_progress(false);
 220   heap->set_concurrent_weak_root_in_progress(false);
 221 
 222   heap->set_full_gc_in_progress(true);
 223 
 224   assert(ShenandoahSafepoint::is_at_shenandoah_safepoint(), "must be at a safepoint");
 225   assert(Thread::current()->is_VM_thread(), "Do full GC only while world is stopped");
 226 
 227   {
 228     ShenandoahGCPhase phase(ShenandoahPhaseTimings::full_gc_heapdump_pre);
 229     heap->pre_full_gc_dump(_gc_timer);
 230   }
 231 
 232   {
 233     ShenandoahGCPhase prepare_phase(ShenandoahPhaseTimings::full_gc_prepare);
 234     // Full GC is supposed to recover from any GC state:
 235 
 236     // a0. Remember if we have forwarded objects
 237     bool has_forwarded_objects = heap->has_forwarded_objects();
 238 
 239     // a1. Cancel evacuation, if in progress
 240     if (heap->is_evacuation_in_progress()) {
 241       heap->set_evacuation_in_progress(false);
 242     }
 243     assert(!heap->is_evacuation_in_progress(), "sanity");
 244 
 245     // a2. Cancel update-refs, if in progress
 246     if (heap->is_update_refs_in_progress()) {
 247       heap->set_update_refs_in_progress(false);
 248     }
 249     assert(!heap->is_update_refs_in_progress(), "sanity");
 250 
 251     // b. Cancel all concurrent marks, if in progress
 252     if (heap->is_concurrent_mark_in_progress()) {
 253       heap->cancel_concurrent_mark();
 254     }
 255     assert(!heap->is_concurrent_mark_in_progress(), "sanity");
 256 
 257     // c. Update roots if this full GC is due to evac-oom, which may carry from-space pointers in roots.
 258     if (has_forwarded_objects) {
 259       update_roots(true /*full_gc*/);
 260     }
 261 
 262     // d. Reset the bitmaps for new marking
 263     heap->global_generation()->reset_mark_bitmap();
 264     assert(heap->marking_context()->is_bitmap_clear(), "sanity");
 265     assert(!heap->global_generation()->is_mark_complete(), "sanity");
 266 
 267     // e. Abandon reference discovery and clear all discovered references.
 268     ShenandoahReferenceProcessor* rp = heap->global_generation()->ref_processor();
 269     rp->abandon_partial_discovery();
 270 
 271     // f. Sync pinned region status from the CP marks
 272     heap->sync_pinned_region_status();
 273 
 274     // The rest of prologue:
 275     _preserved_marks->init(heap->workers()->active_workers());
 276 
 277     assert(heap->has_forwarded_objects() == has_forwarded_objects, "This should not change");
 278   }
 279 
 280   if (UseTLAB) {
 281     // TODO: Do we need to explicitly retire PLABs?
 282     heap->gclabs_retire(ResizeTLAB);
 283     heap->tlabs_retire(ResizeTLAB);
 284   }
 285 
 286   OrderAccess::fence();
 287 
 288   phase1_mark_heap();
 289 
 290   // Once marking is done, which may have fixed up forwarded objects, we can drop it.
 291   // Coming out of Full GC, we would not have any forwarded objects.
 292   // This also prevents resolves with fwdptr from kicking in while adjusting pointers in phase3.
 293   heap->set_has_forwarded_objects(false);
 294 
 295   heap->set_full_gc_move_in_progress(true);
 296 
 297   // Setup workers for the rest
 298   OrderAccess::fence();
 299 
 300   // Initialize worker slices
 301   ShenandoahHeapRegionSet** worker_slices = NEW_C_HEAP_ARRAY(ShenandoahHeapRegionSet*, heap->max_workers(), mtGC);
 302   for (uint i = 0; i < heap->max_workers(); i++) {
 303     worker_slices[i] = new ShenandoahHeapRegionSet();
 304   }
 305 
 306   {
 307     // The rest of code performs region moves, where region status is undefined
 308     // until all phases run together.
 309     ShenandoahHeapLocker lock(heap->lock());
 310 
 311     phase2_calculate_target_addresses(worker_slices);
 312 
 313     OrderAccess::fence();
 314 
 315     phase3_update_references();
 316 
 317     phase4_compact_objects(worker_slices);
 318   }
 319 
 320   {
 321     // Epilogue
 322     _preserved_marks->restore(heap->workers());
 323     _preserved_marks->reclaim();
 324 
 325     if (heap->mode()->is_generational()) {
 326       ShenandoahGCPhase phase(ShenandoahPhaseTimings::full_gc_reconstruct_remembered_set);
 327       ShenandoahReconstructRememberedSetTask task;
 328       heap->workers()->run_task(&task);
 329     }
 330   }
 331 
 332   // Resize metaspace
 333   MetaspaceGC::compute_new_size();
 334 
 335   // Free worker slices
 336   for (uint i = 0; i < heap->max_workers(); i++) {
 337     delete worker_slices[i];
 338   }
 339   FREE_C_HEAP_ARRAY(ShenandoahHeapRegionSet*, worker_slices);
 340 
 341   heap->set_full_gc_move_in_progress(false);
 342   heap->set_full_gc_in_progress(false);
 343 
 344   if (ShenandoahVerify) {
 345     if (heap->mode()->is_generational()) {
 346       heap->verifier()->verify_after_generational_fullgc();
 347     } else {
 348       heap->verifier()->verify_after_fullgc();
 349     }
 350   }
 351 
 352   if (VerifyAfterGC) {
 353     Universe::verify();
 354   }
 355 
 356   {
 357     ShenandoahGCPhase phase(ShenandoahPhaseTimings::full_gc_heapdump_post);
 358     heap->post_full_gc_dump(_gc_timer);
 359   }
 360 }
 361 
 362 class ShenandoahPrepareForMarkClosure: public ShenandoahHeapRegionClosure {
 363 private:
 364   ShenandoahMarkingContext* const _ctx;
 365 
 366 public:
 367   ShenandoahPrepareForMarkClosure() : _ctx(ShenandoahHeap::heap()->marking_context()) {}
 368 
 369   void heap_region_do(ShenandoahHeapRegion *r) {
 370     if (r->affiliation() != FREE) {
 371       _ctx->capture_top_at_mark_start(r);
 372       r->clear_live_data();
 373     }
 374   }
 375 
 376   bool is_thread_safe() { return true; }
 377 };
 378 
 379 void ShenandoahFullGC::phase1_mark_heap() {
 380   GCTraceTime(Info, gc, phases) time("Phase 1: Mark live objects", _gc_timer);
 381   ShenandoahGCPhase mark_phase(ShenandoahPhaseTimings::full_gc_mark);
 382 
 383   ShenandoahHeap* heap = ShenandoahHeap::heap();
 384 
 385   ShenandoahPrepareForMarkClosure cl;
 386   heap->parallel_heap_region_iterate(&cl);
 387 
 388   heap->set_unload_classes(heap->global_generation()->heuristics()->can_unload_classes());
 389 
 390   ShenandoahReferenceProcessor* rp = heap->global_generation()->ref_processor();
 391   // enable ("weak") refs discovery
 392   rp->set_soft_reference_policy(true); // forcefully purge all soft references
 393 
 394   ShenandoahSTWMark mark(heap->global_generation(), true /*full_gc*/);
 395   mark.mark();
 396   heap->parallel_cleaning(true /* full_gc */);
 397 }
 398 
 399 class ShenandoahPrepareForCompactionTask : public WorkerTask {
 400 private:
 401   PreservedMarksSet*        const _preserved_marks;
 402   ShenandoahHeap*           const _heap;
 403   ShenandoahHeapRegionSet** const _worker_slices;
 404   size_t                    const _num_workers;
 405 
 406 public:
 407   ShenandoahPrepareForCompactionTask(PreservedMarksSet *preserved_marks, ShenandoahHeapRegionSet **worker_slices,
 408                                      size_t num_workers);
 409 
 410   static bool is_candidate_region(ShenandoahHeapRegion* r) {
 411     // Empty region: get it into the slice to defragment the slice itself.
 412     // We could have skipped this without violating correctness, but we really
 413     // want to compact all live regions to the start of the heap, which sometimes
 414     // means moving them into the fully empty regions.
 415     if (r->is_empty()) return true;
 416 
 417     // Can move the region, and this is not the humongous region. Humongous
 418     // moves are special cased here, because their moves are handled separately.
 419     return r->is_stw_move_allowed() && !r->is_humongous();
 420   }
 421 
 422   void work(uint worker_id);
 423 };
 424 
 425 class ShenandoahPrepareForGenerationalCompactionObjectClosure : public ObjectClosure {
 426 private:
 427   ShenandoahPrepareForCompactionTask* _compactor;
 428   PreservedMarks*          const _preserved_marks;
 429   ShenandoahHeap*          const _heap;
 430 
 431   // _empty_regions is a thread-local list of heap regions that have been completely emptied by this worker thread's
 432   // compaction efforts.  The worker thread that drives these efforts adds compacted regions to this list if the
 433   // region has not been compacted onto itself.
 434   GrowableArray<ShenandoahHeapRegion*>& _empty_regions;
 435   int _empty_regions_pos;
 436   ShenandoahHeapRegion*          _old_to_region;
 437   ShenandoahHeapRegion*          _young_to_region;
 438   ShenandoahHeapRegion*          _from_region;
 439   ShenandoahRegionAffiliation    _from_affiliation;
 440   HeapWord*                      _old_compact_point;
 441   HeapWord*                      _young_compact_point;
 442   uint                           _worker_id;
 443 
 444 public:
 445   ShenandoahPrepareForGenerationalCompactionObjectClosure(ShenandoahPrepareForCompactionTask* compactor,
 446                                                           PreservedMarks* preserved_marks,
 447                                                           GrowableArray<ShenandoahHeapRegion*>& empty_regions,
 448                                                           ShenandoahHeapRegion* old_to_region,
 449                                                           ShenandoahHeapRegion* young_to_region, uint worker_id) :
 450       _compactor(compactor),
 451       _preserved_marks(preserved_marks),
 452       _heap(ShenandoahHeap::heap()),
 453       _empty_regions(empty_regions),
 454       _empty_regions_pos(0),
 455       _old_to_region(old_to_region),
 456       _young_to_region(young_to_region),
 457       _from_region(NULL),
 458       _old_compact_point((old_to_region != nullptr)? old_to_region->bottom(): nullptr),
 459       _young_compact_point((young_to_region != nullptr)? young_to_region->bottom(): nullptr),
 460       _worker_id(worker_id) {}
 461 
 462   void set_from_region(ShenandoahHeapRegion* from_region) {
 463     _from_region = from_region;
 464     _from_affiliation = from_region->affiliation();
 465     if (_from_region->has_live()) {
 466       if (_from_affiliation == ShenandoahRegionAffiliation::OLD_GENERATION) {
 467         if (_old_to_region == nullptr) {
 468           _old_to_region = from_region;
 469           _old_compact_point = from_region->bottom();
 470         }
 471       } else {
 472         assert(_from_affiliation == ShenandoahRegionAffiliation::YOUNG_GENERATION, "from_region must be OLD or YOUNG");
 473         if (_young_to_region == nullptr) {
 474           _young_to_region = from_region;
 475           _young_compact_point = from_region->bottom();
 476         }
 477       }
 478     } // else, we won't iterate over this _from_region so we don't need to set up to region to hold copies
 479   }
 480 
 481   void finish() {
 482     finish_old_region();
 483     finish_young_region();
 484   }
 485 
 486   void finish_old_region() {
 487     if (_old_to_region != nullptr) {
 488       log_debug(gc)("Planned compaction into Old Region " SIZE_FORMAT ", used: " SIZE_FORMAT " tabulated by worker %u",
 489                     _old_to_region->index(), _old_compact_point - _old_to_region->bottom(), _worker_id);
 490       _old_to_region->set_new_top(_old_compact_point);
 491       _old_to_region = nullptr;
 492     }
 493   }
 494 
 495   void finish_young_region() {
 496     if (_young_to_region != nullptr) {
 497       log_debug(gc)("Worker %u planned compaction into Young Region " SIZE_FORMAT ", used: " SIZE_FORMAT,
 498                     _worker_id, _young_to_region->index(), _young_compact_point - _young_to_region->bottom());
 499       _young_to_region->set_new_top(_young_compact_point);
 500       _young_to_region = nullptr;
 501     }
 502   }
 503 
 504   bool is_compact_same_region() {
 505     return (_from_region == _old_to_region) || (_from_region == _young_to_region);
 506   }
 507 
 508   int empty_regions_pos() {
 509     return _empty_regions_pos;
 510   }
 511 
 512   void do_object(oop p) {
 513     assert(_from_region != NULL, "must set before work");
 514     assert((_from_region->bottom() <= cast_from_oop<HeapWord*>(p)) && (cast_from_oop<HeapWord*>(p) < _from_region->top()),
 515            "Object must reside in _from_region");
 516     assert(_heap->complete_marking_context()->is_marked(p), "must be marked");
 517     assert(!_heap->complete_marking_context()->allocated_after_mark_start(p), "must be truly marked");
 518 
 519     size_t obj_size = p->size();
 520     uint from_region_age = _from_region->age();
 521     uint object_age = p->age();
 522 
 523     bool promote_object = false;
 524     if ((_from_affiliation == ShenandoahRegionAffiliation::YOUNG_GENERATION) &&
 525         (from_region_age + object_age >= InitialTenuringThreshold)) {
 526       if ((_old_to_region != nullptr) && (_old_compact_point + obj_size > _old_to_region->end())) {
 527         finish_old_region();
 528         _old_to_region = nullptr;
 529       }
 530       if (_old_to_region == nullptr) {
 531         if (_empty_regions_pos < _empty_regions.length()) {
 532           ShenandoahHeapRegion* new_to_region = _empty_regions.at(_empty_regions_pos);
 533           _empty_regions_pos++;
 534           new_to_region->set_affiliation(OLD_GENERATION);
 535           _old_to_region = new_to_region;
 536           _old_compact_point = _old_to_region->bottom();
 537           promote_object = true;
 538         }
 539         // Else this worker thread does not yet have any empty regions into which this aged object can be promoted so
 540         // we leave promote_object as false, deferring the promotion.
 541       } else {
 542         promote_object = true;
 543       }
 544     }
 545 
 546     if (promote_object || (_from_affiliation == ShenandoahRegionAffiliation::OLD_GENERATION)) {
 547       assert(_old_to_region != nullptr, "_old_to_region should not be NULL when evacuating to OLD region");
 548       if (_old_compact_point + obj_size > _old_to_region->end()) {
 549         ShenandoahHeapRegion* new_to_region;
 550 
 551         log_debug(gc)("Worker %u finishing old region " SIZE_FORMAT ", compact_point: " PTR_FORMAT ", obj_size: " SIZE_FORMAT
 552                       ", &compact_point[obj_size]: " PTR_FORMAT ", region end: " PTR_FORMAT,  _worker_id, _old_to_region->index(),
 553                       p2i(_old_compact_point), obj_size, p2i(_old_compact_point + obj_size), p2i(_old_to_region->end()));
 554 
 555         // Object does not fit.  Get a new _old_to_region.
 556         finish_old_region();
 557         if (_empty_regions_pos < _empty_regions.length()) {
 558           new_to_region = _empty_regions.at(_empty_regions_pos);
 559           _empty_regions_pos++;
 560           new_to_region->set_affiliation(OLD_GENERATION);
 561         } else {
 562           // If we've exhausted the previously selected _old_to_region, we know that the _old_to_region is distinct
 563           // from _from_region.  That's because there is always room for _from_region to be compacted into itself.
 564           // Since we're out of empty regions, let's use _from_region to hold the results of its own compaction.
 565           new_to_region = _from_region;
 566         }
 567 
 568         assert(new_to_region != _old_to_region, "must not reuse same OLD to-region");
 569         assert(new_to_region != NULL, "must not be NULL");
 570         _old_to_region = new_to_region;
 571         _old_compact_point = _old_to_region->bottom();
 572       }
 573 
 574       // Object fits into current region, record new location:
 575       assert(_old_compact_point + obj_size <= _old_to_region->end(), "must fit");
 576       shenandoah_assert_not_forwarded(NULL, p);
 577       _preserved_marks->push_if_necessary(p, p->mark());
 578       p->forward_to(cast_to_oop(_old_compact_point));
 579       _old_compact_point += obj_size;
 580     } else {
 581       assert(_from_affiliation == ShenandoahRegionAffiliation::YOUNG_GENERATION,
 582              "_from_region must be OLD_GENERATION or YOUNG_GENERATION");
 583       assert(_young_to_region != nullptr, "_young_to_region should not be NULL when compacting YOUNG _from_region");
 584 
 585       // After full gc compaction, all regions have age 0.  Embed the region's age into the object's age in order to preserve
 586       // tenuring progress.
 587       _heap->increase_object_age(p, from_region_age + 1);
 588 
 589       if (_young_compact_point + obj_size > _young_to_region->end()) {
 590         ShenandoahHeapRegion* new_to_region;
 591 
 592         log_debug(gc)("Worker %u finishing young region " SIZE_FORMAT ", compact_point: " PTR_FORMAT ", obj_size: " SIZE_FORMAT
 593                       ", &compact_point[obj_size]: " PTR_FORMAT ", region end: " PTR_FORMAT,  _worker_id, _young_to_region->index(),
 594                       p2i(_young_compact_point), obj_size, p2i(_young_compact_point + obj_size), p2i(_young_to_region->end()));
 595 
 596         // Object does not fit.  Get a new _young_to_region.
 597         finish_young_region();
 598         if (_empty_regions_pos < _empty_regions.length()) {
 599           new_to_region = _empty_regions.at(_empty_regions_pos);
 600           _empty_regions_pos++;
 601           new_to_region->set_affiliation(YOUNG_GENERATION);
 602         } else {
 603           // If we've exhausted the previously selected _young_to_region, we know that the _young_to_region is distinct
 604           // from _from_region.  That's because there is always room for _from_region to be compacted into itself.
 605           // Since we're out of empty regions, let's use _from_region to hold the results of its own compaction.
 606           new_to_region = _from_region;
 607         }
 608 
 609         assert(new_to_region != _young_to_region, "must not reuse same OLD to-region");
 610         assert(new_to_region != NULL, "must not be NULL");
 611         _young_to_region = new_to_region;
 612         _young_compact_point = _young_to_region->bottom();
 613       }
 614 
 615       // Object fits into current region, record new location:
 616       assert(_young_compact_point + obj_size <= _young_to_region->end(), "must fit");
 617       shenandoah_assert_not_forwarded(NULL, p);
 618       _preserved_marks->push_if_necessary(p, p->mark());
 619       p->forward_to(cast_to_oop(_young_compact_point));
 620       _young_compact_point += obj_size;
 621     }
 622   }
 623 };
 624 
 625 
 626 class ShenandoahPrepareForCompactionObjectClosure : public ObjectClosure {
 627 private:
 628   PreservedMarks*          const _preserved_marks;
 629   ShenandoahHeap*          const _heap;
 630   GrowableArray<ShenandoahHeapRegion*>& _empty_regions;
 631   int _empty_regions_pos;
 632   ShenandoahHeapRegion*          _to_region;
 633   ShenandoahHeapRegion*          _from_region;
 634   HeapWord* _compact_point;
 635 
 636 public:
 637   ShenandoahPrepareForCompactionObjectClosure(PreservedMarks* preserved_marks,
 638                                               GrowableArray<ShenandoahHeapRegion*>& empty_regions,
 639                                               ShenandoahHeapRegion* to_region) :
 640     _preserved_marks(preserved_marks),
 641     _heap(ShenandoahHeap::heap()),
 642     _empty_regions(empty_regions),
 643     _empty_regions_pos(0),
 644     _to_region(to_region),
 645     _from_region(NULL),
 646     _compact_point(to_region->bottom()) {}
 647 
 648   void set_from_region(ShenandoahHeapRegion* from_region) {
 649     _from_region = from_region;
 650   }
 651 
 652   void finish_region() {
 653     assert(_to_region != NULL, "should not happen");
 654     assert(!_heap->mode()->is_generational(), "Generational GC should use different Closure");
 655     _to_region->set_new_top(_compact_point);
 656   }
 657 
 658   bool is_compact_same_region() {
 659     return _from_region == _to_region;
 660   }
 661 
 662   int empty_regions_pos() {
 663     return _empty_regions_pos;
 664   }
 665 
 666   void do_object(oop p) {
 667     assert(_from_region != NULL, "must set before work");
 668     assert(_heap->complete_marking_context()->is_marked(p), "must be marked");
 669     assert(!_heap->complete_marking_context()->allocated_after_mark_start(p), "must be truly marked");
 670 
 671     size_t obj_size = p->size();
 672     if (_compact_point + obj_size > _to_region->end()) {
 673       finish_region();
 674 
 675       // Object doesn't fit. Pick next empty region and start compacting there.
 676       ShenandoahHeapRegion* new_to_region;
 677       if (_empty_regions_pos < _empty_regions.length()) {
 678         new_to_region = _empty_regions.at(_empty_regions_pos);
 679         _empty_regions_pos++;
 680       } else {
 681         // Out of empty region? Compact within the same region.
 682         new_to_region = _from_region;
 683       }
 684 
 685       assert(new_to_region != _to_region, "must not reuse same to-region");
 686       assert(new_to_region != NULL, "must not be NULL");
 687       _to_region = new_to_region;
 688       _compact_point = _to_region->bottom();
 689     }
 690 
 691     // Object fits into current region, record new location:
 692     assert(_compact_point + obj_size <= _to_region->end(), "must fit");
 693     shenandoah_assert_not_forwarded(NULL, p);
 694     _preserved_marks->push_if_necessary(p, p->mark());
 695     p->forward_to(cast_to_oop(_compact_point));
 696     _compact_point += obj_size;
 697   }
 698 };
 699 
 700 
 701 ShenandoahPrepareForCompactionTask::ShenandoahPrepareForCompactionTask(PreservedMarksSet *preserved_marks,
 702                                                                        ShenandoahHeapRegionSet **worker_slices,
 703                                                                        size_t num_workers) :
 704     WorkerTask("Shenandoah Prepare For Compaction"),
 705     _preserved_marks(preserved_marks), _heap(ShenandoahHeap::heap()),
 706     _worker_slices(worker_slices), _num_workers(num_workers) { }
 707 
 708 
 709 void ShenandoahPrepareForCompactionTask::work(uint worker_id) {
 710   ShenandoahParallelWorkerSession worker_session(worker_id);
 711   ShenandoahHeapRegionSet* slice = _worker_slices[worker_id];
 712   ShenandoahHeapRegionSetIterator it(slice);
 713   ShenandoahHeapRegion* from_region = it.next();
 714   // No work?
 715   if (from_region == NULL) {
 716     return;
 717   }
 718 
 719   // Sliding compaction. Walk all regions in the slice, and compact them.
 720   // Remember empty regions and reuse them as needed.
 721   ResourceMark rm;
 722 
 723   GrowableArray<ShenandoahHeapRegion*> empty_regions((int)_heap->num_regions());
 724 
 725   if (_heap->mode()->is_generational()) {
 726     ShenandoahHeapRegion* old_to_region = (from_region->is_old())? from_region: nullptr;
 727     ShenandoahHeapRegion* young_to_region = (from_region->is_young())? from_region: nullptr;
 728     ShenandoahPrepareForGenerationalCompactionObjectClosure cl(this, _preserved_marks->get(worker_id), empty_regions,
 729                                                                old_to_region, young_to_region, worker_id);
 730     while (from_region != NULL) {
 731       assert(is_candidate_region(from_region), "Sanity");
 732       log_debug(gc)("Worker %u compacting %s Region " SIZE_FORMAT " which had used " SIZE_FORMAT " and %s live",
 733                     worker_id, affiliation_name(from_region->affiliation()),
 734                     from_region->index(), from_region->used(), from_region->has_live()? "has": "does not have");
 735       cl.set_from_region(from_region);
 736       if (from_region->has_live()) {
 737         _heap->marked_object_iterate(from_region, &cl);
 738       }
 739 
 740       // Compacted the region to somewhere else? From-region is empty then.
 741       if (!cl.is_compact_same_region()) {
 742         empty_regions.append(from_region);
 743       }
 744       from_region = it.next();
 745     }
 746     cl.finish();
 747 
 748     // Mark all remaining regions as empty
 749     for (int pos = cl.empty_regions_pos(); pos < empty_regions.length(); ++pos) {
 750       ShenandoahHeapRegion* r = empty_regions.at(pos);
 751       r->set_new_top(r->bottom());
 752     }
 753   } else {
 754     ShenandoahPrepareForCompactionObjectClosure cl(_preserved_marks->get(worker_id), empty_regions, from_region);
 755     while (from_region != NULL) {
 756       assert(is_candidate_region(from_region), "Sanity");
 757       cl.set_from_region(from_region);
 758       if (from_region->has_live()) {
 759         _heap->marked_object_iterate(from_region, &cl);
 760       }
 761 
 762       // Compacted the region to somewhere else? From-region is empty then.
 763       if (!cl.is_compact_same_region()) {
 764         empty_regions.append(from_region);
 765       }
 766       from_region = it.next();
 767     }
 768     cl.finish_region();
 769 
 770     // Mark all remaining regions as empty
 771     for (int pos = cl.empty_regions_pos(); pos < empty_regions.length(); ++pos) {
 772       ShenandoahHeapRegion* r = empty_regions.at(pos);
 773       r->set_new_top(r->bottom());
 774     }
 775   }
 776 }
 777 
 778 void ShenandoahFullGC::calculate_target_humongous_objects() {
 779   ShenandoahHeap* heap = ShenandoahHeap::heap();
 780 
 781   // Compute the new addresses for humongous objects. We need to do this after addresses
 782   // for regular objects are calculated, and we know what regions in heap suffix are
 783   // available for humongous moves.
 784   //
 785   // Scan the heap backwards, because we are compacting humongous regions towards the end.
 786   // Maintain the contiguous compaction window in [to_begin; to_end), so that we can slide
 787   // humongous start there.
 788   //
 789   // The complication is potential non-movable regions during the scan. If such region is
 790   // detected, then sliding restarts towards that non-movable region.
 791 
 792   size_t to_begin = heap->num_regions();
 793   size_t to_end = heap->num_regions();
 794 
 795   log_debug(gc)("Full GC calculating target humongous objects from end " SIZE_FORMAT, to_end);
 796   for (size_t c = heap->num_regions(); c > 0; c--) {
 797     ShenandoahHeapRegion *r = heap->get_region(c - 1);
 798     if (r->is_humongous_continuation() || (r->new_top() == r->bottom())) {
 799       // To-region candidate: record this, and continue scan
 800       to_begin = r->index();
 801       continue;
 802     }
 803 
 804     if (r->is_humongous_start() && r->is_stw_move_allowed()) {
 805       // From-region candidate: movable humongous region
 806       oop old_obj = cast_to_oop(r->bottom());
 807       size_t words_size = old_obj->size();
 808       size_t num_regions = ShenandoahHeapRegion::required_regions(words_size * HeapWordSize);
 809 
 810       size_t start = to_end - num_regions;
 811 
 812       if (start >= to_begin && start != r->index()) {
 813         // Fits into current window, and the move is non-trivial. Record the move then, and continue scan.
 814         _preserved_marks->get(0)->push_if_necessary(old_obj, old_obj->mark());
 815         old_obj->forward_to(cast_to_oop(heap->get_region(start)->bottom()));
 816         to_end = start;
 817         continue;
 818       }
 819     }
 820 
 821     // Failed to fit. Scan starting from current region.
 822     to_begin = r->index();
 823     to_end = r->index();
 824   }
 825 }
 826 
 827 class ShenandoahEnsureHeapActiveClosure: public ShenandoahHeapRegionClosure {
 828 private:
 829   ShenandoahHeap* const _heap;
 830 
 831 public:
 832   ShenandoahEnsureHeapActiveClosure() : _heap(ShenandoahHeap::heap()) {}
 833   void heap_region_do(ShenandoahHeapRegion* r) {
 834     bool is_generational = _heap->mode()->is_generational();
 835     if (r->is_trash()) {
 836       r->recycle();
 837     }
 838     if (r->is_cset()) {
 839       // Leave afffiliation unchanged.
 840       r->make_regular_bypass();
 841     }
 842     if (r->is_empty_uncommitted()) {
 843       r->make_committed_bypass();
 844     }
 845     assert (r->is_committed(), "only committed regions in heap now, see region " SIZE_FORMAT, r->index());
 846 
 847     // Record current region occupancy: this communicates empty regions are free
 848     // to the rest of Full GC code.
 849     r->set_new_top(r->top());
 850   }
 851 };
 852 
 853 class ShenandoahTrashImmediateGarbageClosure: public ShenandoahHeapRegionClosure {
 854 private:
 855   ShenandoahHeap* const _heap;
 856   ShenandoahMarkingContext* const _ctx;
 857 
 858 public:
 859   ShenandoahTrashImmediateGarbageClosure() :
 860     _heap(ShenandoahHeap::heap()),
 861     _ctx(ShenandoahHeap::heap()->complete_marking_context()) {}
 862 
 863   void heap_region_do(ShenandoahHeapRegion* r) {
 864     if (r->affiliation() != FREE) {
 865       if (r->is_humongous_start()) {
 866         oop humongous_obj = cast_to_oop(r->bottom());
 867         if (!_ctx->is_marked(humongous_obj)) {
 868           assert(!r->has_live(),
 869                  "Humongous Start %s Region " SIZE_FORMAT " is not marked, should not have live",
 870                  affiliation_name(r->affiliation()),  r->index());
 871           log_debug(gc)("Trashing immediate humongous region " SIZE_FORMAT " because not marked", r->index());
 872           _heap->trash_humongous_region_at(r);
 873         } else {
 874           assert(r->has_live(),
 875                  "Humongous Start %s Region " SIZE_FORMAT " should have live", affiliation_name(r->affiliation()),  r->index());
 876         }
 877       } else if (r->is_humongous_continuation()) {
 878         // If we hit continuation, the non-live humongous starts should have been trashed already
 879         assert(r->humongous_start_region()->has_live(),
 880                "Humongous Continuation %s Region " SIZE_FORMAT " should have live", affiliation_name(r->affiliation()),  r->index());
 881       } else if (r->is_regular()) {
 882         if (!r->has_live()) {
 883           log_debug(gc)("Trashing immediate regular region " SIZE_FORMAT " because has no live", r->index());
 884           r->make_trash_immediate();
 885         }
 886       }
 887     }
 888     // else, ignore this FREE region.
 889     // TODO: change iterators so they do not process FREE regions.
 890   }
 891 };
 892 
 893 void ShenandoahFullGC::distribute_slices(ShenandoahHeapRegionSet** worker_slices) {
 894   ShenandoahHeap* heap = ShenandoahHeap::heap();
 895 
 896   uint n_workers = heap->workers()->active_workers();
 897   size_t n_regions = heap->num_regions();
 898 
 899   // What we want to accomplish: have the dense prefix of data, while still balancing
 900   // out the parallel work.
 901   //
 902   // Assuming the amount of work is driven by the live data that needs moving, we can slice
 903   // the entire heap into equal-live-sized prefix slices, and compact into them. So, each
 904   // thread takes all regions in its prefix subset, and then it takes some regions from
 905   // the tail.
 906   //
 907   // Tail region selection becomes interesting.
 908   //
 909   // First, we want to distribute the regions fairly between the workers, and those regions
 910   // might have different amount of live data. So, until we sure no workers need live data,
 911   // we need to only take what the worker needs.
 912   //
 913   // Second, since we slide everything to the left in each slice, the most busy regions
 914   // would be the ones on the left. Which means we want to have all workers have their after-tail
 915   // regions as close to the left as possible.
 916   //
 917   // The easiest way to do this is to distribute after-tail regions in round-robin between
 918   // workers that still need live data.
 919   //
 920   // Consider parallel workers A, B, C, then the target slice layout would be:
 921   //
 922   //  AAAAAAAABBBBBBBBCCCCCCCC|ABCABCABCABCABCABCABCABABABABABABABABABABAAAAA
 923   //
 924   //  (.....dense-prefix.....) (.....................tail...................)
 925   //  [all regions fully live] [left-most regions are fuller that right-most]
 926   //
 927 
 928   // Compute how much live data is there. This would approximate the size of dense prefix
 929   // we target to create.
 930   size_t total_live = 0;
 931   for (size_t idx = 0; idx < n_regions; idx++) {
 932     ShenandoahHeapRegion *r = heap->get_region(idx);
 933     if (ShenandoahPrepareForCompactionTask::is_candidate_region(r)) {
 934       total_live += r->get_live_data_words();
 935     }
 936   }
 937 
 938   // Estimate the size for the dense prefix. Note that we specifically count only the
 939   // "full" regions, so there would be some non-full regions in the slice tail.
 940   size_t live_per_worker = total_live / n_workers;
 941   size_t prefix_regions_per_worker = live_per_worker / ShenandoahHeapRegion::region_size_words();
 942   size_t prefix_regions_total = prefix_regions_per_worker * n_workers;
 943   prefix_regions_total = MIN2(prefix_regions_total, n_regions);
 944   assert(prefix_regions_total <= n_regions, "Sanity");
 945 
 946   // There might be non-candidate regions in the prefix. To compute where the tail actually
 947   // ends up being, we need to account those as well.
 948   size_t prefix_end = prefix_regions_total;
 949   for (size_t idx = 0; idx < prefix_regions_total; idx++) {
 950     ShenandoahHeapRegion *r = heap->get_region(idx);
 951     if (!ShenandoahPrepareForCompactionTask::is_candidate_region(r)) {
 952       prefix_end++;
 953     }
 954   }
 955   prefix_end = MIN2(prefix_end, n_regions);
 956   assert(prefix_end <= n_regions, "Sanity");
 957 
 958   // Distribute prefix regions per worker: each thread definitely gets its own same-sized
 959   // subset of dense prefix.
 960   size_t prefix_idx = 0;
 961 
 962   size_t* live = NEW_C_HEAP_ARRAY(size_t, n_workers, mtGC);
 963 
 964   for (size_t wid = 0; wid < n_workers; wid++) {
 965     ShenandoahHeapRegionSet* slice = worker_slices[wid];
 966 
 967     live[wid] = 0;
 968     size_t regs = 0;
 969 
 970     // Add all prefix regions for this worker
 971     while (prefix_idx < prefix_end && regs < prefix_regions_per_worker) {
 972       ShenandoahHeapRegion *r = heap->get_region(prefix_idx);
 973       if (ShenandoahPrepareForCompactionTask::is_candidate_region(r)) {
 974         slice->add_region(r);
 975         live[wid] += r->get_live_data_words();
 976         regs++;
 977       }
 978       prefix_idx++;
 979     }
 980   }
 981 
 982   // Distribute the tail among workers in round-robin fashion.
 983   size_t wid = n_workers - 1;
 984 
 985   for (size_t tail_idx = prefix_end; tail_idx < n_regions; tail_idx++) {
 986     ShenandoahHeapRegion *r = heap->get_region(tail_idx);
 987     if (ShenandoahPrepareForCompactionTask::is_candidate_region(r)) {
 988       assert(wid < n_workers, "Sanity");
 989 
 990       size_t live_region = r->get_live_data_words();
 991 
 992       // Select next worker that still needs live data.
 993       size_t old_wid = wid;
 994       do {
 995         wid++;
 996         if (wid == n_workers) wid = 0;
 997       } while (live[wid] + live_region >= live_per_worker && old_wid != wid);
 998 
 999       if (old_wid == wid) {
1000         // Circled back to the same worker? This means liveness data was
1001         // miscalculated. Bump the live_per_worker limit so that
1002         // everyone gets a piece of the leftover work.
1003         live_per_worker += ShenandoahHeapRegion::region_size_words();
1004       }
1005 
1006       worker_slices[wid]->add_region(r);
1007       live[wid] += live_region;
1008     }
1009   }
1010 
1011   FREE_C_HEAP_ARRAY(size_t, live);
1012 
1013 #ifdef ASSERT
1014   ResourceBitMap map(n_regions);
1015   for (size_t wid = 0; wid < n_workers; wid++) {
1016     ShenandoahHeapRegionSetIterator it(worker_slices[wid]);
1017     ShenandoahHeapRegion* r = it.next();
1018     while (r != NULL) {
1019       size_t idx = r->index();
1020       assert(ShenandoahPrepareForCompactionTask::is_candidate_region(r), "Sanity: " SIZE_FORMAT, idx);
1021       assert(!map.at(idx), "No region distributed twice: " SIZE_FORMAT, idx);
1022       map.at_put(idx, true);
1023       r = it.next();
1024     }
1025   }
1026 
1027   for (size_t rid = 0; rid < n_regions; rid++) {
1028     bool is_candidate = ShenandoahPrepareForCompactionTask::is_candidate_region(heap->get_region(rid));
1029     bool is_distributed = map.at(rid);
1030     assert(is_distributed || !is_candidate, "All candidates are distributed: " SIZE_FORMAT, rid);
1031   }
1032 #endif
1033 }
1034 
1035 void ShenandoahFullGC::phase2_calculate_target_addresses(ShenandoahHeapRegionSet** worker_slices) {
1036   GCTraceTime(Info, gc, phases) time("Phase 2: Compute new object addresses", _gc_timer);
1037   ShenandoahGCPhase calculate_address_phase(ShenandoahPhaseTimings::full_gc_calculate_addresses);
1038 
1039   ShenandoahHeap* heap = ShenandoahHeap::heap();
1040 
1041   // About to figure out which regions can be compacted, make sure pinning status
1042   // had been updated in GC prologue.
1043   heap->assert_pinned_region_status();
1044 
1045   {
1046     // Trash the immediately collectible regions before computing addresses
1047     ShenandoahTrashImmediateGarbageClosure tigcl;
1048     heap->heap_region_iterate(&tigcl);
1049 
1050     // Make sure regions are in good state: committed, active, clean.
1051     // This is needed because we are potentially sliding the data through them.
1052     ShenandoahEnsureHeapActiveClosure ecl;
1053     heap->heap_region_iterate(&ecl);
1054   }
1055 
1056   if (heap->mode()->is_generational()) {
1057     heap->young_generation()->clear_used();
1058     heap->old_generation()->clear_used();
1059   }
1060 
1061   // Compute the new addresses for regular objects
1062   {
1063     ShenandoahGCPhase phase(ShenandoahPhaseTimings::full_gc_calculate_addresses_regular);
1064 
1065     distribute_slices(worker_slices);
1066 
1067     size_t num_workers = heap->max_workers();
1068 
1069     ResourceMark rm;
1070     ShenandoahPrepareForCompactionTask task(_preserved_marks, worker_slices, num_workers);
1071     heap->workers()->run_task(&task);
1072   }
1073 
1074   // Compute the new addresses for humongous objects
1075   {
1076     ShenandoahGCPhase phase(ShenandoahPhaseTimings::full_gc_calculate_addresses_humong);
1077     calculate_target_humongous_objects();
1078   }
1079 }
1080 
1081 class ShenandoahAdjustPointersClosure : public MetadataVisitingOopIterateClosure {
1082 private:
1083   ShenandoahHeap* const _heap;
1084   ShenandoahMarkingContext* const _ctx;
1085 
1086   template <class T>
1087   inline void do_oop_work(T* p) {
1088     T o = RawAccess<>::oop_load(p);
1089     if (!CompressedOops::is_null(o)) {
1090       oop obj = CompressedOops::decode_not_null(o);
1091       assert(_ctx->is_marked(obj), "must be marked");
1092       if (obj->is_forwarded()) {
1093         oop forw = obj->forwardee();
1094         RawAccess<IS_NOT_NULL>::oop_store(p, forw);
1095       }
1096     }
1097   }
1098 
1099 public:
1100   ShenandoahAdjustPointersClosure() :
1101     _heap(ShenandoahHeap::heap()),
1102     _ctx(ShenandoahHeap::heap()->complete_marking_context()) {}
1103 
1104   void do_oop(oop* p)       { do_oop_work(p); }
1105   void do_oop(narrowOop* p) { do_oop_work(p); }
1106   void do_method(Method* m) {}
1107   void do_nmethod(nmethod* nm) {}
1108 };
1109 
1110 class ShenandoahAdjustPointersObjectClosure : public ObjectClosure {
1111 private:
1112   ShenandoahHeap* const _heap;
1113   ShenandoahAdjustPointersClosure _cl;
1114 
1115 public:
1116   ShenandoahAdjustPointersObjectClosure() :
1117     _heap(ShenandoahHeap::heap()) {
1118   }
1119   void do_object(oop p) {
1120     assert(_heap->complete_marking_context()->is_marked(p), "must be marked");
1121     p->oop_iterate(&_cl);
1122   }
1123 };
1124 
1125 class ShenandoahAdjustPointersTask : public WorkerTask {
1126 private:
1127   ShenandoahHeap*          const _heap;
1128   ShenandoahRegionIterator       _regions;
1129 
1130 public:
1131   ShenandoahAdjustPointersTask() :
1132     WorkerTask("Shenandoah Adjust Pointers"),
1133     _heap(ShenandoahHeap::heap()) {
1134   }
1135 
1136   void work(uint worker_id) {
1137     ShenandoahParallelWorkerSession worker_session(worker_id);
1138     ShenandoahAdjustPointersObjectClosure obj_cl;
1139     ShenandoahHeapRegion* r = _regions.next();
1140     while (r != NULL) {
1141       if (!r->is_humongous_continuation() && r->has_live()) {
1142         _heap->marked_object_iterate(r, &obj_cl);
1143       }
1144       if (r->is_pinned() && r->is_old() && r->is_active() && !r->is_humongous()) {
1145         // Pinned regions are not compacted so they may still hold unmarked objects with
1146         // reference to reclaimed memory. Remembered set scanning will crash if it attempts
1147         // to iterate the oops in these objects.
1148         r->begin_preemptible_coalesce_and_fill();
1149         r->oop_fill_and_coalesce_wo_cancel();
1150       }
1151       r = _regions.next();
1152     }
1153   }
1154 };
1155 
1156 class ShenandoahAdjustRootPointersTask : public WorkerTask {
1157 private:
1158   ShenandoahRootAdjuster* _rp;
1159   PreservedMarksSet* _preserved_marks;
1160 public:
1161   ShenandoahAdjustRootPointersTask(ShenandoahRootAdjuster* rp, PreservedMarksSet* preserved_marks) :
1162     WorkerTask("Shenandoah Adjust Root Pointers"),
1163     _rp(rp),
1164     _preserved_marks(preserved_marks) {}
1165 
1166   void work(uint worker_id) {
1167     ShenandoahParallelWorkerSession worker_session(worker_id);
1168     ShenandoahAdjustPointersClosure cl;
1169     _rp->roots_do(worker_id, &cl);
1170     _preserved_marks->get(worker_id)->adjust_during_full_gc();
1171   }
1172 };
1173 
1174 void ShenandoahFullGC::phase3_update_references() {
1175   GCTraceTime(Info, gc, phases) time("Phase 3: Adjust pointers", _gc_timer);
1176   ShenandoahGCPhase adjust_pointer_phase(ShenandoahPhaseTimings::full_gc_adjust_pointers);
1177 
1178   ShenandoahHeap* heap = ShenandoahHeap::heap();
1179 
1180   WorkerThreads* workers = heap->workers();
1181   uint nworkers = workers->active_workers();
1182   {
1183 #if COMPILER2_OR_JVMCI
1184     DerivedPointerTable::clear();
1185 #endif
1186     ShenandoahRootAdjuster rp(nworkers, ShenandoahPhaseTimings::full_gc_adjust_roots);
1187     ShenandoahAdjustRootPointersTask task(&rp, _preserved_marks);
1188     workers->run_task(&task);
1189 #if COMPILER2_OR_JVMCI
1190     DerivedPointerTable::update_pointers();
1191 #endif
1192   }
1193 
1194   ShenandoahAdjustPointersTask adjust_pointers_task;
1195   workers->run_task(&adjust_pointers_task);
1196 }
1197 
1198 class ShenandoahCompactObjectsClosure : public ObjectClosure {
1199 private:
1200   ShenandoahHeap* const _heap;
1201   uint            const _worker_id;
1202 
1203 public:
1204   ShenandoahCompactObjectsClosure(uint worker_id) :
1205     _heap(ShenandoahHeap::heap()), _worker_id(worker_id) {}
1206 
1207   void do_object(oop p) {
1208     assert(_heap->complete_marking_context()->is_marked(p), "must be marked");
1209     size_t size = p->size();
1210     if (p->is_forwarded()) {
1211       HeapWord* compact_from = cast_from_oop<HeapWord*>(p);
1212       HeapWord* compact_to = cast_from_oop<HeapWord*>(p->forwardee());
1213       Copy::aligned_conjoint_words(compact_from, compact_to, size);
1214       oop new_obj = cast_to_oop(compact_to);
1215 
1216       ContinuationGCSupport::relativize_stack_chunk(new_obj);
1217       new_obj->init_mark();
1218     }
1219   }
1220 };
1221 
1222 class ShenandoahCompactObjectsTask : public WorkerTask {
1223 private:
1224   ShenandoahHeap* const _heap;
1225   ShenandoahHeapRegionSet** const _worker_slices;
1226 
1227 public:
1228   ShenandoahCompactObjectsTask(ShenandoahHeapRegionSet** worker_slices) :
1229     WorkerTask("Shenandoah Compact Objects"),
1230     _heap(ShenandoahHeap::heap()),
1231     _worker_slices(worker_slices) {
1232   }
1233 
1234   void work(uint worker_id) {
1235     ShenandoahParallelWorkerSession worker_session(worker_id);
1236     ShenandoahHeapRegionSetIterator slice(_worker_slices[worker_id]);
1237 
1238     ShenandoahCompactObjectsClosure cl(worker_id);
1239     ShenandoahHeapRegion* r = slice.next();
1240     while (r != NULL) {
1241       assert(!r->is_humongous(), "must not get humongous regions here");
1242       if (r->has_live()) {
1243         _heap->marked_object_iterate(r, &cl);
1244       }
1245       r->set_top(r->new_top());
1246       r = slice.next();
1247     }
1248   }
1249 };
1250 
1251 class ShenandoahPostCompactClosure : public ShenandoahHeapRegionClosure {
1252 private:
1253   ShenandoahHeap* const _heap;
1254   size_t _live;
1255 
1256 public:
1257   ShenandoahPostCompactClosure() : _heap(ShenandoahHeap::heap()), _live(0) {
1258     _heap->free_set()->clear();
1259   }
1260 
1261   void heap_region_do(ShenandoahHeapRegion* r) {
1262     assert (!r->is_cset(), "cset regions should have been demoted already");
1263     bool is_generational = _heap->mode()->is_generational();
1264 
1265     // Need to reset the complete-top-at-mark-start pointer here because
1266     // the complete marking bitmap is no longer valid. This ensures
1267     // size-based iteration in marked_object_iterate().
1268     // NOTE: See blurb at ShenandoahMCResetCompleteBitmapTask on why we need to skip
1269     // pinned regions.
1270     if (!r->is_pinned()) {
1271       _heap->complete_marking_context()->reset_top_at_mark_start(r);
1272     }
1273 
1274     size_t live = r->used();
1275 
1276     // Make empty regions that have been allocated into regular
1277     if (r->is_empty() && live > 0) {
1278       if (!is_generational) {
1279         r->make_young_maybe();
1280       }
1281       // else, generational mode compaction has already established affiliation.
1282       r->make_regular_bypass();
1283     }
1284 
1285     // Reclaim regular regions that became empty
1286     if (r->is_regular() && live == 0) {
1287       r->make_trash();
1288     }
1289 
1290     // Recycle all trash regions
1291     if (r->is_trash()) {
1292       live = 0;
1293       r->recycle();
1294     }
1295 
1296     // Update final usage for generations
1297     if (is_generational && live != 0) {
1298       if (r->is_young()) {
1299         _heap->young_generation()->increase_used(live);
1300       } else if (r->is_old()) {
1301         _heap->old_generation()->increase_used(live);
1302       }
1303     }
1304 
1305     r->set_live_data(live);
1306     r->reset_alloc_metadata();
1307     _live += live;
1308   }
1309 
1310   size_t get_live() {
1311     return _live;
1312   }
1313 };
1314 
1315 void ShenandoahFullGC::compact_humongous_objects() {
1316   // Compact humongous regions, based on their fwdptr objects.
1317   //
1318   // This code is serial, because doing the in-slice parallel sliding is tricky. In most cases,
1319   // humongous regions are already compacted, and do not require further moves, which alleviates
1320   // sliding costs. We may consider doing this in parallel in future.
1321 
1322   ShenandoahHeap* heap = ShenandoahHeap::heap();
1323 
1324   for (size_t c = heap->num_regions(); c > 0; c--) {
1325     ShenandoahHeapRegion* r = heap->get_region(c - 1);
1326     if (r->is_humongous_start()) {
1327       oop old_obj = cast_to_oop(r->bottom());
1328       if (!old_obj->is_forwarded()) {
1329         // No need to move the object, it stays at the same slot
1330         continue;
1331       }
1332       size_t words_size = old_obj->size();
1333       size_t num_regions = ShenandoahHeapRegion::required_regions(words_size * HeapWordSize);
1334 
1335       size_t old_start = r->index();
1336       size_t old_end   = old_start + num_regions - 1;
1337       size_t new_start = heap->heap_region_index_containing(old_obj->forwardee());
1338       size_t new_end   = new_start + num_regions - 1;
1339       assert(old_start != new_start, "must be real move");
1340       assert(r->is_stw_move_allowed(), "Region " SIZE_FORMAT " should be movable", r->index());
1341 
1342       ContinuationGCSupport::relativize_stack_chunk(cast_to_oop<HeapWord*>(heap->get_region(old_start)->bottom()));
1343       log_debug(gc)("Full GC compaction moves humongous object from region " SIZE_FORMAT " to region " SIZE_FORMAT,
1344                     old_start, new_start);
1345 
1346       Copy::aligned_conjoint_words(heap->get_region(old_start)->bottom(),
1347                                    heap->get_region(new_start)->bottom(),
1348                                    words_size);
1349 
1350       oop new_obj = cast_to_oop(heap->get_region(new_start)->bottom());
1351       new_obj->init_mark();
1352 
1353       {
1354         ShenandoahRegionAffiliation original_affiliation = r->affiliation();
1355         for (size_t c = old_start; c <= old_end; c++) {
1356           ShenandoahHeapRegion* r = heap->get_region(c);
1357           // Leave humongous region affiliation unchanged.
1358           r->make_regular_bypass();
1359           r->set_top(r->bottom());
1360         }
1361 
1362         for (size_t c = new_start; c <= new_end; c++) {
1363           ShenandoahHeapRegion* r = heap->get_region(c);
1364           if (c == new_start) {
1365             r->make_humongous_start_bypass(original_affiliation);
1366           } else {
1367             r->make_humongous_cont_bypass(original_affiliation);
1368           }
1369 
1370           // Trailing region may be non-full, record the remainder there
1371           size_t remainder = words_size & ShenandoahHeapRegion::region_size_words_mask();
1372           if ((c == new_end) && (remainder != 0)) {
1373             r->set_top(r->bottom() + remainder);
1374           } else {
1375             r->set_top(r->end());
1376           }
1377 
1378           r->reset_alloc_metadata();
1379         }
1380       }
1381     }
1382   }
1383 }
1384 
1385 // This is slightly different to ShHeap::reset_next_mark_bitmap:
1386 // we need to remain able to walk pinned regions.
1387 // Since pinned region do not move and don't get compacted, we will get holes with
1388 // unreachable objects in them (which may have pointers to unloaded Klasses and thus
1389 // cannot be iterated over using oop->size(). The only way to safely iterate over those is using
1390 // a valid marking bitmap and valid TAMS pointer. This class only resets marking
1391 // bitmaps for un-pinned regions, and later we only reset TAMS for unpinned regions.
1392 class ShenandoahMCResetCompleteBitmapTask : public WorkerTask {
1393 private:
1394   ShenandoahRegionIterator _regions;
1395 
1396 public:
1397   ShenandoahMCResetCompleteBitmapTask() :
1398     WorkerTask("Shenandoah Reset Bitmap") {
1399   }
1400 
1401   void work(uint worker_id) {
1402     ShenandoahParallelWorkerSession worker_session(worker_id);
1403     ShenandoahHeapRegion* region = _regions.next();
1404     ShenandoahHeap* heap = ShenandoahHeap::heap();
1405     ShenandoahMarkingContext* const ctx = heap->complete_marking_context();
1406     while (region != NULL) {
1407       if (heap->is_bitmap_slice_committed(region) && !region->is_pinned() && region->has_live()) {
1408         ctx->clear_bitmap(region);
1409       }
1410       region = _regions.next();
1411     }
1412   }
1413 };
1414 
1415 void ShenandoahFullGC::phase4_compact_objects(ShenandoahHeapRegionSet** worker_slices) {
1416   GCTraceTime(Info, gc, phases) time("Phase 4: Move objects", _gc_timer);
1417   ShenandoahGCPhase compaction_phase(ShenandoahPhaseTimings::full_gc_copy_objects);
1418 
1419   ShenandoahHeap* heap = ShenandoahHeap::heap();
1420 
1421   // Compact regular objects first
1422   {
1423     ShenandoahGCPhase phase(ShenandoahPhaseTimings::full_gc_copy_objects_regular);
1424     ShenandoahCompactObjectsTask compact_task(worker_slices);
1425     heap->workers()->run_task(&compact_task);
1426   }
1427 
1428   // Compact humongous objects after regular object moves
1429   {
1430     ShenandoahGCPhase phase(ShenandoahPhaseTimings::full_gc_copy_objects_humong);
1431     compact_humongous_objects();
1432   }
1433 
1434   // Reset complete bitmap. We're about to reset the complete-top-at-mark-start pointer
1435   // and must ensure the bitmap is in sync.
1436   {
1437     ShenandoahGCPhase phase(ShenandoahPhaseTimings::full_gc_copy_objects_reset_complete);
1438     ShenandoahMCResetCompleteBitmapTask task;
1439     heap->workers()->run_task(&task);
1440   }
1441 
1442   // Bring regions in proper states after the collection, and set heap properties.
1443   {
1444     ShenandoahGCPhase phase(ShenandoahPhaseTimings::full_gc_copy_objects_rebuild);
1445 
1446     if (heap->mode()->is_generational()) {
1447       heap->young_generation()->clear_used();
1448       heap->old_generation()->clear_used();
1449     }
1450 
1451     ShenandoahPostCompactClosure post_compact;
1452     heap->heap_region_iterate(&post_compact);
1453     heap->set_used(post_compact.get_live());
1454     if (heap->mode()->is_generational()) {
1455       log_info(gc)("FullGC done: GLOBAL usage: " SIZE_FORMAT ", young usage: " SIZE_FORMAT ", old usage: " SIZE_FORMAT,
1456                     post_compact.get_live(), heap->young_generation()->used(), heap->old_generation()->used());
1457     }
1458 
1459     heap->collection_set()->clear();
1460     heap->free_set()->rebuild();
1461   }
1462 
1463   heap->clear_cancelled_gc(true /* clear oom handler */);
1464 }