1 /*
   2  * Copyright (c) 2014, 2019, Red Hat, Inc. All rights reserved.
   3  *
   4  * This code is free software; you can redistribute it and/or modify it
   5  * under the terms of the GNU General Public License version 2 only, as
   6  * published by the Free Software Foundation.
   7  *
   8  * This code is distributed in the hope that it will be useful, but WITHOUT
   9  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  10  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  11  * version 2 for more details (a copy is included in the LICENSE file that
  12  * accompanied this code).
  13  *
  14  * You should have received a copy of the GNU General Public License version
  15  * 2 along with this work; if not, write to the Free Software Foundation,
  16  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  17  *
  18  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  19  * or visit www.oracle.com if you need additional information or have any
  20  * questions.
  21  *
  22  */
  23 
  24 #include "precompiled.hpp"
  25 
  26 #include "code/codeCache.hpp"
  27 #include "gc/shared/gcTraceTime.inline.hpp"
  28 #include "gc/shenandoah/shenandoahBrooksPointer.hpp"
  29 #include "gc/shenandoah/shenandoahConcurrentMark.inline.hpp"
  30 #include "gc/shenandoah/shenandoahCollectionSet.hpp"
  31 #include "gc/shenandoah/shenandoahFreeSet.hpp"
  32 #include "gc/shenandoah/shenandoahPhaseTimings.hpp"
  33 #include "gc/shenandoah/shenandoahMarkCompact.hpp"
  34 #include "gc/shenandoah/shenandoahHeapRegionSet.hpp"
  35 #include "gc/shenandoah/shenandoahHeap.inline.hpp"
  36 #include "gc/shenandoah/shenandoahHeuristics.hpp"
  37 #include "gc/shenandoah/shenandoahMarkingContext.inline.hpp"
  38 #include "gc/shenandoah/shenandoahRootProcessor.hpp"
  39 #include "gc/shenandoah/shenandoahTraversalGC.hpp"
  40 #include "gc/shenandoah/shenandoahTaskqueue.inline.hpp"
  41 #include "gc/shenandoah/shenandoahUtils.hpp"
  42 #include "gc/shenandoah/shenandoahVerifier.hpp"
  43 #include "gc/shenandoah/shenandoahVMOperations.hpp"
  44 #include "gc/shenandoah/shenandoahWorkerPolicy.hpp"
  45 #include "memory/metaspace.hpp"
  46 #include "oops/oop.inline.hpp"
  47 #include "runtime/thread.hpp"
  48 #include "utilities/copy.hpp"
  49 #include "utilities/growableArray.hpp"
  50 #include "gc/shared/workgroup.hpp"
  51 
  52 void ShenandoahMarkCompact::initialize(GCTimer* gc_timer) {
  53   _gc_timer = gc_timer;
  54 }
  55 
  56 void ShenandoahMarkCompact::do_it(GCCause::Cause gc_cause) {
  57   ShenandoahHeap* heap = ShenandoahHeap::heap();
  58 
  59   if (ShenandoahVerify) {
  60     heap->verifier()->verify_before_fullgc();
  61   }
  62 
  63   if (VerifyBeforeGC) {
  64     Universe::verify();
  65   }
  66 
  67   heap->set_full_gc_in_progress(true);
  68 
  69   assert(ShenandoahSafepoint::is_at_shenandoah_safepoint(), "must be at a safepoint");
  70   assert(Thread::current()->is_VM_thread(), "Do full GC only while world is stopped");
  71 
  72   {
  73     ShenandoahGCPhase phase(ShenandoahPhaseTimings::full_gc_heapdumps);
  74     heap->pre_full_gc_dump(_gc_timer);
  75   }
  76 
  77   {
  78     ShenandoahGCPhase prepare_phase(ShenandoahPhaseTimings::full_gc_prepare);
  79     // Full GC is supposed to recover from any GC state:
  80 
  81     // a0. Remember if we have forwarded objects
  82     bool has_forwarded_objects = heap->has_forwarded_objects();
  83 
  84     // a1. Cancel evacuation, if in progress
  85     if (heap->is_evacuation_in_progress()) {
  86       heap->set_evacuation_in_progress(false);
  87     }
  88     assert(!heap->is_evacuation_in_progress(), "sanity");
  89 
  90     // a2. Cancel update-refs, if in progress
  91     if (heap->is_update_refs_in_progress()) {
  92       heap->set_update_refs_in_progress(false);
  93     }
  94     assert(!heap->is_update_refs_in_progress(), "sanity");
  95 
  96     // a3. Cancel concurrent traversal GC, if in progress
  97     if (heap->is_concurrent_traversal_in_progress()) {
  98       heap->traversal_gc()->reset();
  99       heap->set_concurrent_traversal_in_progress(false);
 100     }
 101 
 102     // b. Cancel concurrent mark, if in progress
 103     if (heap->is_concurrent_mark_in_progress()) {
 104       heap->concurrent_mark()->cancel();
 105       heap->stop_concurrent_marking();
 106     }
 107     assert(!heap->is_concurrent_mark_in_progress(), "sanity");
 108 
 109     // c. Reset the bitmaps for new marking
 110     heap->reset_mark_bitmap();
 111     assert(heap->marking_context()->is_bitmap_clear(), "sanity");
 112     assert(!heap->marking_context()->is_complete(), "sanity");
 113 
 114     // d. Abandon reference discovery and clear all discovered references.
 115     ReferenceProcessor* rp = heap->ref_processor();
 116     rp->disable_discovery();
 117     rp->abandon_partial_discovery();
 118     rp->verify_no_references_recorded();
 119 
 120     // e. Set back forwarded objects bit back, in case some steps above dropped it.
 121     heap->set_has_forwarded_objects(has_forwarded_objects);
 122   }
 123 
 124   heap->make_parsable(true);
 125 
 126   CodeCache::gc_prologue();
 127 
 128   OrderAccess::fence();
 129 
 130   phase1_mark_heap();
 131 
 132   // Once marking is done, which may have fixed up forwarded objects, we can drop it.
 133   // Coming out of Full GC, we would not have any forwarded objects.
 134   // This also prevents read barrier from kicking in while adjusting pointers in phase3.
 135   heap->set_has_forwarded_objects(false);
 136 
 137   heap->set_full_gc_move_in_progress(true);
 138 
 139   // Setup workers for the rest
 140   OrderAccess::fence();
 141 
 142   // Initialize worker slices
 143   ShenandoahHeapRegionSet** worker_slices = NEW_C_HEAP_ARRAY(ShenandoahHeapRegionSet*, heap->max_workers(), mtGC);
 144   for (uint i = 0; i < heap->max_workers(); i++) {
 145     worker_slices[i] = new ShenandoahHeapRegionSet();
 146   }
 147 
 148   {
 149     // The rest of code performs region moves, where region status is undefined
 150     // until all phases run together.
 151     ShenandoahHeapLocker lock(heap->lock());
 152 
 153     phase2_calculate_target_addresses(worker_slices);
 154 
 155     OrderAccess::fence();
 156 
 157     phase3_update_references();
 158 
 159     phase4_compact_objects(worker_slices);
 160   }
 161 
 162   // Resize metaspace
 163   MetaspaceGC::compute_new_size();
 164 
 165   // Free worker slices
 166   for (uint i = 0; i < heap->max_workers(); i++) {
 167     delete worker_slices[i];
 168   }
 169   FREE_C_HEAP_ARRAY(ShenandoahHeapRegionSet*, worker_slices);
 170 
 171   CodeCache::gc_epilogue();
 172   JvmtiExport::gc_epilogue();
 173 
 174   heap->set_full_gc_move_in_progress(false);
 175   heap->set_full_gc_in_progress(false);
 176 
 177   if (ShenandoahVerify) {
 178     heap->verifier()->verify_after_fullgc();
 179   }
 180 
 181   if (VerifyAfterGC) {
 182     Universe::verify();
 183   }
 184 
 185   {
 186     ShenandoahGCPhase phase(ShenandoahPhaseTimings::full_gc_heapdumps);
 187     heap->post_full_gc_dump(_gc_timer);
 188   }
 189 }
 190 
 191 class ShenandoahPrepareForMarkClosure: public ShenandoahHeapRegionClosure {
 192 private:
 193   ShenandoahMarkingContext* const _ctx;
 194 
 195 public:
 196   ShenandoahPrepareForMarkClosure() : _ctx(ShenandoahHeap::heap()->marking_context()) {}
 197 
 198   void heap_region_do(ShenandoahHeapRegion *r) {
 199     _ctx->capture_top_at_mark_start(r);
 200     r->clear_live_data();
 201     r->set_concurrent_iteration_safe_limit(r->top());
 202   }
 203 };
 204 
 205 void ShenandoahMarkCompact::phase1_mark_heap() {
 206   GCTraceTime(Info, gc, phases) time("Phase 1: Mark live objects", _gc_timer);
 207   ShenandoahGCPhase mark_phase(ShenandoahPhaseTimings::full_gc_mark);
 208 
 209   ShenandoahHeap* heap = ShenandoahHeap::heap();
 210 
 211   ShenandoahPrepareForMarkClosure cl;
 212   heap->heap_region_iterate(&cl);
 213 
 214   ShenandoahConcurrentMark* cm = heap->concurrent_mark();
 215 
 216   heap->set_process_references(heap->heuristics()->can_process_references());
 217   heap->set_unload_classes(heap->heuristics()->can_unload_classes());
 218 
 219   ReferenceProcessor* rp = heap->ref_processor();
 220   // enable ("weak") refs discovery
 221   rp->enable_discovery(true /*verify_no_refs*/);
 222   rp->setup_policy(true); // forcefully purge all soft references
 223   rp->set_active_mt_degree(heap->workers()->active_workers());
 224 
 225   cm->update_roots(ShenandoahPhaseTimings::full_gc_roots);
 226   cm->mark_roots(ShenandoahPhaseTimings::full_gc_roots);
 227   cm->finish_mark_from_roots(/* full_gc = */ true);
 228 
 229   heap->mark_complete_marking_context();
 230 }
 231 
 232 class ShenandoahPrepareForCompactionObjectClosure : public ObjectClosure {
 233 private:
 234   ShenandoahHeap*          const _heap;
 235   GrowableArray<ShenandoahHeapRegion*>& _empty_regions;
 236   int _empty_regions_pos;
 237   ShenandoahHeapRegion*          _to_region;
 238   ShenandoahHeapRegion*          _from_region;
 239   HeapWord* _compact_point;
 240 
 241 public:
 242   ShenandoahPrepareForCompactionObjectClosure(GrowableArray<ShenandoahHeapRegion*>& empty_regions, ShenandoahHeapRegion* to_region) :
 243     _heap(ShenandoahHeap::heap()),
 244     _empty_regions(empty_regions),
 245     _empty_regions_pos(0),
 246     _to_region(to_region),
 247     _from_region(NULL),
 248     _compact_point(to_region->bottom()) {}
 249 
 250   void set_from_region(ShenandoahHeapRegion* from_region) {
 251     _from_region = from_region;
 252   }
 253 
 254   void finish_region() {
 255     assert(_to_region != NULL, "should not happen");
 256     _to_region->set_new_top(_compact_point);
 257   }
 258 
 259   bool is_compact_same_region() {
 260     return _from_region == _to_region;
 261   }
 262 
 263   int empty_regions_pos() {
 264     return _empty_regions_pos;
 265   }
 266 
 267   void do_object(oop p) {
 268     assert(_from_region != NULL, "must set before work");
 269     assert(_heap->complete_marking_context()->is_marked(p), "must be marked");
 270     assert(!_heap->complete_marking_context()->allocated_after_mark_start((HeapWord*) p), "must be truly marked");
 271 
 272     size_t obj_size = p->size() + ShenandoahBrooksPointer::word_size();
 273     if (_compact_point + obj_size > _to_region->end()) {
 274       finish_region();
 275 
 276       // Object doesn't fit. Pick next empty region and start compacting there.
 277       ShenandoahHeapRegion* new_to_region;
 278       if (_empty_regions_pos < _empty_regions.length()) {
 279         new_to_region = _empty_regions.at(_empty_regions_pos);
 280         _empty_regions_pos++;
 281       } else {
 282         // Out of empty region? Compact within the same region.
 283         new_to_region = _from_region;
 284       }
 285 
 286       assert(new_to_region != _to_region, "must not reuse same to-region");
 287       assert(new_to_region != NULL, "must not be NULL");
 288       _to_region = new_to_region;
 289       _compact_point = _to_region->bottom();
 290     }
 291 
 292     // Object fits into current region, record new location:
 293     assert(_compact_point + obj_size <= _to_region->end(), "must fit");
 294     shenandoah_assert_not_forwarded(NULL, p);
 295     ShenandoahBrooksPointer::set_raw(p, _compact_point + ShenandoahBrooksPointer::word_size());
 296     _compact_point += obj_size;
 297   }
 298 };
 299 
 300 class ShenandoahPrepareForCompactionTask : public AbstractGangTask {
 301 private:
 302   ShenandoahHeap*           const _heap;
 303   ShenandoahHeapRegionSet** const _worker_slices;
 304   ShenandoahRegionIterator        _heap_regions;
 305 
 306   ShenandoahHeapRegion* next_from_region(ShenandoahHeapRegionSet* slice) {
 307     ShenandoahHeapRegion* from_region = _heap_regions.next();
 308 
 309     while (from_region != NULL && (!from_region->is_move_allowed() || from_region->is_humongous())) {
 310       from_region = _heap_regions.next();
 311     }
 312 
 313     if (from_region != NULL) {
 314       assert(slice != NULL, "sanity");
 315       assert(!from_region->is_humongous(), "this path cannot handle humongous regions");
 316       assert(from_region->is_move_allowed(), "only regions that can be moved in mark-compact");
 317       slice->add_region(from_region);
 318     }
 319 
 320     return from_region;
 321   }
 322 
 323 public:
 324   ShenandoahPrepareForCompactionTask(ShenandoahHeapRegionSet** worker_slices) :
 325     AbstractGangTask("Shenandoah Prepare For Compaction Task"),
 326     _heap(ShenandoahHeap::heap()), _worker_slices(worker_slices) {
 327   }
 328 
 329   void work(uint worker_id) {
 330     ShenandoahHeapRegionSet* slice = _worker_slices[worker_id];
 331     ShenandoahHeapRegion* from_region = next_from_region(slice);
 332     // No work?
 333     if (from_region == NULL) {
 334       return;
 335     }
 336 
 337     // Sliding compaction. Walk all regions in the slice, and compact them.
 338     // Remember empty regions and reuse them as needed.
 339     ResourceMark rm;
 340     GrowableArray<ShenandoahHeapRegion*> empty_regions((int)_heap->num_regions());
 341     ShenandoahPrepareForCompactionObjectClosure cl(empty_regions, from_region);
 342     while (from_region != NULL) {
 343       cl.set_from_region(from_region);
 344       if (from_region->has_live()) {
 345         _heap->marked_object_iterate(from_region, &cl);
 346       }
 347 
 348       // Compacted the region to somewhere else? From-region is empty then.
 349       if (!cl.is_compact_same_region()) {
 350         empty_regions.append(from_region);
 351       }
 352       from_region = next_from_region(slice);
 353     }
 354     cl.finish_region();
 355 
 356     // Mark all remaining regions as empty
 357     for (int pos = cl.empty_regions_pos(); pos < empty_regions.length(); ++pos) {
 358       ShenandoahHeapRegion* r = empty_regions.at(pos);
 359       r->set_new_top(r->bottom());
 360     }
 361   }
 362 };
 363 
 364 void ShenandoahMarkCompact::calculate_target_humongous_objects() {
 365   ShenandoahHeap* heap = ShenandoahHeap::heap();
 366 
 367   // Compute the new addresses for humongous objects. We need to do this after addresses
 368   // for regular objects are calculated, and we know what regions in heap suffix are
 369   // available for humongous moves.
 370   //
 371   // Scan the heap backwards, because we are compacting humongous regions towards the end.
 372   // Maintain the contiguous compaction window in [to_begin; to_end), so that we can slide
 373   // humongous start there.
 374   //
 375   // The complication is potential non-movable regions during the scan. If such region is
 376   // detected, then sliding restarts towards that non-movable region.
 377 
 378   size_t to_begin = heap->num_regions();
 379   size_t to_end = heap->num_regions();
 380 
 381   for (size_t c = heap->num_regions() - 1; c > 0; c--) {
 382     ShenandoahHeapRegion *r = heap->get_region(c);
 383     if (r->is_humongous_continuation() || (r->new_top() == r->bottom())) {
 384       // To-region candidate: record this, and continue scan
 385       to_begin = r->region_number();
 386       continue;
 387     }
 388 
 389     if (r->is_humongous_start() && r->is_move_allowed()) {
 390       // From-region candidate: movable humongous region
 391       oop old_obj = oop(r->bottom() + ShenandoahBrooksPointer::word_size());
 392       size_t words_size = old_obj->size() + ShenandoahBrooksPointer::word_size();
 393       size_t num_regions = ShenandoahHeapRegion::required_regions(words_size * HeapWordSize);
 394 
 395       size_t start = to_end - num_regions;
 396 
 397       if (start >= to_begin && start != r->region_number()) {
 398         // Fits into current window, and the move is non-trivial. Record the move then, and continue scan.
 399         ShenandoahBrooksPointer::set_raw(old_obj, heap->get_region(start)->bottom() + ShenandoahBrooksPointer::word_size());
 400         to_end = start;
 401         continue;
 402       }
 403     }
 404 
 405     // Failed to fit. Scan starting from current region.
 406     to_begin = r->region_number();
 407     to_end = r->region_number();
 408   }
 409 }
 410 
 411 class ShenandoahEnsureHeapActiveClosure: public ShenandoahHeapRegionClosure {
 412 private:
 413   ShenandoahHeap* const _heap;
 414 
 415 public:
 416   ShenandoahEnsureHeapActiveClosure() : _heap(ShenandoahHeap::heap()) {}
 417   void heap_region_do(ShenandoahHeapRegion* r) {
 418     if (r->is_trash()) {
 419       r->recycle();
 420     }
 421     if (r->is_cset()) {
 422       r->make_regular_bypass();
 423     }
 424     if (r->is_empty_uncommitted()) {
 425       r->make_committed_bypass();
 426     }
 427     assert (r->is_committed(), "only committed regions in heap now, see region " SIZE_FORMAT, r->region_number());
 428 
 429     // Record current region occupancy: this communicates empty regions are free
 430     // to the rest of Full GC code.
 431     r->set_new_top(r->top());
 432   }
 433 };
 434 
 435 class ShenandoahTrashImmediateGarbageClosure: public ShenandoahHeapRegionClosure {
 436 private:
 437   ShenandoahHeap* const _heap;
 438   ShenandoahMarkingContext* const _ctx;
 439 
 440 public:
 441   ShenandoahTrashImmediateGarbageClosure() :
 442     _heap(ShenandoahHeap::heap()),
 443     _ctx(ShenandoahHeap::heap()->complete_marking_context()) {}
 444 
 445   void heap_region_do(ShenandoahHeapRegion* r) {
 446     if (r->is_humongous_start()) {
 447       oop humongous_obj = oop(r->bottom() + ShenandoahBrooksPointer::word_size());
 448       if (!_ctx->is_marked(humongous_obj)) {
 449         assert(!r->has_live(),
 450                "Region " SIZE_FORMAT " is not marked, should not have live", r->region_number());
 451         _heap->trash_humongous_region_at(r);
 452       } else {
 453         assert(r->has_live(),
 454                "Region " SIZE_FORMAT " should have live", r->region_number());
 455       }
 456     } else if (r->is_humongous_continuation()) {
 457       // If we hit continuation, the non-live humongous starts should have been trashed already
 458       assert(r->humongous_start_region()->has_live(),
 459              "Region " SIZE_FORMAT " should have live", r->region_number());
 460     } else if (r->is_regular()) {
 461       if (!r->has_live()) {
 462         r->make_trash_immediate();
 463       }
 464     }
 465   }
 466 };
 467 
 468 void ShenandoahMarkCompact::phase2_calculate_target_addresses(ShenandoahHeapRegionSet** worker_slices) {
 469   GCTraceTime(Info, gc, phases) time("Phase 2: Compute new object addresses", _gc_timer);
 470   ShenandoahGCPhase calculate_address_phase(ShenandoahPhaseTimings::full_gc_calculate_addresses);
 471 
 472   ShenandoahHeap* heap = ShenandoahHeap::heap();
 473 
 474   {
 475     // Trash the immediately collectible regions before computing addresses
 476     ShenandoahTrashImmediateGarbageClosure tigcl;
 477     heap->heap_region_iterate(&tigcl);
 478 
 479     // Make sure regions are in good state: committed, active, clean.
 480     // This is needed because we are potentially sliding the data through them.
 481     ShenandoahEnsureHeapActiveClosure ecl;
 482     heap->heap_region_iterate(&ecl);
 483   }
 484 
 485   // Compute the new addresses for regular objects
 486   {
 487     ShenandoahGCPhase phase(ShenandoahPhaseTimings::full_gc_calculate_addresses_regular);
 488     ShenandoahPrepareForCompactionTask prepare_task(worker_slices);
 489     heap->workers()->run_task(&prepare_task);
 490   }
 491 
 492   // Compute the new addresses for humongous objects
 493   {
 494     ShenandoahGCPhase phase(ShenandoahPhaseTimings::full_gc_calculate_addresses_humong);
 495     calculate_target_humongous_objects();
 496   }
 497 }
 498 
 499 class ShenandoahAdjustPointersClosure : public MetadataVisitingOopIterateClosure {
 500 private:
 501   ShenandoahHeap* const _heap;
 502   ShenandoahMarkingContext* const _ctx;
 503 
 504   template <class T>
 505   inline void do_oop_work(T* p) {
 506     T o = RawAccess<>::oop_load(p);
 507     if (!CompressedOops::is_null(o)) {
 508       oop obj = CompressedOops::decode_not_null(o);
 509       assert(_ctx->is_marked(obj), "must be marked");
 510       oop forw = oop(ShenandoahBrooksPointer::get_raw(obj));
 511       RawAccess<IS_NOT_NULL>::oop_store(p, forw);
 512     }
 513   }
 514 
 515 public:
 516   ShenandoahAdjustPointersClosure() :
 517     _heap(ShenandoahHeap::heap()),
 518     _ctx(ShenandoahHeap::heap()->complete_marking_context()) {}
 519 
 520   void do_oop(oop* p)       { do_oop_work(p); }
 521   void do_oop(narrowOop* p) { do_oop_work(p); }
 522 };
 523 
 524 class ShenandoahAdjustPointersObjectClosure : public ObjectClosure {
 525 private:
 526   ShenandoahHeap* const _heap;
 527   ShenandoahAdjustPointersClosure _cl;
 528 
 529 public:
 530   ShenandoahAdjustPointersObjectClosure() :
 531     _heap(ShenandoahHeap::heap()) {
 532   }
 533   void do_object(oop p) {
 534     assert(_heap->complete_marking_context()->is_marked(p), "must be marked");
 535     HeapWord* forw = ShenandoahBrooksPointer::get_raw(p);
 536     p->oop_iterate(&_cl);
 537   }
 538 };
 539 
 540 class ShenandoahAdjustPointersTask : public AbstractGangTask {
 541 private:
 542   ShenandoahHeap*          const _heap;
 543   ShenandoahRegionIterator       _regions;
 544 
 545 public:
 546   ShenandoahAdjustPointersTask() :
 547     AbstractGangTask("Shenandoah Adjust Pointers Task"),
 548     _heap(ShenandoahHeap::heap()) {
 549   }
 550 
 551   void work(uint worker_id) {
 552     ShenandoahAdjustPointersObjectClosure obj_cl;
 553     ShenandoahHeapRegion* r = _regions.next();
 554     while (r != NULL) {
 555       if (!r->is_humongous_continuation() && r->has_live()) {
 556         _heap->marked_object_iterate(r, &obj_cl);
 557       }
 558       r = _regions.next();
 559     }
 560   }
 561 };
 562 
 563 class ShenandoahAdjustRootPointersTask : public AbstractGangTask {
 564 private:
 565   ShenandoahRootProcessor* _rp;
 566 
 567 public:
 568   ShenandoahAdjustRootPointersTask(ShenandoahRootProcessor* rp) :
 569     AbstractGangTask("Shenandoah Adjust Root Pointers Task"),
 570     _rp(rp) {}
 571 
 572   void work(uint worker_id) {
 573     ShenandoahAdjustPointersClosure cl;
 574     CLDToOopClosure adjust_cld_closure(&cl, ClassLoaderData::_claim_strong);
 575     MarkingCodeBlobClosure adjust_code_closure(&cl,
 576                                              CodeBlobToOopClosure::FixRelocations);
 577 
 578     _rp->process_all_roots(&cl, &cl,
 579                            &adjust_cld_closure,
 580                            &adjust_code_closure, NULL, worker_id);
 581   }
 582 };
 583 
 584 void ShenandoahMarkCompact::phase3_update_references() {
 585   GCTraceTime(Info, gc, phases) time("Phase 3: Adjust pointers", _gc_timer);
 586   ShenandoahGCPhase adjust_pointer_phase(ShenandoahPhaseTimings::full_gc_adjust_pointers);
 587 
 588   ShenandoahHeap* heap = ShenandoahHeap::heap();
 589 
 590   WorkGang* workers = heap->workers();
 591   uint nworkers = workers->active_workers();
 592   {
 593 #if COMPILER2_OR_JVMCI
 594     DerivedPointerTable::clear();
 595 #endif
 596     ShenandoahRootProcessor rp(heap, nworkers, ShenandoahPhaseTimings::full_gc_roots);
 597     ShenandoahAdjustRootPointersTask task(&rp);
 598     workers->run_task(&task);
 599 #if COMPILER2_OR_JVMCI
 600     DerivedPointerTable::update_pointers();
 601 #endif
 602   }
 603 
 604   ShenandoahAdjustPointersTask adjust_pointers_task;
 605   workers->run_task(&adjust_pointers_task);
 606 }
 607 
 608 class ShenandoahCompactObjectsClosure : public ObjectClosure {
 609 private:
 610   ShenandoahHeap* const _heap;
 611   uint            const _worker_id;
 612 
 613 public:
 614   ShenandoahCompactObjectsClosure(uint worker_id) :
 615     _heap(ShenandoahHeap::heap()), _worker_id(worker_id) {}
 616 
 617   void do_object(oop p) {
 618     assert(_heap->complete_marking_context()->is_marked(p), "must be marked");
 619     size_t size = (size_t)p->size();
 620     HeapWord* compact_to = ShenandoahBrooksPointer::get_raw(p);
 621     HeapWord* compact_from = (HeapWord*) p;
 622     if (compact_from != compact_to) {
 623       Copy::aligned_conjoint_words(compact_from, compact_to, size);
 624     }
 625     oop new_obj = oop(compact_to);
 626     ShenandoahBrooksPointer::initialize(new_obj);
 627   }
 628 };
 629 
 630 class ShenandoahCompactObjectsTask : public AbstractGangTask {
 631 private:
 632   ShenandoahHeap* const _heap;
 633   ShenandoahHeapRegionSet** const _worker_slices;
 634 
 635 public:
 636   ShenandoahCompactObjectsTask(ShenandoahHeapRegionSet** worker_slices) :
 637     AbstractGangTask("Shenandoah Compact Objects Task"),
 638     _heap(ShenandoahHeap::heap()),
 639     _worker_slices(worker_slices) {
 640   }
 641 
 642   void work(uint worker_id) {
 643     ShenandoahHeapRegionSetIterator slice(_worker_slices[worker_id]);
 644 
 645     ShenandoahCompactObjectsClosure cl(worker_id);
 646     ShenandoahHeapRegion* r = slice.next();
 647     while (r != NULL) {
 648       assert(!r->is_humongous(), "must not get humongous regions here");
 649       if (r->has_live()) {
 650         _heap->marked_object_iterate(r, &cl);
 651       }
 652       r->set_top(r->new_top());
 653       r = slice.next();
 654     }
 655   }
 656 };
 657 
 658 class ShenandoahPostCompactClosure : public ShenandoahHeapRegionClosure {
 659 private:
 660   ShenandoahHeap* const _heap;
 661   size_t _live;
 662 
 663 public:
 664   ShenandoahPostCompactClosure() : _heap(ShenandoahHeap::heap()), _live(0) {
 665     _heap->free_set()->clear();
 666   }
 667 
 668   void heap_region_do(ShenandoahHeapRegion* r) {
 669     assert (!r->is_cset(), "cset regions should have been demoted already");
 670 
 671     // Need to reset the complete-top-at-mark-start pointer here because
 672     // the complete marking bitmap is no longer valid. This ensures
 673     // size-based iteration in marked_object_iterate().
 674     // NOTE: See blurb at ShenandoahMCResetCompleteBitmapTask on why we need to skip
 675     // pinned regions.
 676     if (!r->is_pinned()) {
 677       _heap->complete_marking_context()->reset_top_at_mark_start(r);
 678     }
 679 
 680     size_t live = r->used();
 681 
 682     // Make empty regions that have been allocated into regular
 683     if (r->is_empty() && live > 0) {
 684       r->make_regular_bypass();
 685     }
 686 
 687     // Reclaim regular regions that became empty
 688     if (r->is_regular() && live == 0) {
 689       r->make_trash();
 690     }
 691 
 692     // Recycle all trash regions
 693     if (r->is_trash()) {
 694       live = 0;
 695       r->recycle();
 696     }
 697 
 698     r->set_live_data(live);
 699     r->reset_alloc_metadata_to_shared();
 700     _live += live;
 701   }
 702 
 703   size_t get_live() {
 704     return _live;
 705   }
 706 };
 707 
 708 void ShenandoahMarkCompact::compact_humongous_objects() {
 709   // Compact humongous regions, based on their fwdptr objects.
 710   //
 711   // This code is serial, because doing the in-slice parallel sliding is tricky. In most cases,
 712   // humongous regions are already compacted, and do not require further moves, which alleviates
 713   // sliding costs. We may consider doing this in parallel in future.
 714 
 715   ShenandoahHeap* heap = ShenandoahHeap::heap();
 716 
 717   for (size_t c = heap->num_regions() - 1; c > 0; c--) {
 718     ShenandoahHeapRegion* r = heap->get_region(c);
 719     if (r->is_humongous_start()) {
 720       oop old_obj = oop(r->bottom() + ShenandoahBrooksPointer::word_size());
 721       size_t words_size = old_obj->size() + ShenandoahBrooksPointer::word_size();
 722       size_t num_regions = ShenandoahHeapRegion::required_regions(words_size * HeapWordSize);
 723 
 724       size_t old_start = r->region_number();
 725       size_t old_end   = old_start + num_regions - 1;
 726       size_t new_start = heap->heap_region_index_containing(ShenandoahBrooksPointer::get_raw(old_obj));
 727       size_t new_end   = new_start + num_regions - 1;
 728 
 729       if (old_start == new_start) {
 730         // No need to move the object, it stays at the same slot
 731         continue;
 732       }
 733 
 734       assert (r->is_move_allowed(), "should be movable");
 735 
 736       Copy::aligned_conjoint_words(heap->get_region(old_start)->bottom(),
 737                                    heap->get_region(new_start)->bottom(),
 738                                    ShenandoahHeapRegion::region_size_words()*num_regions);
 739 
 740       oop new_obj = oop(heap->get_region(new_start)->bottom() + ShenandoahBrooksPointer::word_size());
 741       ShenandoahBrooksPointer::initialize(new_obj);
 742 
 743       {
 744         for (size_t c = old_start; c <= old_end; c++) {
 745           ShenandoahHeapRegion* r = heap->get_region(c);
 746           r->make_regular_bypass();
 747           r->set_top(r->bottom());
 748         }
 749 
 750         for (size_t c = new_start; c <= new_end; c++) {
 751           ShenandoahHeapRegion* r = heap->get_region(c);
 752           if (c == new_start) {
 753             r->make_humongous_start_bypass();
 754           } else {
 755             r->make_humongous_cont_bypass();
 756           }
 757 
 758           // Trailing region may be non-full, record the remainder there
 759           size_t remainder = words_size & ShenandoahHeapRegion::region_size_words_mask();
 760           if ((c == new_end) && (remainder != 0)) {
 761             r->set_top(r->bottom() + remainder);
 762           } else {
 763             r->set_top(r->end());
 764           }
 765 
 766           r->reset_alloc_metadata_to_shared();
 767         }
 768       }
 769     }
 770   }
 771 }
 772 
 773 // This is slightly different to ShHeap::reset_next_mark_bitmap:
 774 // we need to remain able to walk pinned regions.
 775 // Since pinned region do not move and don't get compacted, we will get holes with
 776 // unreachable objects in them (which may have pointers to unloaded Klasses and thus
 777 // cannot be iterated over using oop->size(). The only way to safely iterate over those is using
 778 // a valid marking bitmap and valid TAMS pointer. This class only resets marking
 779 // bitmaps for un-pinned regions, and later we only reset TAMS for unpinned regions.
 780 class ShenandoahMCResetCompleteBitmapTask : public AbstractGangTask {
 781 private:
 782   ShenandoahRegionIterator _regions;
 783 
 784 public:
 785   ShenandoahMCResetCompleteBitmapTask() :
 786     AbstractGangTask("Parallel Reset Bitmap Task") {
 787   }
 788 
 789   void work(uint worker_id) {
 790     ShenandoahHeapRegion* region = _regions.next();
 791     ShenandoahHeap* heap = ShenandoahHeap::heap();
 792     ShenandoahMarkingContext* const ctx = heap->complete_marking_context();
 793     while (region != NULL) {
 794       if (heap->is_bitmap_slice_committed(region) && !region->is_pinned() && region->has_live()) {
 795         ctx->clear_bitmap(region);
 796       }
 797       region = _regions.next();
 798     }
 799   }
 800 };
 801 
 802 void ShenandoahMarkCompact::phase4_compact_objects(ShenandoahHeapRegionSet** worker_slices) {
 803   GCTraceTime(Info, gc, phases) time("Phase 4: Move objects", _gc_timer);
 804   ShenandoahGCPhase compaction_phase(ShenandoahPhaseTimings::full_gc_copy_objects);
 805 
 806   ShenandoahHeap* heap = ShenandoahHeap::heap();
 807 
 808   // Compact regular objects first
 809   {
 810     ShenandoahGCPhase phase(ShenandoahPhaseTimings::full_gc_copy_objects_regular);
 811     ShenandoahCompactObjectsTask compact_task(worker_slices);
 812     heap->workers()->run_task(&compact_task);
 813   }
 814 
 815   // Compact humongous objects after regular object moves
 816   {
 817     ShenandoahGCPhase phase(ShenandoahPhaseTimings::full_gc_copy_objects_humong);
 818     compact_humongous_objects();
 819   }
 820 
 821   // Reset complete bitmap. We're about to reset the complete-top-at-mark-start pointer
 822   // and must ensure the bitmap is in sync.
 823   {
 824     ShenandoahGCPhase phase(ShenandoahPhaseTimings::full_gc_copy_objects_reset_complete);
 825     ShenandoahMCResetCompleteBitmapTask task;
 826     heap->workers()->run_task(&task);
 827   }
 828 
 829   // Bring regions in proper states after the collection, and set heap properties.
 830   {
 831     ShenandoahGCPhase phase(ShenandoahPhaseTimings::full_gc_copy_objects_rebuild);
 832 
 833     ShenandoahPostCompactClosure post_compact;
 834     heap->heap_region_iterate(&post_compact);
 835     heap->set_used(post_compact.get_live());
 836 
 837     heap->collection_set()->clear();
 838     heap->free_set()->rebuild();
 839   }
 840 
 841   heap->clear_cancelled_gc();
 842 }