1 /*
   2  * Copyright (c) 2005, 2024, Oracle and/or its affiliates. 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 #include "classfile/classLoaderDataGraph.hpp"
  27 #include "classfile/javaClasses.inline.hpp"
  28 #include "classfile/stringTable.hpp"
  29 #include "classfile/symbolTable.hpp"
  30 #include "classfile/systemDictionary.hpp"
  31 #include "code/codeCache.hpp"
  32 #include "compiler/oopMap.hpp"
  33 #include "gc/parallel/parallelArguments.hpp"
  34 #include "gc/parallel/parallelScavengeHeap.inline.hpp"
  35 #include "gc/parallel/parMarkBitMap.inline.hpp"
  36 #include "gc/parallel/psAdaptiveSizePolicy.hpp"
  37 #include "gc/parallel/psCompactionManager.inline.hpp"
  38 #include "gc/parallel/psOldGen.hpp"
  39 #include "gc/parallel/psParallelCompact.inline.hpp"
  40 #include "gc/parallel/psPromotionManager.inline.hpp"
  41 #include "gc/parallel/psRootType.hpp"
  42 #include "gc/parallel/psScavenge.hpp"
  43 #include "gc/parallel/psStringDedup.hpp"
  44 #include "gc/parallel/psYoungGen.hpp"
  45 #include "gc/shared/classUnloadingContext.hpp"
  46 #include "gc/shared/gcCause.hpp"
  47 #include "gc/shared/gcHeapSummary.hpp"
  48 #include "gc/shared/gcId.hpp"
  49 #include "gc/shared/gcLocker.hpp"
  50 #include "gc/shared/gcTimer.hpp"
  51 #include "gc/shared/gcTrace.hpp"
  52 #include "gc/shared/gcTraceTime.inline.hpp"
  53 #include "gc/shared/isGCActiveMark.hpp"
  54 #include "gc/shared/oopStorage.inline.hpp"
  55 #include "gc/shared/oopStorageSet.inline.hpp"
  56 #include "gc/shared/oopStorageSetParState.inline.hpp"
  57 #include "gc/shared/referencePolicy.hpp"
  58 #include "gc/shared/referenceProcessor.hpp"
  59 #include "gc/shared/referenceProcessorPhaseTimes.hpp"
  60 #include "gc/shared/spaceDecorator.inline.hpp"
  61 #include "gc/shared/taskTerminator.hpp"
  62 #include "gc/shared/weakProcessor.inline.hpp"
  63 #include "gc/shared/workerPolicy.hpp"
  64 #include "gc/shared/workerThread.hpp"
  65 #include "gc/shared/workerUtils.hpp"
  66 #include "logging/log.hpp"
  67 #include "memory/iterator.inline.hpp"
  68 #include "memory/metaspaceUtils.hpp"
  69 #include "memory/resourceArea.hpp"
  70 #include "memory/universe.hpp"
  71 #include "nmt/memTracker.hpp"
  72 #include "oops/access.inline.hpp"
  73 #include "oops/flatArrayKlass.inline.hpp"
  74 #include "oops/instanceClassLoaderKlass.inline.hpp"
  75 #include "oops/instanceKlass.inline.hpp"
  76 #include "oops/instanceMirrorKlass.inline.hpp"
  77 #include "oops/methodData.hpp"
  78 #include "oops/objArrayKlass.inline.hpp"
  79 #include "oops/oop.inline.hpp"
  80 #include "runtime/atomic.hpp"
  81 #include "runtime/handles.inline.hpp"
  82 #include "runtime/java.hpp"
  83 #include "runtime/safepoint.hpp"
  84 #include "runtime/threads.hpp"
  85 #include "runtime/vmThread.hpp"
  86 #include "services/memoryService.hpp"
  87 #include "utilities/align.hpp"
  88 #include "utilities/debug.hpp"
  89 #include "utilities/events.hpp"
  90 #include "utilities/formatBuffer.hpp"
  91 #include "utilities/macros.hpp"
  92 #include "utilities/stack.inline.hpp"
  93 #if INCLUDE_JVMCI
  94 #include "jvmci/jvmci.hpp"
  95 #endif
  96 
  97 #include <math.h>
  98 
  99 // All sizes are in HeapWords.
 100 const size_t ParallelCompactData::Log2RegionSize  = 16; // 64K words
 101 const size_t ParallelCompactData::RegionSize      = (size_t)1 << Log2RegionSize;
 102 const size_t ParallelCompactData::RegionSizeBytes =
 103   RegionSize << LogHeapWordSize;
 104 const size_t ParallelCompactData::RegionSizeOffsetMask = RegionSize - 1;
 105 const size_t ParallelCompactData::RegionAddrOffsetMask = RegionSizeBytes - 1;
 106 const size_t ParallelCompactData::RegionAddrMask       = ~RegionAddrOffsetMask;
 107 
 108 const size_t ParallelCompactData::Log2BlockSize   = 7; // 128 words
 109 const size_t ParallelCompactData::BlockSize       = (size_t)1 << Log2BlockSize;
 110 const size_t ParallelCompactData::BlockSizeBytes  =
 111   BlockSize << LogHeapWordSize;
 112 const size_t ParallelCompactData::BlockSizeOffsetMask = BlockSize - 1;
 113 const size_t ParallelCompactData::BlockAddrOffsetMask = BlockSizeBytes - 1;
 114 const size_t ParallelCompactData::BlockAddrMask       = ~BlockAddrOffsetMask;
 115 
 116 const size_t ParallelCompactData::BlocksPerRegion = RegionSize / BlockSize;
 117 const size_t ParallelCompactData::Log2BlocksPerRegion =
 118   Log2RegionSize - Log2BlockSize;
 119 
 120 const ParallelCompactData::RegionData::region_sz_t
 121 ParallelCompactData::RegionData::dc_shift = 27;
 122 
 123 const ParallelCompactData::RegionData::region_sz_t
 124 ParallelCompactData::RegionData::dc_mask = ~0U << dc_shift;
 125 
 126 const ParallelCompactData::RegionData::region_sz_t
 127 ParallelCompactData::RegionData::dc_one = 0x1U << dc_shift;
 128 
 129 const ParallelCompactData::RegionData::region_sz_t
 130 ParallelCompactData::RegionData::los_mask = ~dc_mask;
 131 
 132 const ParallelCompactData::RegionData::region_sz_t
 133 ParallelCompactData::RegionData::dc_claimed = 0x8U << dc_shift;
 134 
 135 const ParallelCompactData::RegionData::region_sz_t
 136 ParallelCompactData::RegionData::dc_completed = 0xcU << dc_shift;
 137 
 138 SpaceInfo PSParallelCompact::_space_info[PSParallelCompact::last_space_id];
 139 
 140 SpanSubjectToDiscoveryClosure PSParallelCompact::_span_based_discoverer;
 141 ReferenceProcessor* PSParallelCompact::_ref_processor = nullptr;
 142 
 143 double PSParallelCompact::_dwl_mean;
 144 double PSParallelCompact::_dwl_std_dev;
 145 double PSParallelCompact::_dwl_first_term;
 146 double PSParallelCompact::_dwl_adjustment;
 147 #ifdef  ASSERT
 148 bool   PSParallelCompact::_dwl_initialized = false;
 149 #endif  // #ifdef ASSERT
 150 
 151 void SplitInfo::record(size_t src_region_idx, size_t partial_obj_size,
 152                        HeapWord* destination)
 153 {
 154   assert(src_region_idx != 0, "invalid src_region_idx");
 155   assert(partial_obj_size != 0, "invalid partial_obj_size argument");
 156   assert(destination != nullptr, "invalid destination argument");
 157 
 158   _src_region_idx = src_region_idx;
 159   _partial_obj_size = partial_obj_size;
 160   _destination = destination;
 161 
 162   // These fields may not be updated below, so make sure they're clear.
 163   assert(_dest_region_addr == nullptr, "should have been cleared");
 164   assert(_first_src_addr == nullptr, "should have been cleared");
 165 
 166   // Determine the number of destination regions for the partial object.
 167   HeapWord* const last_word = destination + partial_obj_size - 1;
 168   const ParallelCompactData& sd = PSParallelCompact::summary_data();
 169   HeapWord* const beg_region_addr = sd.region_align_down(destination);
 170   HeapWord* const end_region_addr = sd.region_align_down(last_word);
 171 
 172   if (beg_region_addr == end_region_addr) {
 173     // One destination region.
 174     _destination_count = 1;
 175     if (end_region_addr == destination) {
 176       // The destination falls on a region boundary, thus the first word of the
 177       // partial object will be the first word copied to the destination region.
 178       _dest_region_addr = end_region_addr;
 179       _first_src_addr = sd.region_to_addr(src_region_idx);
 180     }
 181   } else {
 182     // Two destination regions.  When copied, the partial object will cross a
 183     // destination region boundary, so a word somewhere within the partial
 184     // object will be the first word copied to the second destination region.
 185     _destination_count = 2;
 186     _dest_region_addr = end_region_addr;
 187     const size_t ofs = pointer_delta(end_region_addr, destination);
 188     assert(ofs < _partial_obj_size, "sanity");
 189     _first_src_addr = sd.region_to_addr(src_region_idx) + ofs;
 190   }
 191 }
 192 
 193 void SplitInfo::clear()
 194 {
 195   _src_region_idx = 0;
 196   _partial_obj_size = 0;
 197   _destination = nullptr;
 198   _destination_count = 0;
 199   _dest_region_addr = nullptr;
 200   _first_src_addr = nullptr;
 201   assert(!is_valid(), "sanity");
 202 }
 203 
 204 #ifdef  ASSERT
 205 void SplitInfo::verify_clear()
 206 {
 207   assert(_src_region_idx == 0, "not clear");
 208   assert(_partial_obj_size == 0, "not clear");
 209   assert(_destination == nullptr, "not clear");
 210   assert(_destination_count == 0, "not clear");
 211   assert(_dest_region_addr == nullptr, "not clear");
 212   assert(_first_src_addr == nullptr, "not clear");
 213 }
 214 #endif  // #ifdef ASSERT
 215 
 216 
 217 void PSParallelCompact::print_on_error(outputStream* st) {
 218   _mark_bitmap.print_on_error(st);
 219 }
 220 
 221 #ifndef PRODUCT
 222 const char* PSParallelCompact::space_names[] = {
 223   "old ", "eden", "from", "to  "
 224 };
 225 
 226 void PSParallelCompact::print_region_ranges() {
 227   if (!log_develop_is_enabled(Trace, gc, compaction)) {
 228     return;
 229   }
 230   Log(gc, compaction) log;
 231   ResourceMark rm;
 232   LogStream ls(log.trace());
 233   Universe::print_on(&ls);
 234   log.trace("space  bottom     top        end        new_top");
 235   log.trace("------ ---------- ---------- ---------- ----------");
 236 
 237   for (unsigned int id = 0; id < last_space_id; ++id) {
 238     const MutableSpace* space = _space_info[id].space();
 239     log.trace("%u %s "
 240               SIZE_FORMAT_W(10) " " SIZE_FORMAT_W(10) " "
 241               SIZE_FORMAT_W(10) " " SIZE_FORMAT_W(10) " ",
 242               id, space_names[id],
 243               summary_data().addr_to_region_idx(space->bottom()),
 244               summary_data().addr_to_region_idx(space->top()),
 245               summary_data().addr_to_region_idx(space->end()),
 246               summary_data().addr_to_region_idx(_space_info[id].new_top()));
 247   }
 248 }
 249 
 250 static void
 251 print_generic_summary_region(size_t i, const ParallelCompactData::RegionData* c)
 252 {
 253 #define REGION_IDX_FORMAT        SIZE_FORMAT_W(7)
 254 #define REGION_DATA_FORMAT       SIZE_FORMAT_W(5)
 255 
 256   ParallelCompactData& sd = PSParallelCompact::summary_data();
 257   size_t dci = c->destination() ? sd.addr_to_region_idx(c->destination()) : 0;
 258   log_develop_trace(gc, compaction)(
 259       REGION_IDX_FORMAT " " PTR_FORMAT " "
 260       REGION_IDX_FORMAT " " PTR_FORMAT " "
 261       REGION_DATA_FORMAT " " REGION_DATA_FORMAT " "
 262       REGION_DATA_FORMAT " " REGION_IDX_FORMAT " %d",
 263       i, p2i(c->data_location()), dci, p2i(c->destination()),
 264       c->partial_obj_size(), c->live_obj_size(),
 265       c->data_size(), c->source_region(), c->destination_count());
 266 
 267 #undef  REGION_IDX_FORMAT
 268 #undef  REGION_DATA_FORMAT
 269 }
 270 
 271 void
 272 print_generic_summary_data(ParallelCompactData& summary_data,
 273                            HeapWord* const beg_addr,
 274                            HeapWord* const end_addr)
 275 {
 276   size_t total_words = 0;
 277   size_t i = summary_data.addr_to_region_idx(beg_addr);
 278   const size_t last = summary_data.addr_to_region_idx(end_addr);
 279   HeapWord* pdest = 0;
 280 
 281   while (i < last) {
 282     ParallelCompactData::RegionData* c = summary_data.region(i);
 283     if (c->data_size() != 0 || c->destination() != pdest) {
 284       print_generic_summary_region(i, c);
 285       total_words += c->data_size();
 286       pdest = c->destination();
 287     }
 288     ++i;
 289   }
 290 
 291   log_develop_trace(gc, compaction)("summary_data_bytes=" SIZE_FORMAT, total_words * HeapWordSize);
 292 }
 293 
 294 void
 295 PSParallelCompact::print_generic_summary_data(ParallelCompactData& summary_data,
 296                                               HeapWord* const beg_addr,
 297                                               HeapWord* const end_addr) {
 298   ::print_generic_summary_data(summary_data,beg_addr, end_addr);
 299 }
 300 
 301 void
 302 print_generic_summary_data(ParallelCompactData& summary_data,
 303                            SpaceInfo* space_info)
 304 {
 305   if (!log_develop_is_enabled(Trace, gc, compaction)) {
 306     return;
 307   }
 308 
 309   for (unsigned int id = 0; id < PSParallelCompact::last_space_id; ++id) {
 310     const MutableSpace* space = space_info[id].space();
 311     print_generic_summary_data(summary_data, space->bottom(),
 312                                MAX2(space->top(), space_info[id].new_top()));
 313   }
 314 }
 315 
 316 static void
 317 print_initial_summary_data(ParallelCompactData& summary_data,
 318                            const MutableSpace* space) {
 319   if (space->top() == space->bottom()) {
 320     return;
 321   }
 322 
 323   const size_t region_size = ParallelCompactData::RegionSize;
 324   typedef ParallelCompactData::RegionData RegionData;
 325   HeapWord* const top_aligned_up = summary_data.region_align_up(space->top());
 326   const size_t end_region = summary_data.addr_to_region_idx(top_aligned_up);
 327   const RegionData* c = summary_data.region(end_region - 1);
 328   HeapWord* end_addr = c->destination() + c->data_size();
 329   const size_t live_in_space = pointer_delta(end_addr, space->bottom());
 330 
 331   // Print (and count) the full regions at the beginning of the space.
 332   size_t full_region_count = 0;
 333   size_t i = summary_data.addr_to_region_idx(space->bottom());
 334   while (i < end_region && summary_data.region(i)->data_size() == region_size) {
 335     ParallelCompactData::RegionData* c = summary_data.region(i);
 336     log_develop_trace(gc, compaction)(
 337         SIZE_FORMAT_W(5) " " PTR_FORMAT " " SIZE_FORMAT_W(5) " " SIZE_FORMAT_W(5) " " SIZE_FORMAT_W(5) " " SIZE_FORMAT_W(5) " %d",
 338         i, p2i(c->destination()),
 339         c->partial_obj_size(), c->live_obj_size(),
 340         c->data_size(), c->source_region(), c->destination_count());
 341     ++full_region_count;
 342     ++i;
 343   }
 344 
 345   size_t live_to_right = live_in_space - full_region_count * region_size;
 346 
 347   double max_reclaimed_ratio = 0.0;
 348   size_t max_reclaimed_ratio_region = 0;
 349   size_t max_dead_to_right = 0;
 350   size_t max_live_to_right = 0;
 351 
 352   // Print the 'reclaimed ratio' for regions while there is something live in
 353   // the region or to the right of it.  The remaining regions are empty (and
 354   // uninteresting), and computing the ratio will result in division by 0.
 355   while (i < end_region && live_to_right > 0) {
 356     c = summary_data.region(i);
 357     HeapWord* const region_addr = summary_data.region_to_addr(i);
 358     const size_t used_to_right = pointer_delta(space->top(), region_addr);
 359     const size_t dead_to_right = used_to_right - live_to_right;
 360     const double reclaimed_ratio = double(dead_to_right) / live_to_right;
 361 
 362     if (reclaimed_ratio > max_reclaimed_ratio) {
 363             max_reclaimed_ratio = reclaimed_ratio;
 364             max_reclaimed_ratio_region = i;
 365             max_dead_to_right = dead_to_right;
 366             max_live_to_right = live_to_right;
 367     }
 368 
 369     ParallelCompactData::RegionData* c = summary_data.region(i);
 370     log_develop_trace(gc, compaction)(
 371         SIZE_FORMAT_W(5) " " PTR_FORMAT " " SIZE_FORMAT_W(5) " " SIZE_FORMAT_W(5) " " SIZE_FORMAT_W(5) " " SIZE_FORMAT_W(5) " %d"
 372         "%12.10f " SIZE_FORMAT_W(10) " " SIZE_FORMAT_W(10),
 373         i, p2i(c->destination()),
 374         c->partial_obj_size(), c->live_obj_size(),
 375         c->data_size(), c->source_region(), c->destination_count(),
 376         reclaimed_ratio, dead_to_right, live_to_right);
 377 
 378 
 379     live_to_right -= c->data_size();
 380     ++i;
 381   }
 382 
 383   // Any remaining regions are empty.  Print one more if there is one.
 384   if (i < end_region) {
 385     ParallelCompactData::RegionData* c = summary_data.region(i);
 386     log_develop_trace(gc, compaction)(
 387         SIZE_FORMAT_W(5) " " PTR_FORMAT " " SIZE_FORMAT_W(5) " " SIZE_FORMAT_W(5) " " SIZE_FORMAT_W(5) " " SIZE_FORMAT_W(5) " %d",
 388          i, p2i(c->destination()),
 389          c->partial_obj_size(), c->live_obj_size(),
 390          c->data_size(), c->source_region(), c->destination_count());
 391   }
 392 
 393   log_develop_trace(gc, compaction)("max:  " SIZE_FORMAT_W(4) " d2r=" SIZE_FORMAT_W(10) " l2r=" SIZE_FORMAT_W(10) " max_ratio=%14.12f",
 394                                     max_reclaimed_ratio_region, max_dead_to_right, max_live_to_right, max_reclaimed_ratio);
 395 }
 396 
 397 static void
 398 print_initial_summary_data(ParallelCompactData& summary_data,
 399                            SpaceInfo* space_info) {
 400   if (!log_develop_is_enabled(Trace, gc, compaction)) {
 401     return;
 402   }
 403 
 404   unsigned int id = PSParallelCompact::old_space_id;
 405   const MutableSpace* space;
 406   do {
 407     space = space_info[id].space();
 408     print_initial_summary_data(summary_data, space);
 409   } while (++id < PSParallelCompact::eden_space_id);
 410 
 411   do {
 412     space = space_info[id].space();
 413     print_generic_summary_data(summary_data, space->bottom(), space->top());
 414   } while (++id < PSParallelCompact::last_space_id);
 415 }
 416 #endif  // #ifndef PRODUCT
 417 
 418 ParallelCompactData::ParallelCompactData() :
 419   _heap_start(nullptr),
 420   DEBUG_ONLY(_heap_end(nullptr) COMMA)
 421   _region_vspace(nullptr),
 422   _reserved_byte_size(0),
 423   _region_data(nullptr),
 424   _region_count(0),
 425   _block_vspace(nullptr),
 426   _block_data(nullptr),
 427   _block_count(0) {}
 428 
 429 bool ParallelCompactData::initialize(MemRegion reserved_heap)
 430 {
 431   _heap_start = reserved_heap.start();
 432   const size_t heap_size = reserved_heap.word_size();
 433   DEBUG_ONLY(_heap_end = _heap_start + heap_size;)
 434 
 435   assert(region_align_down(_heap_start) == _heap_start,
 436          "region start not aligned");
 437 
 438   bool result = initialize_region_data(heap_size) && initialize_block_data();
 439   return result;
 440 }
 441 
 442 PSVirtualSpace*
 443 ParallelCompactData::create_vspace(size_t count, size_t element_size)
 444 {
 445   const size_t raw_bytes = count * element_size;
 446   const size_t page_sz = os::page_size_for_region_aligned(raw_bytes, 10);
 447   const size_t granularity = os::vm_allocation_granularity();
 448   _reserved_byte_size = align_up(raw_bytes, MAX2(page_sz, granularity));
 449 
 450   const size_t rs_align = page_sz == os::vm_page_size() ? 0 :
 451     MAX2(page_sz, granularity);
 452   ReservedSpace rs(_reserved_byte_size, rs_align, page_sz);
 453   os::trace_page_sizes("Parallel Compact Data", raw_bytes, raw_bytes, rs.base(),
 454                        rs.size(), page_sz);
 455 
 456   MemTracker::record_virtual_memory_type((address)rs.base(), mtGC);
 457 
 458   PSVirtualSpace* vspace = new PSVirtualSpace(rs, page_sz);
 459   if (vspace != 0) {
 460     if (vspace->expand_by(_reserved_byte_size)) {
 461       return vspace;
 462     }
 463     delete vspace;
 464     // Release memory reserved in the space.
 465     rs.release();
 466   }
 467 
 468   return 0;
 469 }
 470 
 471 bool ParallelCompactData::initialize_region_data(size_t heap_size)
 472 {
 473   assert(is_aligned(heap_size, RegionSize), "precondition");
 474 
 475   const size_t count = heap_size >> Log2RegionSize;
 476   _region_vspace = create_vspace(count, sizeof(RegionData));
 477   if (_region_vspace != 0) {
 478     _region_data = (RegionData*)_region_vspace->reserved_low_addr();
 479     _region_count = count;
 480     return true;
 481   }
 482   return false;
 483 }
 484 
 485 bool ParallelCompactData::initialize_block_data()
 486 {
 487   assert(_region_count != 0, "region data must be initialized first");
 488   const size_t count = _region_count << Log2BlocksPerRegion;
 489   _block_vspace = create_vspace(count, sizeof(BlockData));
 490   if (_block_vspace != 0) {
 491     _block_data = (BlockData*)_block_vspace->reserved_low_addr();
 492     _block_count = count;
 493     return true;
 494   }
 495   return false;
 496 }
 497 
 498 void ParallelCompactData::clear()
 499 {
 500   memset(_region_data, 0, _region_vspace->committed_size());
 501   memset(_block_data, 0, _block_vspace->committed_size());
 502 }
 503 
 504 void ParallelCompactData::clear_range(size_t beg_region, size_t end_region) {
 505   assert(beg_region <= _region_count, "beg_region out of range");
 506   assert(end_region <= _region_count, "end_region out of range");
 507   assert(RegionSize % BlockSize == 0, "RegionSize not a multiple of BlockSize");
 508 
 509   const size_t region_cnt = end_region - beg_region;
 510   memset(_region_data + beg_region, 0, region_cnt * sizeof(RegionData));
 511 
 512   const size_t beg_block = beg_region * BlocksPerRegion;
 513   const size_t block_cnt = region_cnt * BlocksPerRegion;
 514   memset(_block_data + beg_block, 0, block_cnt * sizeof(BlockData));
 515 }
 516 
 517 HeapWord* ParallelCompactData::partial_obj_end(size_t region_idx) const
 518 {
 519   const RegionData* cur_cp = region(region_idx);
 520   const RegionData* const end_cp = region(region_count() - 1);
 521 
 522   HeapWord* result = region_to_addr(region_idx);
 523   if (cur_cp < end_cp) {
 524     do {
 525       result += cur_cp->partial_obj_size();
 526     } while (cur_cp->partial_obj_size() == RegionSize && ++cur_cp < end_cp);
 527   }
 528   return result;
 529 }
 530 
 531 void ParallelCompactData::add_obj(HeapWord* addr, size_t len)
 532 {
 533   const size_t obj_ofs = pointer_delta(addr, _heap_start);
 534   const size_t beg_region = obj_ofs >> Log2RegionSize;
 535   // end_region is inclusive
 536   const size_t end_region = (obj_ofs + len - 1) >> Log2RegionSize;
 537 
 538   if (beg_region == end_region) {
 539     // All in one region.
 540     _region_data[beg_region].add_live_obj(len);
 541     return;
 542   }
 543 
 544   // First region.
 545   const size_t beg_ofs = region_offset(addr);
 546   _region_data[beg_region].add_live_obj(RegionSize - beg_ofs);
 547 
 548   // Middle regions--completely spanned by this object.
 549   for (size_t region = beg_region + 1; region < end_region; ++region) {
 550     _region_data[region].set_partial_obj_size(RegionSize);
 551     _region_data[region].set_partial_obj_addr(addr);
 552   }
 553 
 554   // Last region.
 555   const size_t end_ofs = region_offset(addr + len - 1);
 556   _region_data[end_region].set_partial_obj_size(end_ofs + 1);
 557   _region_data[end_region].set_partial_obj_addr(addr);
 558 }
 559 
 560 void
 561 ParallelCompactData::summarize_dense_prefix(HeapWord* beg, HeapWord* end)
 562 {
 563   assert(is_region_aligned(beg), "not RegionSize aligned");
 564   assert(is_region_aligned(end), "not RegionSize aligned");
 565 
 566   size_t cur_region = addr_to_region_idx(beg);
 567   const size_t end_region = addr_to_region_idx(end);
 568   HeapWord* addr = beg;
 569   while (cur_region < end_region) {
 570     _region_data[cur_region].set_destination(addr);
 571     _region_data[cur_region].set_destination_count(0);
 572     _region_data[cur_region].set_source_region(cur_region);
 573     _region_data[cur_region].set_data_location(addr);
 574 
 575     // Update live_obj_size so the region appears completely full.
 576     size_t live_size = RegionSize - _region_data[cur_region].partial_obj_size();
 577     _region_data[cur_region].set_live_obj_size(live_size);
 578 
 579     ++cur_region;
 580     addr += RegionSize;
 581   }
 582 }
 583 
 584 // Find the point at which a space can be split and, if necessary, record the
 585 // split point.
 586 //
 587 // If the current src region (which overflowed the destination space) doesn't
 588 // have a partial object, the split point is at the beginning of the current src
 589 // region (an "easy" split, no extra bookkeeping required).
 590 //
 591 // If the current src region has a partial object, the split point is in the
 592 // region where that partial object starts (call it the split_region).  If
 593 // split_region has a partial object, then the split point is just after that
 594 // partial object (a "hard" split where we have to record the split data and
 595 // zero the partial_obj_size field).  With a "hard" split, we know that the
 596 // partial_obj ends within split_region because the partial object that caused
 597 // the overflow starts in split_region.  If split_region doesn't have a partial
 598 // obj, then the split is at the beginning of split_region (another "easy"
 599 // split).
 600 HeapWord*
 601 ParallelCompactData::summarize_split_space(size_t src_region,
 602                                            SplitInfo& split_info,
 603                                            HeapWord* destination,
 604                                            HeapWord* target_end,
 605                                            HeapWord** target_next)
 606 {
 607   assert(destination <= target_end, "sanity");
 608   assert(destination + _region_data[src_region].data_size() > target_end,
 609     "region should not fit into target space");
 610   assert(is_region_aligned(target_end), "sanity");
 611 
 612   size_t split_region = src_region;
 613   HeapWord* split_destination = destination;
 614   size_t partial_obj_size = _region_data[src_region].partial_obj_size();
 615 
 616   if (destination + partial_obj_size > target_end) {
 617     // The split point is just after the partial object (if any) in the
 618     // src_region that contains the start of the object that overflowed the
 619     // destination space.
 620     //
 621     // Find the start of the "overflow" object and set split_region to the
 622     // region containing it.
 623     HeapWord* const overflow_obj = _region_data[src_region].partial_obj_addr();
 624     split_region = addr_to_region_idx(overflow_obj);
 625 
 626     // Clear the source_region field of all destination regions whose first word
 627     // came from data after the split point (a non-null source_region field
 628     // implies a region must be filled).
 629     //
 630     // An alternative to the simple loop below:  clear during post_compact(),
 631     // which uses memcpy instead of individual stores, and is easy to
 632     // parallelize.  (The downside is that it clears the entire RegionData
 633     // object as opposed to just one field.)
 634     //
 635     // post_compact() would have to clear the summary data up to the highest
 636     // address that was written during the summary phase, which would be
 637     //
 638     //         max(top, max(new_top, clear_top))
 639     //
 640     // where clear_top is a new field in SpaceInfo.  Would have to set clear_top
 641     // to target_end.
 642     const RegionData* const sr = region(split_region);
 643     const size_t beg_idx =
 644       addr_to_region_idx(region_align_up(sr->destination() +
 645                                          sr->partial_obj_size()));
 646     const size_t end_idx = addr_to_region_idx(target_end);
 647 
 648     log_develop_trace(gc, compaction)("split:  clearing source_region field in [" SIZE_FORMAT ", " SIZE_FORMAT ")", beg_idx, end_idx);
 649     for (size_t idx = beg_idx; idx < end_idx; ++idx) {
 650       _region_data[idx].set_source_region(0);
 651     }
 652 
 653     // Set split_destination and partial_obj_size to reflect the split region.
 654     split_destination = sr->destination();
 655     partial_obj_size = sr->partial_obj_size();
 656   }
 657 
 658   // The split is recorded only if a partial object extends onto the region.
 659   if (partial_obj_size != 0) {
 660     _region_data[split_region].set_partial_obj_size(0);
 661     split_info.record(split_region, partial_obj_size, split_destination);
 662   }
 663 
 664   // Setup the continuation addresses.
 665   *target_next = split_destination + partial_obj_size;
 666   HeapWord* const source_next = region_to_addr(split_region) + partial_obj_size;
 667 
 668   if (log_develop_is_enabled(Trace, gc, compaction)) {
 669     const char * split_type = partial_obj_size == 0 ? "easy" : "hard";
 670     log_develop_trace(gc, compaction)("%s split:  src=" PTR_FORMAT " src_c=" SIZE_FORMAT " pos=" SIZE_FORMAT,
 671                                       split_type, p2i(source_next), split_region, partial_obj_size);
 672     log_develop_trace(gc, compaction)("%s split:  dst=" PTR_FORMAT " dst_c=" SIZE_FORMAT " tn=" PTR_FORMAT,
 673                                       split_type, p2i(split_destination),
 674                                       addr_to_region_idx(split_destination),
 675                                       p2i(*target_next));
 676 
 677     if (partial_obj_size != 0) {
 678       HeapWord* const po_beg = split_info.destination();
 679       HeapWord* const po_end = po_beg + split_info.partial_obj_size();
 680       log_develop_trace(gc, compaction)("%s split:  po_beg=" PTR_FORMAT " " SIZE_FORMAT " po_end=" PTR_FORMAT " " SIZE_FORMAT,
 681                                         split_type,
 682                                         p2i(po_beg), addr_to_region_idx(po_beg),
 683                                         p2i(po_end), addr_to_region_idx(po_end));
 684     }
 685   }
 686 
 687   return source_next;
 688 }
 689 
 690 bool ParallelCompactData::summarize(SplitInfo& split_info,
 691                                     HeapWord* source_beg, HeapWord* source_end,
 692                                     HeapWord** source_next,
 693                                     HeapWord* target_beg, HeapWord* target_end,
 694                                     HeapWord** target_next)
 695 {
 696   HeapWord* const source_next_val = source_next == nullptr ? nullptr : *source_next;
 697   log_develop_trace(gc, compaction)(
 698       "sb=" PTR_FORMAT " se=" PTR_FORMAT " sn=" PTR_FORMAT
 699       "tb=" PTR_FORMAT " te=" PTR_FORMAT " tn=" PTR_FORMAT,
 700       p2i(source_beg), p2i(source_end), p2i(source_next_val),
 701       p2i(target_beg), p2i(target_end), p2i(*target_next));
 702 
 703   size_t cur_region = addr_to_region_idx(source_beg);
 704   const size_t end_region = addr_to_region_idx(region_align_up(source_end));
 705 
 706   HeapWord *dest_addr = target_beg;
 707   while (cur_region < end_region) {
 708     // The destination must be set even if the region has no data.
 709     _region_data[cur_region].set_destination(dest_addr);
 710 
 711     size_t words = _region_data[cur_region].data_size();
 712     if (words > 0) {
 713       // If cur_region does not fit entirely into the target space, find a point
 714       // at which the source space can be 'split' so that part is copied to the
 715       // target space and the rest is copied elsewhere.
 716       if (dest_addr + words > target_end) {
 717         assert(source_next != nullptr, "source_next is null when splitting");
 718         *source_next = summarize_split_space(cur_region, split_info, dest_addr,
 719                                              target_end, target_next);
 720         return false;
 721       }
 722 
 723       // Compute the destination_count for cur_region, and if necessary, update
 724       // source_region for a destination region.  The source_region field is
 725       // updated if cur_region is the first (left-most) region to be copied to a
 726       // destination region.
 727       //
 728       // The destination_count calculation is a bit subtle.  A region that has
 729       // data that compacts into itself does not count itself as a destination.
 730       // This maintains the invariant that a zero count means the region is
 731       // available and can be claimed and then filled.
 732       uint destination_count = 0;
 733       if (split_info.is_split(cur_region)) {
 734         // The current region has been split:  the partial object will be copied
 735         // to one destination space and the remaining data will be copied to
 736         // another destination space.  Adjust the initial destination_count and,
 737         // if necessary, set the source_region field if the partial object will
 738         // cross a destination region boundary.
 739         destination_count = split_info.destination_count();
 740         if (destination_count == 2) {
 741           size_t dest_idx = addr_to_region_idx(split_info.dest_region_addr());
 742           _region_data[dest_idx].set_source_region(cur_region);
 743         }
 744       }
 745 
 746       HeapWord* const last_addr = dest_addr + words - 1;
 747       const size_t dest_region_1 = addr_to_region_idx(dest_addr);
 748       const size_t dest_region_2 = addr_to_region_idx(last_addr);
 749 
 750       // Initially assume that the destination regions will be the same and
 751       // adjust the value below if necessary.  Under this assumption, if
 752       // cur_region == dest_region_2, then cur_region will be compacted
 753       // completely into itself.
 754       destination_count += cur_region == dest_region_2 ? 0 : 1;
 755       if (dest_region_1 != dest_region_2) {
 756         // Destination regions differ; adjust destination_count.
 757         destination_count += 1;
 758         // Data from cur_region will be copied to the start of dest_region_2.
 759         _region_data[dest_region_2].set_source_region(cur_region);
 760       } else if (is_region_aligned(dest_addr)) {
 761         // Data from cur_region will be copied to the start of the destination
 762         // region.
 763         _region_data[dest_region_1].set_source_region(cur_region);
 764       }
 765 
 766       _region_data[cur_region].set_destination_count(destination_count);
 767       _region_data[cur_region].set_data_location(region_to_addr(cur_region));
 768       dest_addr += words;
 769     }
 770 
 771     ++cur_region;
 772   }
 773 
 774   *target_next = dest_addr;
 775   return true;
 776 }
 777 
 778 HeapWord* ParallelCompactData::calc_new_pointer(HeapWord* addr, ParCompactionManager* cm) const {
 779   assert(addr != nullptr, "Should detect null oop earlier");
 780   assert(ParallelScavengeHeap::heap()->is_in(addr), "not in heap");
 781   assert(PSParallelCompact::mark_bitmap()->is_marked(addr), "not marked");
 782 
 783   // Region covering the object.
 784   RegionData* const region_ptr = addr_to_region_ptr(addr);
 785   HeapWord* result = region_ptr->destination();
 786 
 787   // If the entire Region is live, the new location is region->destination + the
 788   // offset of the object within in the Region.
 789 
 790   // Run some performance tests to determine if this special case pays off.  It
 791   // is worth it for pointers into the dense prefix.  If the optimization to
 792   // avoid pointer updates in regions that only point to the dense prefix is
 793   // ever implemented, this should be revisited.
 794   if (region_ptr->data_size() == RegionSize) {
 795     result += region_offset(addr);
 796     return result;
 797   }
 798 
 799   // Otherwise, the new location is region->destination + block offset + the
 800   // number of live words in the Block that are (a) to the left of addr and (b)
 801   // due to objects that start in the Block.
 802 
 803   // Fill in the block table if necessary.  This is unsynchronized, so multiple
 804   // threads may fill the block table for a region (harmless, since it is
 805   // idempotent).
 806   if (!region_ptr->blocks_filled()) {
 807     PSParallelCompact::fill_blocks(addr_to_region_idx(addr));
 808     region_ptr->set_blocks_filled();
 809   }
 810 
 811   HeapWord* const search_start = block_align_down(addr);
 812   const size_t block_offset = addr_to_block_ptr(addr)->offset();
 813 
 814   const ParMarkBitMap* bitmap = PSParallelCompact::mark_bitmap();
 815   const size_t live = bitmap->live_words_in_range(cm, search_start, cast_to_oop(addr));
 816   result += block_offset + live;
 817   DEBUG_ONLY(PSParallelCompact::check_new_location(addr, result));
 818   return result;
 819 }
 820 
 821 #ifdef ASSERT
 822 void ParallelCompactData::verify_clear(const PSVirtualSpace* vspace)
 823 {
 824   const size_t* const beg = (const size_t*)vspace->committed_low_addr();
 825   const size_t* const end = (const size_t*)vspace->committed_high_addr();
 826   for (const size_t* p = beg; p < end; ++p) {
 827     assert(*p == 0, "not zero");
 828   }
 829 }
 830 
 831 void ParallelCompactData::verify_clear()
 832 {
 833   verify_clear(_region_vspace);
 834   verify_clear(_block_vspace);
 835 }
 836 #endif  // #ifdef ASSERT
 837 
 838 STWGCTimer          PSParallelCompact::_gc_timer;
 839 ParallelOldTracer   PSParallelCompact::_gc_tracer;
 840 elapsedTimer        PSParallelCompact::_accumulated_time;
 841 unsigned int        PSParallelCompact::_maximum_compaction_gc_num = 0;
 842 CollectorCounters*  PSParallelCompact::_counters = nullptr;
 843 ParMarkBitMap       PSParallelCompact::_mark_bitmap;
 844 ParallelCompactData PSParallelCompact::_summary_data;
 845 
 846 PSParallelCompact::IsAliveClosure PSParallelCompact::_is_alive_closure;
 847 
 848 bool PSParallelCompact::IsAliveClosure::do_object_b(oop p) { return mark_bitmap()->is_marked(p); }
 849 
 850 void PSParallelCompact::post_initialize() {
 851   ParallelScavengeHeap* heap = ParallelScavengeHeap::heap();
 852   _span_based_discoverer.set_span(heap->reserved_region());
 853   _ref_processor =
 854     new ReferenceProcessor(&_span_based_discoverer,
 855                            ParallelGCThreads,   // mt processing degree
 856                            ParallelGCThreads,   // mt discovery degree
 857                            false,               // concurrent_discovery
 858                            &_is_alive_closure); // non-header is alive closure
 859 
 860   _counters = new CollectorCounters("Parallel full collection pauses", 1);
 861 
 862   // Initialize static fields in ParCompactionManager.
 863   ParCompactionManager::initialize(mark_bitmap());
 864 }
 865 
 866 bool PSParallelCompact::initialize() {
 867   ParallelScavengeHeap* heap = ParallelScavengeHeap::heap();
 868   MemRegion mr = heap->reserved_region();
 869 
 870   // Was the old gen get allocated successfully?
 871   if (!heap->old_gen()->is_allocated()) {
 872     return false;
 873   }
 874 
 875   initialize_space_info();
 876   initialize_dead_wood_limiter();
 877 
 878   if (!_mark_bitmap.initialize(mr)) {
 879     vm_shutdown_during_initialization(
 880       err_msg("Unable to allocate " SIZE_FORMAT "KB bitmaps for parallel "
 881       "garbage collection for the requested " SIZE_FORMAT "KB heap.",
 882       _mark_bitmap.reserved_byte_size()/K, mr.byte_size()/K));
 883     return false;
 884   }
 885 
 886   if (!_summary_data.initialize(mr)) {
 887     vm_shutdown_during_initialization(
 888       err_msg("Unable to allocate " SIZE_FORMAT "KB card tables for parallel "
 889       "garbage collection for the requested " SIZE_FORMAT "KB heap.",
 890       _summary_data.reserved_byte_size()/K, mr.byte_size()/K));
 891     return false;
 892   }
 893 
 894   return true;
 895 }
 896 
 897 void PSParallelCompact::initialize_space_info()
 898 {
 899   memset(&_space_info, 0, sizeof(_space_info));
 900 
 901   ParallelScavengeHeap* heap = ParallelScavengeHeap::heap();
 902   PSYoungGen* young_gen = heap->young_gen();
 903 
 904   _space_info[old_space_id].set_space(heap->old_gen()->object_space());
 905   _space_info[eden_space_id].set_space(young_gen->eden_space());
 906   _space_info[from_space_id].set_space(young_gen->from_space());
 907   _space_info[to_space_id].set_space(young_gen->to_space());
 908 
 909   _space_info[old_space_id].set_start_array(heap->old_gen()->start_array());
 910 }
 911 
 912 void PSParallelCompact::initialize_dead_wood_limiter()
 913 {
 914   const size_t max = 100;
 915   _dwl_mean = double(MIN2(ParallelOldDeadWoodLimiterMean, max)) / 100.0;
 916   _dwl_std_dev = double(MIN2(ParallelOldDeadWoodLimiterStdDev, max)) / 100.0;
 917   _dwl_first_term = 1.0 / (sqrt(2.0 * M_PI) * _dwl_std_dev);
 918   DEBUG_ONLY(_dwl_initialized = true;)
 919   _dwl_adjustment = normal_distribution(1.0);
 920 }
 921 
 922 void
 923 PSParallelCompact::clear_data_covering_space(SpaceId id)
 924 {
 925   // At this point, top is the value before GC, new_top() is the value that will
 926   // be set at the end of GC.  The marking bitmap is cleared to top; nothing
 927   // should be marked above top.  The summary data is cleared to the larger of
 928   // top & new_top.
 929   MutableSpace* const space = _space_info[id].space();
 930   HeapWord* const bot = space->bottom();
 931   HeapWord* const top = space->top();
 932   HeapWord* const max_top = MAX2(top, _space_info[id].new_top());
 933 
 934   const idx_t beg_bit = _mark_bitmap.addr_to_bit(bot);
 935   const idx_t end_bit = _mark_bitmap.align_range_end(_mark_bitmap.addr_to_bit(top));
 936   _mark_bitmap.clear_range(beg_bit, end_bit);
 937 
 938   const size_t beg_region = _summary_data.addr_to_region_idx(bot);
 939   const size_t end_region =
 940     _summary_data.addr_to_region_idx(_summary_data.region_align_up(max_top));
 941   _summary_data.clear_range(beg_region, end_region);
 942 
 943   // Clear the data used to 'split' regions.
 944   SplitInfo& split_info = _space_info[id].split_info();
 945   if (split_info.is_valid()) {
 946     split_info.clear();
 947   }
 948   DEBUG_ONLY(split_info.verify_clear();)
 949 }
 950 
 951 void PSParallelCompact::pre_compact()
 952 {
 953   // Update the from & to space pointers in space_info, since they are swapped
 954   // at each young gen gc.  Do the update unconditionally (even though a
 955   // promotion failure does not swap spaces) because an unknown number of young
 956   // collections will have swapped the spaces an unknown number of times.
 957   GCTraceTime(Debug, gc, phases) tm("Pre Compact", &_gc_timer);
 958   ParallelScavengeHeap* heap = ParallelScavengeHeap::heap();
 959   _space_info[from_space_id].set_space(heap->young_gen()->from_space());
 960   _space_info[to_space_id].set_space(heap->young_gen()->to_space());
 961 
 962   // Increment the invocation count
 963   heap->increment_total_collections(true);
 964 
 965   CodeCache::on_gc_marking_cycle_start();
 966 
 967   heap->print_heap_before_gc();
 968   heap->trace_heap_before_gc(&_gc_tracer);
 969 
 970   // Fill in TLABs
 971   heap->ensure_parsability(true);  // retire TLABs
 972 
 973   if (VerifyBeforeGC && heap->total_collections() >= VerifyGCStartAt) {
 974     Universe::verify("Before GC");
 975   }
 976 
 977   // Verify object start arrays
 978   if (VerifyObjectStartArray &&
 979       VerifyBeforeGC) {
 980     heap->old_gen()->verify_object_start_array();
 981   }
 982 
 983   DEBUG_ONLY(mark_bitmap()->verify_clear();)
 984   DEBUG_ONLY(summary_data().verify_clear();)
 985 
 986   ParCompactionManager::reset_all_bitmap_query_caches();
 987 }
 988 
 989 void PSParallelCompact::post_compact()
 990 {
 991   GCTraceTime(Info, gc, phases) tm("Post Compact", &_gc_timer);
 992   ParCompactionManager::remove_all_shadow_regions();
 993 
 994   CodeCache::on_gc_marking_cycle_finish();
 995   CodeCache::arm_all_nmethods();
 996 
 997   for (unsigned int id = old_space_id; id < last_space_id; ++id) {
 998     // Clear the marking bitmap, summary data and split info.
 999     clear_data_covering_space(SpaceId(id));
1000     // Update top().  Must be done after clearing the bitmap and summary data.
1001     _space_info[id].publish_new_top();
1002   }
1003 
1004   ParCompactionManager::flush_all_string_dedup_requests();
1005 
1006   MutableSpace* const eden_space = _space_info[eden_space_id].space();
1007   MutableSpace* const from_space = _space_info[from_space_id].space();
1008   MutableSpace* const to_space   = _space_info[to_space_id].space();
1009 
1010   ParallelScavengeHeap* heap = ParallelScavengeHeap::heap();
1011   bool eden_empty = eden_space->is_empty();
1012 
1013   // Update heap occupancy information which is used as input to the soft ref
1014   // clearing policy at the next gc.
1015   Universe::heap()->update_capacity_and_used_at_gc();
1016 
1017   bool young_gen_empty = eden_empty && from_space->is_empty() &&
1018     to_space->is_empty();
1019 
1020   PSCardTable* ct = heap->card_table();
1021   MemRegion old_mr = heap->old_gen()->committed();
1022   if (young_gen_empty) {
1023     ct->clear_MemRegion(old_mr);
1024   } else {
1025     ct->dirty_MemRegion(old_mr);
1026   }
1027 
1028   {
1029     // Delete metaspaces for unloaded class loaders and clean up loader_data graph
1030     GCTraceTime(Debug, gc, phases) t("Purge Class Loader Data", gc_timer());
1031     ClassLoaderDataGraph::purge(true /* at_safepoint */);
1032     DEBUG_ONLY(MetaspaceUtils::verify();)
1033   }
1034 
1035   // Need to clear claim bits for the next mark.
1036   ClassLoaderDataGraph::clear_claimed_marks();
1037 
1038   heap->prune_scavengable_nmethods();
1039 
1040 #if COMPILER2_OR_JVMCI
1041   DerivedPointerTable::update_pointers();
1042 #endif
1043 
1044   if (ZapUnusedHeapArea) {
1045     heap->gen_mangle_unused_area();
1046   }
1047 
1048   // Signal that we have completed a visit to all live objects.
1049   Universe::heap()->record_whole_heap_examined_timestamp();
1050 }
1051 
1052 HeapWord*
1053 PSParallelCompact::compute_dense_prefix_via_density(const SpaceId id,
1054                                                     bool maximum_compaction)
1055 {
1056   const size_t region_size = ParallelCompactData::RegionSize;
1057   const ParallelCompactData& sd = summary_data();
1058 
1059   const MutableSpace* const space = _space_info[id].space();
1060   HeapWord* const top_aligned_up = sd.region_align_up(space->top());
1061   const RegionData* const beg_cp = sd.addr_to_region_ptr(space->bottom());
1062   const RegionData* const end_cp = sd.addr_to_region_ptr(top_aligned_up);
1063 
1064   // Skip full regions at the beginning of the space--they are necessarily part
1065   // of the dense prefix.
1066   size_t full_count = 0;
1067   const RegionData* cp;
1068   for (cp = beg_cp; cp < end_cp && cp->data_size() == region_size; ++cp) {
1069     ++full_count;
1070   }
1071 
1072   const uint total_invocations = ParallelScavengeHeap::heap()->total_full_collections();
1073   assert(total_invocations >= _maximum_compaction_gc_num, "sanity");
1074   const size_t gcs_since_max = total_invocations - _maximum_compaction_gc_num;
1075   const bool interval_ended = gcs_since_max > HeapMaximumCompactionInterval;
1076   if (maximum_compaction || cp == end_cp || interval_ended) {
1077     _maximum_compaction_gc_num = total_invocations;
1078     return sd.region_to_addr(cp);
1079   }
1080 
1081   HeapWord* const new_top = _space_info[id].new_top();
1082   const size_t space_live = pointer_delta(new_top, space->bottom());
1083   const size_t space_used = space->used_in_words();
1084   const size_t space_capacity = space->capacity_in_words();
1085 
1086   const double cur_density = double(space_live) / space_capacity;
1087   const double deadwood_density =
1088     (1.0 - cur_density) * (1.0 - cur_density) * cur_density * cur_density;
1089   const size_t deadwood_goal = size_t(space_capacity * deadwood_density);
1090 
1091   log_develop_debug(gc, compaction)(
1092       "cur_dens=%5.3f dw_dens=%5.3f dw_goal=" SIZE_FORMAT,
1093       cur_density, deadwood_density, deadwood_goal);
1094   log_develop_debug(gc, compaction)(
1095       "space_live=" SIZE_FORMAT " space_used=" SIZE_FORMAT " "
1096       "space_cap=" SIZE_FORMAT,
1097       space_live, space_used,
1098       space_capacity);
1099 
1100   // XXX - Use binary search?
1101   HeapWord* dense_prefix = sd.region_to_addr(cp);
1102   const RegionData* full_cp = cp;
1103   const RegionData* const top_cp = sd.addr_to_region_ptr(space->top() - 1);
1104   while (cp < end_cp) {
1105     HeapWord* region_destination = cp->destination();
1106     const size_t cur_deadwood = pointer_delta(dense_prefix, region_destination);
1107 
1108     log_develop_trace(gc, compaction)(
1109         "c#=" SIZE_FORMAT_W(4) " dst=" PTR_FORMAT " "
1110         "dp=" PTR_FORMAT " cdw=" SIZE_FORMAT_W(8),
1111         sd.region(cp), p2i(region_destination),
1112         p2i(dense_prefix), cur_deadwood);
1113 
1114     if (cur_deadwood >= deadwood_goal) {
1115       // Found the region that has the correct amount of deadwood to the left.
1116       // This typically occurs after crossing a fairly sparse set of regions, so
1117       // iterate backwards over those sparse regions, looking for the region
1118       // that has the lowest density of live objects 'to the right.'
1119       size_t space_to_left = sd.region(cp) * region_size;
1120       size_t live_to_left = space_to_left - cur_deadwood;
1121       size_t space_to_right = space_capacity - space_to_left;
1122       size_t live_to_right = space_live - live_to_left;
1123       double density_to_right = double(live_to_right) / space_to_right;
1124       while (cp > full_cp) {
1125         --cp;
1126         const size_t prev_region_live_to_right = live_to_right -
1127           cp->data_size();
1128         const size_t prev_region_space_to_right = space_to_right + region_size;
1129         double prev_region_density_to_right =
1130           double(prev_region_live_to_right) / prev_region_space_to_right;
1131         if (density_to_right <= prev_region_density_to_right) {
1132           return dense_prefix;
1133         }
1134 
1135         log_develop_trace(gc, compaction)(
1136             "backing up from c=" SIZE_FORMAT_W(4) " d2r=%10.8f "
1137             "pc_d2r=%10.8f",
1138             sd.region(cp), density_to_right,
1139             prev_region_density_to_right);
1140 
1141         dense_prefix -= region_size;
1142         live_to_right = prev_region_live_to_right;
1143         space_to_right = prev_region_space_to_right;
1144         density_to_right = prev_region_density_to_right;
1145       }
1146       return dense_prefix;
1147     }
1148 
1149     dense_prefix += region_size;
1150     ++cp;
1151   }
1152 
1153   return dense_prefix;
1154 }
1155 
1156 #ifndef PRODUCT
1157 void PSParallelCompact::print_dense_prefix_stats(const char* const algorithm,
1158                                                  const SpaceId id,
1159                                                  const bool maximum_compaction,
1160                                                  HeapWord* const addr)
1161 {
1162   const size_t region_idx = summary_data().addr_to_region_idx(addr);
1163   RegionData* const cp = summary_data().region(region_idx);
1164   const MutableSpace* const space = _space_info[id].space();
1165   HeapWord* const new_top = _space_info[id].new_top();
1166 
1167   const size_t space_live = pointer_delta(new_top, space->bottom());
1168   const size_t dead_to_left = pointer_delta(addr, cp->destination());
1169   const size_t space_cap = space->capacity_in_words();
1170   const double dead_to_left_pct = double(dead_to_left) / space_cap;
1171   const size_t live_to_right = new_top - cp->destination();
1172   const size_t dead_to_right = space->top() - addr - live_to_right;
1173 
1174   log_develop_debug(gc, compaction)(
1175       "%s=" PTR_FORMAT " dpc=" SIZE_FORMAT_W(5) " "
1176       "spl=" SIZE_FORMAT " "
1177       "d2l=" SIZE_FORMAT " d2l%%=%6.4f "
1178       "d2r=" SIZE_FORMAT " l2r=" SIZE_FORMAT " "
1179       "ratio=%10.8f",
1180       algorithm, p2i(addr), region_idx,
1181       space_live,
1182       dead_to_left, dead_to_left_pct,
1183       dead_to_right, live_to_right,
1184       double(dead_to_right) / live_to_right);
1185 }
1186 #endif  // #ifndef PRODUCT
1187 
1188 // Return a fraction indicating how much of the generation can be treated as
1189 // "dead wood" (i.e., not reclaimed).  The function uses a normal distribution
1190 // based on the density of live objects in the generation to determine a limit,
1191 // which is then adjusted so the return value is min_percent when the density is
1192 // 1.
1193 //
1194 // The following table shows some return values for a different values of the
1195 // standard deviation (ParallelOldDeadWoodLimiterStdDev); the mean is 0.5 and
1196 // min_percent is 1.
1197 //
1198 //                          fraction allowed as dead wood
1199 //         -----------------------------------------------------------------
1200 // density std_dev=70 std_dev=75 std_dev=80 std_dev=85 std_dev=90 std_dev=95
1201 // ------- ---------- ---------- ---------- ---------- ---------- ----------
1202 // 0.00000 0.01000000 0.01000000 0.01000000 0.01000000 0.01000000 0.01000000
1203 // 0.05000 0.03193096 0.02836880 0.02550828 0.02319280 0.02130337 0.01974941
1204 // 0.10000 0.05247504 0.04547452 0.03988045 0.03537016 0.03170171 0.02869272
1205 // 0.15000 0.07135702 0.06111390 0.05296419 0.04641639 0.04110601 0.03676066
1206 // 0.20000 0.08831616 0.07509618 0.06461766 0.05622444 0.04943437 0.04388975
1207 // 0.25000 0.10311208 0.08724696 0.07471205 0.06469760 0.05661313 0.05002313
1208 // 0.30000 0.11553050 0.09741183 0.08313394 0.07175114 0.06257797 0.05511132
1209 // 0.35000 0.12538832 0.10545958 0.08978741 0.07731366 0.06727491 0.05911289
1210 // 0.40000 0.13253818 0.11128511 0.09459590 0.08132834 0.07066107 0.06199500
1211 // 0.45000 0.13687208 0.11481163 0.09750361 0.08375387 0.07270534 0.06373386
1212 // 0.50000 0.13832410 0.11599237 0.09847664 0.08456518 0.07338887 0.06431510
1213 // 0.55000 0.13687208 0.11481163 0.09750361 0.08375387 0.07270534 0.06373386
1214 // 0.60000 0.13253818 0.11128511 0.09459590 0.08132834 0.07066107 0.06199500
1215 // 0.65000 0.12538832 0.10545958 0.08978741 0.07731366 0.06727491 0.05911289
1216 // 0.70000 0.11553050 0.09741183 0.08313394 0.07175114 0.06257797 0.05511132
1217 // 0.75000 0.10311208 0.08724696 0.07471205 0.06469760 0.05661313 0.05002313
1218 // 0.80000 0.08831616 0.07509618 0.06461766 0.05622444 0.04943437 0.04388975
1219 // 0.85000 0.07135702 0.06111390 0.05296419 0.04641639 0.04110601 0.03676066
1220 // 0.90000 0.05247504 0.04547452 0.03988045 0.03537016 0.03170171 0.02869272
1221 // 0.95000 0.03193096 0.02836880 0.02550828 0.02319280 0.02130337 0.01974941
1222 // 1.00000 0.01000000 0.01000000 0.01000000 0.01000000 0.01000000 0.01000000
1223 
1224 double PSParallelCompact::dead_wood_limiter(double density, size_t min_percent)
1225 {
1226   assert(_dwl_initialized, "uninitialized");
1227 
1228   // The raw limit is the value of the normal distribution at x = density.
1229   const double raw_limit = normal_distribution(density);
1230 
1231   // Adjust the raw limit so it becomes the minimum when the density is 1.
1232   //
1233   // First subtract the adjustment value (which is simply the precomputed value
1234   // normal_distribution(1.0)); this yields a value of 0 when the density is 1.
1235   // Then add the minimum value, so the minimum is returned when the density is
1236   // 1.  Finally, prevent negative values, which occur when the mean is not 0.5.
1237   const double min = double(min_percent) / 100.0;
1238   const double limit = raw_limit - _dwl_adjustment + min;
1239   return MAX2(limit, 0.0);
1240 }
1241 
1242 ParallelCompactData::RegionData*
1243 PSParallelCompact::first_dead_space_region(const RegionData* beg,
1244                                            const RegionData* end)
1245 {
1246   const size_t region_size = ParallelCompactData::RegionSize;
1247   ParallelCompactData& sd = summary_data();
1248   size_t left = sd.region(beg);
1249   size_t right = end > beg ? sd.region(end) - 1 : left;
1250 
1251   // Binary search.
1252   while (left < right) {
1253     // Equivalent to (left + right) / 2, but does not overflow.
1254     const size_t middle = left + (right - left) / 2;
1255     RegionData* const middle_ptr = sd.region(middle);
1256     HeapWord* const dest = middle_ptr->destination();
1257     HeapWord* const addr = sd.region_to_addr(middle);
1258     assert(dest != nullptr, "sanity");
1259     assert(dest <= addr, "must move left");
1260 
1261     if (middle > left && dest < addr) {
1262       right = middle - 1;
1263     } else if (middle < right && middle_ptr->data_size() == region_size) {
1264       left = middle + 1;
1265     } else {
1266       return middle_ptr;
1267     }
1268   }
1269   return sd.region(left);
1270 }
1271 
1272 ParallelCompactData::RegionData*
1273 PSParallelCompact::dead_wood_limit_region(const RegionData* beg,
1274                                           const RegionData* end,
1275                                           size_t dead_words)
1276 {
1277   ParallelCompactData& sd = summary_data();
1278   size_t left = sd.region(beg);
1279   size_t right = end > beg ? sd.region(end) - 1 : left;
1280 
1281   // Binary search.
1282   while (left < right) {
1283     // Equivalent to (left + right) / 2, but does not overflow.
1284     const size_t middle = left + (right - left) / 2;
1285     RegionData* const middle_ptr = sd.region(middle);
1286     HeapWord* const dest = middle_ptr->destination();
1287     HeapWord* const addr = sd.region_to_addr(middle);
1288     assert(dest != nullptr, "sanity");
1289     assert(dest <= addr, "must move left");
1290 
1291     const size_t dead_to_left = pointer_delta(addr, dest);
1292     if (middle > left && dead_to_left > dead_words) {
1293       right = middle - 1;
1294     } else if (middle < right && dead_to_left < dead_words) {
1295       left = middle + 1;
1296     } else {
1297       return middle_ptr;
1298     }
1299   }
1300   return sd.region(left);
1301 }
1302 
1303 // The result is valid during the summary phase, after the initial summarization
1304 // of each space into itself, and before final summarization.
1305 inline double
1306 PSParallelCompact::reclaimed_ratio(const RegionData* const cp,
1307                                    HeapWord* const bottom,
1308                                    HeapWord* const top,
1309                                    HeapWord* const new_top)
1310 {
1311   ParallelCompactData& sd = summary_data();
1312 
1313   assert(cp != nullptr, "sanity");
1314   assert(bottom != nullptr, "sanity");
1315   assert(top != nullptr, "sanity");
1316   assert(new_top != nullptr, "sanity");
1317   assert(top >= new_top, "summary data problem?");
1318   assert(new_top > bottom, "space is empty; should not be here");
1319   assert(new_top >= cp->destination(), "sanity");
1320   assert(top >= sd.region_to_addr(cp), "sanity");
1321 
1322   HeapWord* const destination = cp->destination();
1323   const size_t dense_prefix_live  = pointer_delta(destination, bottom);
1324   const size_t compacted_region_live = pointer_delta(new_top, destination);
1325   const size_t compacted_region_used = pointer_delta(top,
1326                                                      sd.region_to_addr(cp));
1327   const size_t reclaimable = compacted_region_used - compacted_region_live;
1328 
1329   const double divisor = dense_prefix_live + 1.25 * compacted_region_live;
1330   return double(reclaimable) / divisor;
1331 }
1332 
1333 // Return the address of the end of the dense prefix, a.k.a. the start of the
1334 // compacted region.  The address is always on a region boundary.
1335 //
1336 // Completely full regions at the left are skipped, since no compaction can
1337 // occur in those regions.  Then the maximum amount of dead wood to allow is
1338 // computed, based on the density (amount live / capacity) of the generation;
1339 // the region with approximately that amount of dead space to the left is
1340 // identified as the limit region.  Regions between the last completely full
1341 // region and the limit region are scanned and the one that has the best
1342 // (maximum) reclaimed_ratio() is selected.
1343 HeapWord*
1344 PSParallelCompact::compute_dense_prefix(const SpaceId id,
1345                                         bool maximum_compaction)
1346 {
1347   const size_t region_size = ParallelCompactData::RegionSize;
1348   const ParallelCompactData& sd = summary_data();
1349 
1350   const MutableSpace* const space = _space_info[id].space();
1351   HeapWord* const top = space->top();
1352   HeapWord* const top_aligned_up = sd.region_align_up(top);
1353   HeapWord* const new_top = _space_info[id].new_top();
1354   HeapWord* const new_top_aligned_up = sd.region_align_up(new_top);
1355   HeapWord* const bottom = space->bottom();
1356   const RegionData* const beg_cp = sd.addr_to_region_ptr(bottom);
1357   const RegionData* const top_cp = sd.addr_to_region_ptr(top_aligned_up);
1358   const RegionData* const new_top_cp =
1359     sd.addr_to_region_ptr(new_top_aligned_up);
1360 
1361   // Skip full regions at the beginning of the space--they are necessarily part
1362   // of the dense prefix.
1363   const RegionData* const full_cp = first_dead_space_region(beg_cp, new_top_cp);
1364   assert(full_cp->destination() == sd.region_to_addr(full_cp) ||
1365          space->is_empty(), "no dead space allowed to the left");
1366   assert(full_cp->data_size() < region_size || full_cp == new_top_cp - 1,
1367          "region must have dead space");
1368 
1369   // The gc number is saved whenever a maximum compaction is done, and used to
1370   // determine when the maximum compaction interval has expired.  This avoids
1371   // successive max compactions for different reasons.
1372   const uint total_invocations = ParallelScavengeHeap::heap()->total_full_collections();
1373   assert(total_invocations >= _maximum_compaction_gc_num, "sanity");
1374   const size_t gcs_since_max = total_invocations - _maximum_compaction_gc_num;
1375   const bool interval_ended = gcs_since_max > HeapMaximumCompactionInterval ||
1376     total_invocations == HeapFirstMaximumCompactionCount;
1377   if (maximum_compaction || full_cp == top_cp || interval_ended) {
1378     _maximum_compaction_gc_num = total_invocations;
1379     return sd.region_to_addr(full_cp);
1380   }
1381 
1382   const size_t space_live = pointer_delta(new_top, bottom);
1383   const size_t space_used = space->used_in_words();
1384   const size_t space_capacity = space->capacity_in_words();
1385 
1386   const double density = double(space_live) / double(space_capacity);
1387   const size_t min_percent_free = MarkSweepDeadRatio;
1388   const double limiter = dead_wood_limiter(density, min_percent_free);
1389   const size_t dead_wood_max = space_used - space_live;
1390   const size_t dead_wood_limit = MIN2(size_t(space_capacity * limiter),
1391                                       dead_wood_max);
1392 
1393   log_develop_debug(gc, compaction)(
1394       "space_live=" SIZE_FORMAT " space_used=" SIZE_FORMAT " "
1395       "space_cap=" SIZE_FORMAT,
1396       space_live, space_used,
1397       space_capacity);
1398   log_develop_debug(gc, compaction)(
1399       "dead_wood_limiter(%6.4f, " SIZE_FORMAT ")=%6.4f "
1400       "dead_wood_max=" SIZE_FORMAT " dead_wood_limit=" SIZE_FORMAT,
1401       density, min_percent_free, limiter,
1402       dead_wood_max, dead_wood_limit);
1403 
1404   // Locate the region with the desired amount of dead space to the left.
1405   const RegionData* const limit_cp =
1406     dead_wood_limit_region(full_cp, top_cp, dead_wood_limit);
1407 
1408   // Scan from the first region with dead space to the limit region and find the
1409   // one with the best (largest) reclaimed ratio.
1410   double best_ratio = 0.0;
1411   const RegionData* best_cp = full_cp;
1412   for (const RegionData* cp = full_cp; cp < limit_cp; ++cp) {
1413     double tmp_ratio = reclaimed_ratio(cp, bottom, top, new_top);
1414     if (tmp_ratio > best_ratio) {
1415       best_cp = cp;
1416       best_ratio = tmp_ratio;
1417     }
1418   }
1419 
1420   return sd.region_to_addr(best_cp);
1421 }
1422 
1423 void PSParallelCompact::summarize_spaces_quick()
1424 {
1425   for (unsigned int i = 0; i < last_space_id; ++i) {
1426     const MutableSpace* space = _space_info[i].space();
1427     HeapWord** nta = _space_info[i].new_top_addr();
1428     bool result = _summary_data.summarize(_space_info[i].split_info(),
1429                                           space->bottom(), space->top(), nullptr,
1430                                           space->bottom(), space->end(), nta);
1431     assert(result, "space must fit into itself");
1432     _space_info[i].set_dense_prefix(space->bottom());
1433   }
1434 }
1435 
1436 void PSParallelCompact::fill_dense_prefix_end(SpaceId id)
1437 {
1438   HeapWord* const dense_prefix_end = dense_prefix(id);
1439   const RegionData* region = _summary_data.addr_to_region_ptr(dense_prefix_end);
1440   const idx_t dense_prefix_bit = _mark_bitmap.addr_to_bit(dense_prefix_end);
1441   if (dead_space_crosses_boundary(region, dense_prefix_bit)) {
1442     // Only enough dead space is filled so that any remaining dead space to the
1443     // left is larger than the minimum filler object.  (The remainder is filled
1444     // during the copy/update phase.)
1445     //
1446     // The size of the dead space to the right of the boundary is not a
1447     // concern, since compaction will be able to use whatever space is
1448     // available.
1449     //
1450     // Here '||' is the boundary, 'x' represents a don't care bit and a box
1451     // surrounds the space to be filled with an object.
1452     //
1453     // In the 32-bit VM, each bit represents two 32-bit words:
1454     //                              +---+
1455     // a) beg_bits:  ...  x   x   x | 0 | ||   0   x  x  ...
1456     //    end_bits:  ...  x   x   x | 0 | ||   0   x  x  ...
1457     //                              +---+
1458     //
1459     // In the 64-bit VM, each bit represents one 64-bit word:
1460     //                              +------------+
1461     // b) beg_bits:  ...  x   x   x | 0   ||   0 | x  x  ...
1462     //    end_bits:  ...  x   x   1 | 0   ||   0 | x  x  ...
1463     //                              +------------+
1464     //                          +-------+
1465     // c) beg_bits:  ...  x   x | 0   0 | ||   0   x  x  ...
1466     //    end_bits:  ...  x   1 | 0   0 | ||   0   x  x  ...
1467     //                          +-------+
1468     //                      +-----------+
1469     // d) beg_bits:  ...  x | 0   0   0 | ||   0   x  x  ...
1470     //    end_bits:  ...  1 | 0   0   0 | ||   0   x  x  ...
1471     //                      +-----------+
1472     //                          +-------+
1473     // e) beg_bits:  ...  0   0 | 0   0 | ||   0   x  x  ...
1474     //    end_bits:  ...  0   0 | 0   0 | ||   0   x  x  ...
1475     //                          +-------+
1476 
1477     // Initially assume case a, c or e will apply.
1478     size_t obj_len = CollectedHeap::min_fill_size();
1479     HeapWord* obj_beg = dense_prefix_end - obj_len;
1480 
1481 #ifdef  _LP64
1482     if (MinObjAlignment > 1) { // object alignment > heap word size
1483       // Cases a, c or e.
1484     } else if (_mark_bitmap.is_obj_end(dense_prefix_bit - 2)) {
1485       // Case b above.
1486       obj_beg = dense_prefix_end - 1;
1487     } else if (!_mark_bitmap.is_obj_end(dense_prefix_bit - 3) &&
1488                _mark_bitmap.is_obj_end(dense_prefix_bit - 4)) {
1489       // Case d above.
1490       obj_beg = dense_prefix_end - 3;
1491       obj_len = 3;
1492     }
1493 #endif  // #ifdef _LP64
1494 
1495     CollectedHeap::fill_with_object(obj_beg, obj_len);
1496     _mark_bitmap.mark_obj(obj_beg, obj_len);
1497     _summary_data.add_obj(obj_beg, obj_len);
1498     assert(start_array(id) != nullptr, "sanity");
1499     start_array(id)->update_for_block(obj_beg, obj_beg + obj_len);
1500   }
1501 }
1502 
1503 void
1504 PSParallelCompact::summarize_space(SpaceId id, bool maximum_compaction)
1505 {
1506   assert(id < last_space_id, "id out of range");
1507   assert(_space_info[id].dense_prefix() == _space_info[id].space()->bottom(),
1508          "should have been reset in summarize_spaces_quick()");
1509 
1510   const MutableSpace* space = _space_info[id].space();
1511   if (_space_info[id].new_top() != space->bottom()) {
1512     HeapWord* dense_prefix_end = compute_dense_prefix(id, maximum_compaction);
1513     _space_info[id].set_dense_prefix(dense_prefix_end);
1514 
1515 #ifndef PRODUCT
1516     if (log_is_enabled(Debug, gc, compaction)) {
1517       print_dense_prefix_stats("ratio", id, maximum_compaction,
1518                                dense_prefix_end);
1519       HeapWord* addr = compute_dense_prefix_via_density(id, maximum_compaction);
1520       print_dense_prefix_stats("density", id, maximum_compaction, addr);
1521     }
1522 #endif  // #ifndef PRODUCT
1523 
1524     // Recompute the summary data, taking into account the dense prefix.  If
1525     // every last byte will be reclaimed, then the existing summary data which
1526     // compacts everything can be left in place.
1527     if (!maximum_compaction && dense_prefix_end != space->bottom()) {
1528       // If dead space crosses the dense prefix boundary, it is (at least
1529       // partially) filled with a dummy object, marked live and added to the
1530       // summary data.  This simplifies the copy/update phase and must be done
1531       // before the final locations of objects are determined, to prevent
1532       // leaving a fragment of dead space that is too small to fill.
1533       fill_dense_prefix_end(id);
1534 
1535       // Compute the destination of each Region, and thus each object.
1536       _summary_data.summarize_dense_prefix(space->bottom(), dense_prefix_end);
1537       _summary_data.summarize(_space_info[id].split_info(),
1538                               dense_prefix_end, space->top(), nullptr,
1539                               dense_prefix_end, space->end(),
1540                               _space_info[id].new_top_addr());
1541     }
1542   }
1543 
1544   if (log_develop_is_enabled(Trace, gc, compaction)) {
1545     const size_t region_size = ParallelCompactData::RegionSize;
1546     HeapWord* const dense_prefix_end = _space_info[id].dense_prefix();
1547     const size_t dp_region = _summary_data.addr_to_region_idx(dense_prefix_end);
1548     const size_t dp_words = pointer_delta(dense_prefix_end, space->bottom());
1549     HeapWord* const new_top = _space_info[id].new_top();
1550     const HeapWord* nt_aligned_up = _summary_data.region_align_up(new_top);
1551     const size_t cr_words = pointer_delta(nt_aligned_up, dense_prefix_end);
1552     log_develop_trace(gc, compaction)(
1553         "id=%d cap=" SIZE_FORMAT " dp=" PTR_FORMAT " "
1554         "dp_region=" SIZE_FORMAT " " "dp_count=" SIZE_FORMAT " "
1555         "cr_count=" SIZE_FORMAT " " "nt=" PTR_FORMAT,
1556         id, space->capacity_in_words(), p2i(dense_prefix_end),
1557         dp_region, dp_words / region_size,
1558         cr_words / region_size, p2i(new_top));
1559   }
1560 }
1561 
1562 #ifndef PRODUCT
1563 void PSParallelCompact::summary_phase_msg(SpaceId dst_space_id,
1564                                           HeapWord* dst_beg, HeapWord* dst_end,
1565                                           SpaceId src_space_id,
1566                                           HeapWord* src_beg, HeapWord* src_end)
1567 {
1568   log_develop_trace(gc, compaction)(
1569       "Summarizing %d [%s] into %d [%s]:  "
1570       "src=" PTR_FORMAT "-" PTR_FORMAT " "
1571       SIZE_FORMAT "-" SIZE_FORMAT " "
1572       "dst=" PTR_FORMAT "-" PTR_FORMAT " "
1573       SIZE_FORMAT "-" SIZE_FORMAT,
1574       src_space_id, space_names[src_space_id],
1575       dst_space_id, space_names[dst_space_id],
1576       p2i(src_beg), p2i(src_end),
1577       _summary_data.addr_to_region_idx(src_beg),
1578       _summary_data.addr_to_region_idx(src_end),
1579       p2i(dst_beg), p2i(dst_end),
1580       _summary_data.addr_to_region_idx(dst_beg),
1581       _summary_data.addr_to_region_idx(dst_end));
1582 }
1583 #endif  // #ifndef PRODUCT
1584 
1585 void PSParallelCompact::summary_phase(bool maximum_compaction)
1586 {
1587   GCTraceTime(Info, gc, phases) tm("Summary Phase", &_gc_timer);
1588 
1589   // Quick summarization of each space into itself, to see how much is live.
1590   summarize_spaces_quick();
1591 
1592   log_develop_trace(gc, compaction)("summary phase:  after summarizing each space to self");
1593   NOT_PRODUCT(print_region_ranges());
1594   NOT_PRODUCT(print_initial_summary_data(_summary_data, _space_info));
1595 
1596   // The amount of live data that will end up in old space (assuming it fits).
1597   size_t old_space_total_live = 0;
1598   for (unsigned int id = old_space_id; id < last_space_id; ++id) {
1599     old_space_total_live += pointer_delta(_space_info[id].new_top(),
1600                                           _space_info[id].space()->bottom());
1601   }
1602 
1603   MutableSpace* const old_space = _space_info[old_space_id].space();
1604   const size_t old_capacity = old_space->capacity_in_words();
1605   if (old_space_total_live > old_capacity) {
1606     // XXX - should also try to expand
1607     maximum_compaction = true;
1608   }
1609 
1610   // Old generations.
1611   summarize_space(old_space_id, maximum_compaction);
1612 
1613   // Summarize the remaining spaces in the young gen.  The initial target space
1614   // is the old gen.  If a space does not fit entirely into the target, then the
1615   // remainder is compacted into the space itself and that space becomes the new
1616   // target.
1617   SpaceId dst_space_id = old_space_id;
1618   HeapWord* dst_space_end = old_space->end();
1619   HeapWord** new_top_addr = _space_info[dst_space_id].new_top_addr();
1620   for (unsigned int id = eden_space_id; id < last_space_id; ++id) {
1621     const MutableSpace* space = _space_info[id].space();
1622     const size_t live = pointer_delta(_space_info[id].new_top(),
1623                                       space->bottom());
1624     const size_t available = pointer_delta(dst_space_end, *new_top_addr);
1625 
1626     NOT_PRODUCT(summary_phase_msg(dst_space_id, *new_top_addr, dst_space_end,
1627                                   SpaceId(id), space->bottom(), space->top());)
1628     if (live > 0 && live <= available) {
1629       // All the live data will fit.
1630       bool done = _summary_data.summarize(_space_info[id].split_info(),
1631                                           space->bottom(), space->top(),
1632                                           nullptr,
1633                                           *new_top_addr, dst_space_end,
1634                                           new_top_addr);
1635       assert(done, "space must fit into old gen");
1636 
1637       // Reset the new_top value for the space.
1638       _space_info[id].set_new_top(space->bottom());
1639     } else if (live > 0) {
1640       // Attempt to fit part of the source space into the target space.
1641       HeapWord* next_src_addr = nullptr;
1642       bool done = _summary_data.summarize(_space_info[id].split_info(),
1643                                           space->bottom(), space->top(),
1644                                           &next_src_addr,
1645                                           *new_top_addr, dst_space_end,
1646                                           new_top_addr);
1647       assert(!done, "space should not fit into old gen");
1648       assert(next_src_addr != nullptr, "sanity");
1649 
1650       // The source space becomes the new target, so the remainder is compacted
1651       // within the space itself.
1652       dst_space_id = SpaceId(id);
1653       dst_space_end = space->end();
1654       new_top_addr = _space_info[id].new_top_addr();
1655       NOT_PRODUCT(summary_phase_msg(dst_space_id,
1656                                     space->bottom(), dst_space_end,
1657                                     SpaceId(id), next_src_addr, space->top());)
1658       done = _summary_data.summarize(_space_info[id].split_info(),
1659                                      next_src_addr, space->top(),
1660                                      nullptr,
1661                                      space->bottom(), dst_space_end,
1662                                      new_top_addr);
1663       assert(done, "space must fit when compacted into itself");
1664       assert(*new_top_addr <= space->top(), "usage should not grow");
1665     }
1666   }
1667 
1668   log_develop_trace(gc, compaction)("Summary_phase:  after final summarization");
1669   NOT_PRODUCT(print_region_ranges());
1670   NOT_PRODUCT(print_initial_summary_data(_summary_data, _space_info));
1671 }
1672 
1673 // This method should contain all heap-specific policy for invoking a full
1674 // collection.  invoke_no_policy() will only attempt to compact the heap; it
1675 // will do nothing further.  If we need to bail out for policy reasons, scavenge
1676 // before full gc, or any other specialized behavior, it needs to be added here.
1677 //
1678 // Note that this method should only be called from the vm_thread while at a
1679 // safepoint.
1680 //
1681 // Note that the all_soft_refs_clear flag in the soft ref policy
1682 // may be true because this method can be called without intervening
1683 // activity.  For example when the heap space is tight and full measure
1684 // are being taken to free space.
1685 bool PSParallelCompact::invoke(bool maximum_heap_compaction) {
1686   assert(SafepointSynchronize::is_at_safepoint(), "should be at safepoint");
1687   assert(Thread::current() == (Thread*)VMThread::vm_thread(),
1688          "should be in vm thread");
1689 
1690   ParallelScavengeHeap* heap = ParallelScavengeHeap::heap();
1691   assert(!heap->is_gc_active(), "not reentrant");
1692 
1693   IsGCActiveMark mark;
1694 
1695   if (ScavengeBeforeFullGC) {
1696     PSScavenge::invoke_no_policy();
1697   }
1698 
1699   const bool clear_all_soft_refs =
1700     heap->soft_ref_policy()->should_clear_all_soft_refs();
1701 
1702   return PSParallelCompact::invoke_no_policy(clear_all_soft_refs ||
1703                                              maximum_heap_compaction);
1704 }
1705 
1706 // This method contains no policy. You should probably
1707 // be calling invoke() instead.
1708 bool PSParallelCompact::invoke_no_policy(bool maximum_heap_compaction) {
1709   assert(SafepointSynchronize::is_at_safepoint(), "must be at a safepoint");
1710   assert(ref_processor() != nullptr, "Sanity");
1711 
1712   if (GCLocker::check_active_before_gc()) {
1713     return false;
1714   }
1715 
1716   ParallelScavengeHeap* heap = ParallelScavengeHeap::heap();
1717 
1718   GCIdMark gc_id_mark;
1719   _gc_timer.register_gc_start();
1720   _gc_tracer.report_gc_start(heap->gc_cause(), _gc_timer.gc_start());
1721 
1722   GCCause::Cause gc_cause = heap->gc_cause();
1723   PSYoungGen* young_gen = heap->young_gen();
1724   PSOldGen* old_gen = heap->old_gen();
1725   PSAdaptiveSizePolicy* size_policy = heap->size_policy();
1726 
1727   // The scope of casr should end after code that can change
1728   // SoftRefPolicy::_should_clear_all_soft_refs.
1729   ClearedAllSoftRefs casr(maximum_heap_compaction,
1730                           heap->soft_ref_policy());
1731 
1732   if (ZapUnusedHeapArea) {
1733     // Save information needed to minimize mangling
1734     heap->record_gen_tops_before_GC();
1735   }
1736 
1737   // Make sure data structures are sane, make the heap parsable, and do other
1738   // miscellaneous bookkeeping.
1739   pre_compact();
1740 
1741   const PreGenGCValues pre_gc_values = heap->get_pre_gc_values();
1742 
1743   {
1744     const uint active_workers =
1745       WorkerPolicy::calc_active_workers(ParallelScavengeHeap::heap()->workers().max_workers(),
1746                                         ParallelScavengeHeap::heap()->workers().active_workers(),
1747                                         Threads::number_of_non_daemon_threads());
1748     ParallelScavengeHeap::heap()->workers().set_active_workers(active_workers);
1749 
1750     GCTraceCPUTime tcpu(&_gc_tracer);
1751     GCTraceTime(Info, gc) tm("Pause Full", nullptr, gc_cause, true);
1752 
1753     heap->pre_full_gc_dump(&_gc_timer);
1754 
1755     TraceCollectorStats tcs(counters());
1756     TraceMemoryManagerStats tms(heap->old_gc_manager(), gc_cause, "end of major GC");
1757 
1758     if (log_is_enabled(Debug, gc, heap, exit)) {
1759       accumulated_time()->start();
1760     }
1761 
1762     // Let the size policy know we're starting
1763     size_policy->major_collection_begin();
1764 
1765 #if COMPILER2_OR_JVMCI
1766     DerivedPointerTable::clear();
1767 #endif
1768 
1769     ref_processor()->start_discovery(maximum_heap_compaction);
1770 
1771     ClassUnloadingContext ctx(1 /* num_nmethod_unlink_workers */,
1772                               false /* unregister_nmethods_during_purge */,
1773                               false /* lock_codeblob_free_separately */);
1774 
1775     marking_phase(&_gc_tracer);
1776 
1777     bool max_on_system_gc = UseMaximumCompactionOnSystemGC
1778       && GCCause::is_user_requested_gc(gc_cause);
1779     summary_phase(maximum_heap_compaction || max_on_system_gc);
1780 
1781 #if COMPILER2_OR_JVMCI
1782     assert(DerivedPointerTable::is_active(), "Sanity");
1783     DerivedPointerTable::set_active(false);
1784 #endif
1785 
1786     // adjust_roots() updates Universe::_intArrayKlassObj which is
1787     // needed by the compaction for filling holes in the dense prefix.
1788     adjust_roots();
1789 
1790     compact();
1791 
1792     ParCompactionManager::verify_all_region_stack_empty();
1793 
1794     // Reset the mark bitmap, summary data, and do other bookkeeping.  Must be
1795     // done before resizing.
1796     post_compact();
1797 
1798     // Let the size policy know we're done
1799     size_policy->major_collection_end(old_gen->used_in_bytes(), gc_cause);
1800 
1801     if (UseAdaptiveSizePolicy) {
1802       log_debug(gc, ergo)("AdaptiveSizeStart: collection: %d ", heap->total_collections());
1803       log_trace(gc, ergo)("old_gen_capacity: " SIZE_FORMAT " young_gen_capacity: " SIZE_FORMAT,
1804                           old_gen->capacity_in_bytes(), young_gen->capacity_in_bytes());
1805 
1806       // Don't check if the size_policy is ready here.  Let
1807       // the size_policy check that internally.
1808       if (UseAdaptiveGenerationSizePolicyAtMajorCollection &&
1809           AdaptiveSizePolicy::should_update_promo_stats(gc_cause)) {
1810         // Swap the survivor spaces if from_space is empty. The
1811         // resize_young_gen() called below is normally used after
1812         // a successful young GC and swapping of survivor spaces;
1813         // otherwise, it will fail to resize the young gen with
1814         // the current implementation.
1815         if (young_gen->from_space()->is_empty()) {
1816           young_gen->from_space()->clear(SpaceDecorator::Mangle);
1817           young_gen->swap_spaces();
1818         }
1819 
1820         // Calculate optimal free space amounts
1821         assert(young_gen->max_gen_size() >
1822           young_gen->from_space()->capacity_in_bytes() +
1823           young_gen->to_space()->capacity_in_bytes(),
1824           "Sizes of space in young gen are out-of-bounds");
1825 
1826         size_t young_live = young_gen->used_in_bytes();
1827         size_t eden_live = young_gen->eden_space()->used_in_bytes();
1828         size_t old_live = old_gen->used_in_bytes();
1829         size_t cur_eden = young_gen->eden_space()->capacity_in_bytes();
1830         size_t max_old_gen_size = old_gen->max_gen_size();
1831         size_t max_eden_size = young_gen->max_gen_size() -
1832           young_gen->from_space()->capacity_in_bytes() -
1833           young_gen->to_space()->capacity_in_bytes();
1834 
1835         // Used for diagnostics
1836         size_policy->clear_generation_free_space_flags();
1837 
1838         size_policy->compute_generations_free_space(young_live,
1839                                                     eden_live,
1840                                                     old_live,
1841                                                     cur_eden,
1842                                                     max_old_gen_size,
1843                                                     max_eden_size,
1844                                                     true /* full gc*/);
1845 
1846         size_policy->check_gc_overhead_limit(eden_live,
1847                                              max_old_gen_size,
1848                                              max_eden_size,
1849                                              true /* full gc*/,
1850                                              gc_cause,
1851                                              heap->soft_ref_policy());
1852 
1853         size_policy->decay_supplemental_growth(true /* full gc*/);
1854 
1855         heap->resize_old_gen(
1856           size_policy->calculated_old_free_size_in_bytes());
1857 
1858         heap->resize_young_gen(size_policy->calculated_eden_size_in_bytes(),
1859                                size_policy->calculated_survivor_size_in_bytes());
1860       }
1861 
1862       log_debug(gc, ergo)("AdaptiveSizeStop: collection: %d ", heap->total_collections());
1863     }
1864 
1865     if (UsePerfData) {
1866       PSGCAdaptivePolicyCounters* const counters = heap->gc_policy_counters();
1867       counters->update_counters();
1868       counters->update_old_capacity(old_gen->capacity_in_bytes());
1869       counters->update_young_capacity(young_gen->capacity_in_bytes());
1870     }
1871 
1872     heap->resize_all_tlabs();
1873 
1874     // Resize the metaspace capacity after a collection
1875     MetaspaceGC::compute_new_size();
1876 
1877     if (log_is_enabled(Debug, gc, heap, exit)) {
1878       accumulated_time()->stop();
1879     }
1880 
1881     heap->print_heap_change(pre_gc_values);
1882 
1883     // Track memory usage and detect low memory
1884     MemoryService::track_memory_usage();
1885     heap->update_counters();
1886 
1887     heap->post_full_gc_dump(&_gc_timer);
1888   }
1889 
1890   if (VerifyAfterGC && heap->total_collections() >= VerifyGCStartAt) {
1891     Universe::verify("After GC");
1892   }
1893 
1894   // Re-verify object start arrays
1895   if (VerifyObjectStartArray &&
1896       VerifyAfterGC) {
1897     old_gen->verify_object_start_array();
1898   }
1899 
1900   if (ZapUnusedHeapArea) {
1901     old_gen->object_space()->check_mangled_unused_area_complete();
1902   }
1903 
1904   heap->print_heap_after_gc();
1905   heap->trace_heap_after_gc(&_gc_tracer);
1906 
1907   AdaptiveSizePolicyOutput::print(size_policy, heap->total_collections());
1908 
1909   _gc_timer.register_gc_end();
1910 
1911   _gc_tracer.report_dense_prefix(dense_prefix(old_space_id));
1912   _gc_tracer.report_gc_end(_gc_timer.gc_end(), _gc_timer.time_partitions());
1913 
1914   return true;
1915 }
1916 
1917 class PCAddThreadRootsMarkingTaskClosure : public ThreadClosure {
1918 private:
1919   uint _worker_id;
1920 
1921 public:
1922   PCAddThreadRootsMarkingTaskClosure(uint worker_id) : _worker_id(worker_id) { }
1923   void do_thread(Thread* thread) {
1924     assert(ParallelScavengeHeap::heap()->is_gc_active(), "called outside gc");
1925 
1926     ResourceMark rm;
1927 
1928     ParCompactionManager* cm = ParCompactionManager::gc_thread_compaction_manager(_worker_id);
1929 
1930     PCMarkAndPushClosure mark_and_push_closure(cm);
1931     MarkingCodeBlobClosure mark_and_push_in_blobs(&mark_and_push_closure, !CodeBlobToOopClosure::FixRelocations, true /* keepalive nmethods */);
1932 
1933     thread->oops_do(&mark_and_push_closure, &mark_and_push_in_blobs);
1934 
1935     // Do the real work
1936     cm->follow_marking_stacks();
1937   }
1938 };
1939 
1940 void steal_marking_work(TaskTerminator& terminator, uint worker_id) {
1941   assert(ParallelScavengeHeap::heap()->is_gc_active(), "called outside gc");
1942 
1943   ParCompactionManager* cm =
1944     ParCompactionManager::gc_thread_compaction_manager(worker_id);
1945 
1946   do {
1947     oop obj = nullptr;
1948     ObjArrayTask task;
1949     if (ParCompactionManager::steal_objarray(worker_id,  task)) {
1950       cm->follow_array((objArrayOop)task.obj(), task.index());
1951     } else if (ParCompactionManager::steal(worker_id, obj)) {
1952       cm->follow_contents(obj);
1953     }
1954     cm->follow_marking_stacks();
1955   } while (!terminator.offer_termination());
1956 }
1957 
1958 class MarkFromRootsTask : public WorkerTask {
1959   StrongRootsScope _strong_roots_scope; // needed for Threads::possibly_parallel_threads_do
1960   OopStorageSetStrongParState<false /* concurrent */, false /* is_const */> _oop_storage_set_par_state;
1961   TaskTerminator _terminator;
1962   uint _active_workers;
1963 
1964 public:
1965   MarkFromRootsTask(uint active_workers) :
1966       WorkerTask("MarkFromRootsTask"),
1967       _strong_roots_scope(active_workers),
1968       _terminator(active_workers, ParCompactionManager::oop_task_queues()),
1969       _active_workers(active_workers) {}
1970 
1971   virtual void work(uint worker_id) {
1972     ParCompactionManager* cm = ParCompactionManager::gc_thread_compaction_manager(worker_id);
1973     PCMarkAndPushClosure mark_and_push_closure(cm);
1974 
1975     {
1976       CLDToOopClosure cld_closure(&mark_and_push_closure, ClassLoaderData::_claim_stw_fullgc_mark);
1977       ClassLoaderDataGraph::always_strong_cld_do(&cld_closure);
1978 
1979       // Do the real work
1980       cm->follow_marking_stacks();
1981     }
1982 
1983     PCAddThreadRootsMarkingTaskClosure closure(worker_id);
1984     Threads::possibly_parallel_threads_do(true /* is_par */, &closure);
1985 
1986     // Mark from OopStorages
1987     {
1988       _oop_storage_set_par_state.oops_do(&mark_and_push_closure);
1989       // Do the real work
1990       cm->follow_marking_stacks();
1991     }
1992 
1993     if (_active_workers > 1) {
1994       steal_marking_work(_terminator, worker_id);
1995     }
1996   }
1997 };
1998 
1999 class ParallelCompactRefProcProxyTask : public RefProcProxyTask {
2000   TaskTerminator _terminator;
2001 
2002 public:
2003   ParallelCompactRefProcProxyTask(uint max_workers)
2004     : RefProcProxyTask("ParallelCompactRefProcProxyTask", max_workers),
2005       _terminator(_max_workers, ParCompactionManager::oop_task_queues()) {}
2006 
2007   void work(uint worker_id) override {
2008     assert(worker_id < _max_workers, "sanity");
2009     ParCompactionManager* cm = (_tm == RefProcThreadModel::Single) ? ParCompactionManager::get_vmthread_cm() : ParCompactionManager::gc_thread_compaction_manager(worker_id);
2010     PCMarkAndPushClosure keep_alive(cm);
2011     BarrierEnqueueDiscoveredFieldClosure enqueue;
2012     ParCompactionManager::FollowStackClosure complete_gc(cm, (_tm == RefProcThreadModel::Single) ? nullptr : &_terminator, worker_id);
2013     _rp_task->rp_work(worker_id, PSParallelCompact::is_alive_closure(), &keep_alive, &enqueue, &complete_gc);
2014   }
2015 
2016   void prepare_run_task_hook() override {
2017     _terminator.reset_for_reuse(_queue_count);
2018   }
2019 };
2020 
2021 void PSParallelCompact::marking_phase(ParallelOldTracer *gc_tracer) {
2022   // Recursively traverse all live objects and mark them
2023   GCTraceTime(Info, gc, phases) tm("Marking Phase", &_gc_timer);
2024 
2025   uint active_gc_threads = ParallelScavengeHeap::heap()->workers().active_workers();
2026 
2027   ClassLoaderDataGraph::verify_claimed_marks_cleared(ClassLoaderData::_claim_stw_fullgc_mark);
2028   {
2029     GCTraceTime(Debug, gc, phases) tm("Par Mark", &_gc_timer);
2030 
2031     MarkFromRootsTask task(active_gc_threads);
2032     ParallelScavengeHeap::heap()->workers().run_task(&task);
2033   }
2034 
2035   // Process reference objects found during marking
2036   {
2037     GCTraceTime(Debug, gc, phases) tm("Reference Processing", &_gc_timer);
2038 
2039     ReferenceProcessorStats stats;
2040     ReferenceProcessorPhaseTimes pt(&_gc_timer, ref_processor()->max_num_queues());
2041 
2042     ref_processor()->set_active_mt_degree(active_gc_threads);
2043     ParallelCompactRefProcProxyTask task(ref_processor()->max_num_queues());
2044     stats = ref_processor()->process_discovered_references(task, pt);
2045 
2046     gc_tracer->report_gc_reference_stats(stats);
2047     pt.print_all_references();
2048   }
2049 
2050   // This is the point where the entire marking should have completed.
2051   ParCompactionManager::verify_all_marking_stack_empty();
2052 
2053   {
2054     GCTraceTime(Debug, gc, phases) tm("Weak Processing", &_gc_timer);
2055     WeakProcessor::weak_oops_do(&ParallelScavengeHeap::heap()->workers(),
2056                                 is_alive_closure(),
2057                                 &do_nothing_cl,
2058                                 1);
2059   }
2060 
2061   {
2062     GCTraceTime(Debug, gc, phases) tm_m("Class Unloading", &_gc_timer);
2063 
2064     ClassUnloadingContext* ctx = ClassUnloadingContext::context();
2065 
2066     bool unloading_occurred;
2067     {
2068       CodeCache::UnlinkingScope scope(is_alive_closure());
2069 
2070       // Follow system dictionary roots and unload classes.
2071       unloading_occurred = SystemDictionary::do_unloading(&_gc_timer);
2072 
2073       // Unload nmethods.
2074       CodeCache::do_unloading(unloading_occurred);
2075     }
2076 
2077     {
2078       GCTraceTime(Debug, gc, phases) t("Purge Unlinked NMethods", gc_timer());
2079       // Release unloaded nmethod's memory.
2080       ctx->purge_nmethods();
2081     }
2082     {
2083       GCTraceTime(Debug, gc, phases) ur("Unregister NMethods", &_gc_timer);
2084       ParallelScavengeHeap::heap()->prune_unlinked_nmethods();
2085     }
2086     {
2087       GCTraceTime(Debug, gc, phases) t("Free Code Blobs", gc_timer());
2088       ctx->free_code_blobs();
2089     }
2090 
2091     // Prune dead klasses from subklass/sibling/implementor lists.
2092     Klass::clean_weak_klass_links(unloading_occurred);
2093 
2094     // Clean JVMCI metadata handles.
2095     JVMCI_ONLY(JVMCI::do_unloading(unloading_occurred));
2096   }
2097 
2098   {
2099     GCTraceTime(Debug, gc, phases) tm("Report Object Count", &_gc_timer);
2100     _gc_tracer.report_object_count_after_gc(is_alive_closure(), &ParallelScavengeHeap::heap()->workers());
2101   }
2102 #if TASKQUEUE_STATS
2103   ParCompactionManager::oop_task_queues()->print_and_reset_taskqueue_stats("Oop Queue");
2104   ParCompactionManager::_objarray_task_queues->print_and_reset_taskqueue_stats("ObjArrayOop Queue");
2105 #endif
2106 }
2107 
2108 class PSAdjustTask final : public WorkerTask {
2109   SubTasksDone                               _sub_tasks;
2110   WeakProcessor::Task                        _weak_proc_task;
2111   OopStorageSetStrongParState<false, false>  _oop_storage_iter;
2112   uint                                       _nworkers;
2113 
2114   enum PSAdjustSubTask {
2115     PSAdjustSubTask_code_cache,
2116 
2117     PSAdjustSubTask_num_elements
2118   };
2119 
2120 public:
2121   PSAdjustTask(uint nworkers) :
2122     WorkerTask("PSAdjust task"),
2123     _sub_tasks(PSAdjustSubTask_num_elements),
2124     _weak_proc_task(nworkers),
2125     _nworkers(nworkers) {
2126 
2127     ClassLoaderDataGraph::verify_claimed_marks_cleared(ClassLoaderData::_claim_stw_fullgc_adjust);
2128     if (nworkers > 1) {
2129       Threads::change_thread_claim_token();
2130     }
2131   }
2132 
2133   ~PSAdjustTask() {
2134     Threads::assert_all_threads_claimed();
2135   }
2136 
2137   void work(uint worker_id) {
2138     ParCompactionManager* cm = ParCompactionManager::gc_thread_compaction_manager(worker_id);
2139     PCAdjustPointerClosure adjust(cm);
2140     {
2141       ResourceMark rm;
2142       Threads::possibly_parallel_oops_do(_nworkers > 1, &adjust, nullptr);
2143     }
2144     _oop_storage_iter.oops_do(&adjust);
2145     {
2146       CLDToOopClosure cld_closure(&adjust, ClassLoaderData::_claim_stw_fullgc_adjust);
2147       ClassLoaderDataGraph::cld_do(&cld_closure);
2148     }
2149     {
2150       AlwaysTrueClosure always_alive;
2151       _weak_proc_task.work(worker_id, &always_alive, &adjust);
2152     }
2153     if (_sub_tasks.try_claim_task(PSAdjustSubTask_code_cache)) {
2154       CodeBlobToOopClosure adjust_code(&adjust, CodeBlobToOopClosure::FixRelocations);
2155       CodeCache::blobs_do(&adjust_code);
2156     }
2157     _sub_tasks.all_tasks_claimed();
2158   }
2159 };
2160 
2161 void PSParallelCompact::adjust_roots() {
2162   // Adjust the pointers to reflect the new locations
2163   GCTraceTime(Info, gc, phases) tm("Adjust Roots", &_gc_timer);
2164   uint nworkers = ParallelScavengeHeap::heap()->workers().active_workers();
2165   PSAdjustTask task(nworkers);
2166   ParallelScavengeHeap::heap()->workers().run_task(&task);
2167 }
2168 
2169 // Helper class to print 8 region numbers per line and then print the total at the end.
2170 class FillableRegionLogger : public StackObj {
2171 private:
2172   Log(gc, compaction) log;
2173   static const int LineLength = 8;
2174   size_t _regions[LineLength];
2175   int _next_index;
2176   bool _enabled;
2177   size_t _total_regions;
2178 public:
2179   FillableRegionLogger() : _next_index(0), _enabled(log_develop_is_enabled(Trace, gc, compaction)), _total_regions(0) { }
2180   ~FillableRegionLogger() {
2181     log.trace(SIZE_FORMAT " initially fillable regions", _total_regions);
2182   }
2183 
2184   void print_line() {
2185     if (!_enabled || _next_index == 0) {
2186       return;
2187     }
2188     FormatBuffer<> line("Fillable: ");
2189     for (int i = 0; i < _next_index; i++) {
2190       line.append(" " SIZE_FORMAT_W(7), _regions[i]);
2191     }
2192     log.trace("%s", line.buffer());
2193     _next_index = 0;
2194   }
2195 
2196   void handle(size_t region) {
2197     if (!_enabled) {
2198       return;
2199     }
2200     _regions[_next_index++] = region;
2201     if (_next_index == LineLength) {
2202       print_line();
2203     }
2204     _total_regions++;
2205   }
2206 };
2207 
2208 void PSParallelCompact::prepare_region_draining_tasks(uint parallel_gc_threads)
2209 {
2210   GCTraceTime(Trace, gc, phases) tm("Drain Task Setup", &_gc_timer);
2211 
2212   // Find the threads that are active
2213   uint worker_id = 0;
2214 
2215   // Find all regions that are available (can be filled immediately) and
2216   // distribute them to the thread stacks.  The iteration is done in reverse
2217   // order (high to low) so the regions will be removed in ascending order.
2218 
2219   const ParallelCompactData& sd = PSParallelCompact::summary_data();
2220 
2221   // id + 1 is used to test termination so unsigned  can
2222   // be used with an old_space_id == 0.
2223   FillableRegionLogger region_logger;
2224   for (unsigned int id = to_space_id; id + 1 > old_space_id; --id) {
2225     SpaceInfo* const space_info = _space_info + id;
2226     HeapWord* const new_top = space_info->new_top();
2227 
2228     const size_t beg_region = sd.addr_to_region_idx(space_info->dense_prefix());
2229     const size_t end_region =
2230       sd.addr_to_region_idx(sd.region_align_up(new_top));
2231 
2232     for (size_t cur = end_region - 1; cur + 1 > beg_region; --cur) {
2233       if (sd.region(cur)->claim_unsafe()) {
2234         ParCompactionManager* cm = ParCompactionManager::gc_thread_compaction_manager(worker_id);
2235         bool result = sd.region(cur)->mark_normal();
2236         assert(result, "Must succeed at this point.");
2237         cm->region_stack()->push(cur);
2238         region_logger.handle(cur);
2239         // Assign regions to tasks in round-robin fashion.
2240         if (++worker_id == parallel_gc_threads) {
2241           worker_id = 0;
2242         }
2243       }
2244     }
2245     region_logger.print_line();
2246   }
2247 }
2248 
2249 class TaskQueue : StackObj {
2250   volatile uint _counter;
2251   uint _size;
2252   uint _insert_index;
2253   PSParallelCompact::UpdateDensePrefixTask* _backing_array;
2254 public:
2255   explicit TaskQueue(uint size) : _counter(0), _size(size), _insert_index(0), _backing_array(nullptr) {
2256     _backing_array = NEW_C_HEAP_ARRAY(PSParallelCompact::UpdateDensePrefixTask, _size, mtGC);
2257   }
2258   ~TaskQueue() {
2259     assert(_counter >= _insert_index, "not all queue elements were claimed");
2260     FREE_C_HEAP_ARRAY(T, _backing_array);
2261   }
2262 
2263   void push(const PSParallelCompact::UpdateDensePrefixTask& value) {
2264     assert(_insert_index < _size, "too small backing array");
2265     _backing_array[_insert_index++] = value;
2266   }
2267 
2268   bool try_claim(PSParallelCompact::UpdateDensePrefixTask& reference) {
2269     uint claimed = Atomic::fetch_then_add(&_counter, 1u);
2270     if (claimed < _insert_index) {
2271       reference = _backing_array[claimed];
2272       return true;
2273     } else {
2274       return false;
2275     }
2276   }
2277 };
2278 
2279 #define PAR_OLD_DENSE_PREFIX_OVER_PARTITIONING 4
2280 
2281 void PSParallelCompact::enqueue_dense_prefix_tasks(TaskQueue& task_queue,
2282                                                    uint parallel_gc_threads) {
2283   GCTraceTime(Trace, gc, phases) tm("Dense Prefix Task Setup", &_gc_timer);
2284 
2285   ParallelCompactData& sd = PSParallelCompact::summary_data();
2286 
2287   // Iterate over all the spaces adding tasks for updating
2288   // regions in the dense prefix.  Assume that 1 gc thread
2289   // will work on opening the gaps and the remaining gc threads
2290   // will work on the dense prefix.
2291   unsigned int space_id;
2292   for (space_id = old_space_id; space_id < last_space_id; ++ space_id) {
2293     HeapWord* const dense_prefix_end = _space_info[space_id].dense_prefix();
2294     const MutableSpace* const space = _space_info[space_id].space();
2295 
2296     if (dense_prefix_end == space->bottom()) {
2297       // There is no dense prefix for this space.
2298       continue;
2299     }
2300 
2301     // The dense prefix is before this region.
2302     size_t region_index_end_dense_prefix =
2303         sd.addr_to_region_idx(dense_prefix_end);
2304     RegionData* const dense_prefix_cp =
2305       sd.region(region_index_end_dense_prefix);
2306     assert(dense_prefix_end == space->end() ||
2307            dense_prefix_cp->available() ||
2308            dense_prefix_cp->claimed(),
2309            "The region after the dense prefix should always be ready to fill");
2310 
2311     size_t region_index_start = sd.addr_to_region_idx(space->bottom());
2312 
2313     // Is there dense prefix work?
2314     size_t total_dense_prefix_regions =
2315       region_index_end_dense_prefix - region_index_start;
2316     // How many regions of the dense prefix should be given to
2317     // each thread?
2318     if (total_dense_prefix_regions > 0) {
2319       uint tasks_for_dense_prefix = 1;
2320       if (total_dense_prefix_regions <=
2321           (parallel_gc_threads * PAR_OLD_DENSE_PREFIX_OVER_PARTITIONING)) {
2322         // Don't over partition.  This assumes that
2323         // PAR_OLD_DENSE_PREFIX_OVER_PARTITIONING is a small integer value
2324         // so there are not many regions to process.
2325         tasks_for_dense_prefix = parallel_gc_threads;
2326       } else {
2327         // Over partition
2328         tasks_for_dense_prefix = parallel_gc_threads *
2329           PAR_OLD_DENSE_PREFIX_OVER_PARTITIONING;
2330       }
2331       size_t regions_per_thread = total_dense_prefix_regions /
2332         tasks_for_dense_prefix;
2333       // Give each thread at least 1 region.
2334       if (regions_per_thread == 0) {
2335         regions_per_thread = 1;
2336       }
2337 
2338       for (uint k = 0; k < tasks_for_dense_prefix; k++) {
2339         if (region_index_start >= region_index_end_dense_prefix) {
2340           break;
2341         }
2342         // region_index_end is not processed
2343         size_t region_index_end = MIN2(region_index_start + regions_per_thread,
2344                                        region_index_end_dense_prefix);
2345         task_queue.push(UpdateDensePrefixTask(SpaceId(space_id),
2346                                               region_index_start,
2347                                               region_index_end));
2348         region_index_start = region_index_end;
2349       }
2350     }
2351     // This gets any part of the dense prefix that did not
2352     // fit evenly.
2353     if (region_index_start < region_index_end_dense_prefix) {
2354       task_queue.push(UpdateDensePrefixTask(SpaceId(space_id),
2355                                             region_index_start,
2356                                             region_index_end_dense_prefix));
2357     }
2358   }
2359 }
2360 
2361 #ifdef ASSERT
2362 // Write a histogram of the number of times the block table was filled for a
2363 // region.
2364 void PSParallelCompact::write_block_fill_histogram()
2365 {
2366   if (!log_develop_is_enabled(Trace, gc, compaction)) {
2367     return;
2368   }
2369 
2370   Log(gc, compaction) log;
2371   ResourceMark rm;
2372   LogStream ls(log.trace());
2373   outputStream* out = &ls;
2374 
2375   typedef ParallelCompactData::RegionData rd_t;
2376   ParallelCompactData& sd = summary_data();
2377 
2378   for (unsigned int id = old_space_id; id < last_space_id; ++id) {
2379     MutableSpace* const spc = _space_info[id].space();
2380     if (spc->bottom() != spc->top()) {
2381       const rd_t* const beg = sd.addr_to_region_ptr(spc->bottom());
2382       HeapWord* const top_aligned_up = sd.region_align_up(spc->top());
2383       const rd_t* const end = sd.addr_to_region_ptr(top_aligned_up);
2384 
2385       size_t histo[5] = { 0, 0, 0, 0, 0 };
2386       const size_t histo_len = sizeof(histo) / sizeof(size_t);
2387       const size_t region_cnt = pointer_delta(end, beg, sizeof(rd_t));
2388 
2389       for (const rd_t* cur = beg; cur < end; ++cur) {
2390         ++histo[MIN2(cur->blocks_filled_count(), histo_len - 1)];
2391       }
2392       out->print("Block fill histogram: %u %-4s" SIZE_FORMAT_W(5), id, space_names[id], region_cnt);
2393       for (size_t i = 0; i < histo_len; ++i) {
2394         out->print(" " SIZE_FORMAT_W(5) " %5.1f%%",
2395                    histo[i], 100.0 * histo[i] / region_cnt);
2396       }
2397       out->cr();
2398     }
2399   }
2400 }
2401 #endif // #ifdef ASSERT
2402 
2403 static void compaction_with_stealing_work(TaskTerminator* terminator, uint worker_id) {
2404   assert(ParallelScavengeHeap::heap()->is_gc_active(), "called outside gc");
2405 
2406   ParCompactionManager* cm =
2407     ParCompactionManager::gc_thread_compaction_manager(worker_id);
2408 
2409   // Drain the stacks that have been preloaded with regions
2410   // that are ready to fill.
2411 
2412   cm->drain_region_stacks();
2413 
2414   guarantee(cm->region_stack()->is_empty(), "Not empty");
2415 
2416   size_t region_index = 0;
2417 
2418   while (true) {
2419     if (ParCompactionManager::steal(worker_id, region_index)) {
2420       PSParallelCompact::fill_and_update_region(cm, region_index);
2421       cm->drain_region_stacks();
2422     } else if (PSParallelCompact::steal_unavailable_region(cm, region_index)) {
2423       // Fill and update an unavailable region with the help of a shadow region
2424       PSParallelCompact::fill_and_update_shadow_region(cm, region_index);
2425       cm->drain_region_stacks();
2426     } else {
2427       if (terminator->offer_termination()) {
2428         break;
2429       }
2430       // Go around again.
2431     }
2432   }
2433 }
2434 
2435 class UpdateDensePrefixAndCompactionTask: public WorkerTask {
2436   TaskQueue& _tq;
2437   TaskTerminator _terminator;
2438 
2439 public:
2440   UpdateDensePrefixAndCompactionTask(TaskQueue& tq, uint active_workers) :
2441       WorkerTask("UpdateDensePrefixAndCompactionTask"),
2442       _tq(tq),
2443       _terminator(active_workers, ParCompactionManager::region_task_queues()) {
2444   }
2445   virtual void work(uint worker_id) {
2446     ParCompactionManager* cm = ParCompactionManager::gc_thread_compaction_manager(worker_id);
2447 
2448     for (PSParallelCompact::UpdateDensePrefixTask task; _tq.try_claim(task); /* empty */) {
2449       PSParallelCompact::update_and_deadwood_in_dense_prefix(cm,
2450                                                              task._space_id,
2451                                                              task._region_index_start,
2452                                                              task._region_index_end);
2453     }
2454 
2455     // Once a thread has drained it's stack, it should try to steal regions from
2456     // other threads.
2457     compaction_with_stealing_work(&_terminator, worker_id);
2458 
2459     // At this point all regions have been compacted, so it's now safe
2460     // to update the deferred objects that cross region boundaries.
2461     cm->drain_deferred_objects();
2462   }
2463 };
2464 
2465 void PSParallelCompact::compact() {
2466   GCTraceTime(Info, gc, phases) tm("Compaction Phase", &_gc_timer);
2467 
2468   ParallelScavengeHeap* heap = ParallelScavengeHeap::heap();
2469   PSOldGen* old_gen = heap->old_gen();
2470   uint active_gc_threads = ParallelScavengeHeap::heap()->workers().active_workers();
2471 
2472   // for [0..last_space_id)
2473   //     for [0..active_gc_threads * PAR_OLD_DENSE_PREFIX_OVER_PARTITIONING)
2474   //         push
2475   //     push
2476   //
2477   // max push count is thus: last_space_id * (active_gc_threads * PAR_OLD_DENSE_PREFIX_OVER_PARTITIONING + 1)
2478   TaskQueue task_queue(last_space_id * (active_gc_threads * PAR_OLD_DENSE_PREFIX_OVER_PARTITIONING + 1));
2479   initialize_shadow_regions(active_gc_threads);
2480   prepare_region_draining_tasks(active_gc_threads);
2481   enqueue_dense_prefix_tasks(task_queue, active_gc_threads);
2482 
2483   {
2484     GCTraceTime(Trace, gc, phases) tm("Par Compact", &_gc_timer);
2485 
2486     UpdateDensePrefixAndCompactionTask task(task_queue, active_gc_threads);
2487     ParallelScavengeHeap::heap()->workers().run_task(&task);
2488 
2489 #ifdef  ASSERT
2490     // Verify that all regions have been processed.
2491     for (unsigned int id = old_space_id; id < last_space_id; ++id) {
2492       verify_complete(SpaceId(id));
2493     }
2494 #endif
2495   }
2496 
2497   DEBUG_ONLY(write_block_fill_histogram());
2498 }
2499 
2500 #ifdef  ASSERT
2501 void PSParallelCompact::verify_complete(SpaceId space_id) {
2502   // All Regions between space bottom() to new_top() should be marked as filled
2503   // and all Regions between new_top() and top() should be available (i.e.,
2504   // should have been emptied).
2505   ParallelCompactData& sd = summary_data();
2506   SpaceInfo si = _space_info[space_id];
2507   HeapWord* new_top_addr = sd.region_align_up(si.new_top());
2508   HeapWord* old_top_addr = sd.region_align_up(si.space()->top());
2509   const size_t beg_region = sd.addr_to_region_idx(si.space()->bottom());
2510   const size_t new_top_region = sd.addr_to_region_idx(new_top_addr);
2511   const size_t old_top_region = sd.addr_to_region_idx(old_top_addr);
2512 
2513   bool issued_a_warning = false;
2514 
2515   size_t cur_region;
2516   for (cur_region = beg_region; cur_region < new_top_region; ++cur_region) {
2517     const RegionData* const c = sd.region(cur_region);
2518     if (!c->completed()) {
2519       log_warning(gc)("region " SIZE_FORMAT " not filled: destination_count=%u",
2520                       cur_region, c->destination_count());
2521       issued_a_warning = true;
2522     }
2523   }
2524 
2525   for (cur_region = new_top_region; cur_region < old_top_region; ++cur_region) {
2526     const RegionData* const c = sd.region(cur_region);
2527     if (!c->available()) {
2528       log_warning(gc)("region " SIZE_FORMAT " not empty: destination_count=%u",
2529                       cur_region, c->destination_count());
2530       issued_a_warning = true;
2531     }
2532   }
2533 
2534   if (issued_a_warning) {
2535     print_region_ranges();
2536   }
2537 }
2538 #endif  // #ifdef ASSERT
2539 
2540 inline void UpdateOnlyClosure::do_addr(HeapWord* addr) {
2541   _start_array->update_for_block(addr, addr + cast_to_oop(addr)->size());
2542   compaction_manager()->update_contents(cast_to_oop(addr));
2543 }
2544 
2545 // Update interior oops in the ranges of regions [beg_region, end_region).
2546 void
2547 PSParallelCompact::update_and_deadwood_in_dense_prefix(ParCompactionManager* cm,
2548                                                        SpaceId space_id,
2549                                                        size_t beg_region,
2550                                                        size_t end_region) {
2551   ParallelCompactData& sd = summary_data();
2552   ParMarkBitMap* const mbm = mark_bitmap();
2553 
2554   HeapWord* beg_addr = sd.region_to_addr(beg_region);
2555   HeapWord* const end_addr = sd.region_to_addr(end_region);
2556   assert(beg_region <= end_region, "bad region range");
2557   assert(end_addr <= dense_prefix(space_id), "not in the dense prefix");
2558 
2559 #ifdef  ASSERT
2560   // Claim the regions to avoid triggering an assert when they are marked as
2561   // filled.
2562   for (size_t claim_region = beg_region; claim_region < end_region; ++claim_region) {
2563     assert(sd.region(claim_region)->claim_unsafe(), "claim() failed");
2564   }
2565 #endif  // #ifdef ASSERT
2566 
2567   if (beg_addr != space(space_id)->bottom()) {
2568     // Find the first live object or block of dead space that *starts* in this
2569     // range of regions.  If a partial object crosses onto the region, skip it;
2570     // it will be marked for 'deferred update' when the object head is
2571     // processed.  If dead space crosses onto the region, it is also skipped; it
2572     // will be filled when the prior region is processed.  If neither of those
2573     // apply, the first word in the region is the start of a live object or dead
2574     // space.
2575     assert(beg_addr > space(space_id)->bottom(), "sanity");
2576     const RegionData* const cp = sd.region(beg_region);
2577     if (cp->partial_obj_size() != 0) {
2578       beg_addr = sd.partial_obj_end(beg_region);
2579     } else if (dead_space_crosses_boundary(cp, mbm->addr_to_bit(beg_addr))) {
2580       beg_addr = mbm->find_obj_beg(beg_addr, end_addr);
2581     }
2582   }
2583 
2584   if (beg_addr < end_addr) {
2585     // A live object or block of dead space starts in this range of Regions.
2586      HeapWord* const dense_prefix_end = dense_prefix(space_id);
2587 
2588     // Create closures and iterate.
2589     UpdateOnlyClosure update_closure(mbm, cm, space_id);
2590     FillClosure fill_closure(cm, space_id);
2591     ParMarkBitMap::IterationStatus status;
2592     status = mbm->iterate(&update_closure, &fill_closure, beg_addr, end_addr,
2593                           dense_prefix_end);
2594     if (status == ParMarkBitMap::incomplete) {
2595       update_closure.do_addr(update_closure.source());
2596     }
2597   }
2598 
2599   // Mark the regions as filled.
2600   RegionData* const beg_cp = sd.region(beg_region);
2601   RegionData* const end_cp = sd.region(end_region);
2602   for (RegionData* cp = beg_cp; cp < end_cp; ++cp) {
2603     cp->set_completed();
2604   }
2605 }
2606 
2607 // Return the SpaceId for the space containing addr.  If addr is not in the
2608 // heap, last_space_id is returned.  In debug mode it expects the address to be
2609 // in the heap and asserts such.
2610 PSParallelCompact::SpaceId PSParallelCompact::space_id(HeapWord* addr) {
2611   assert(ParallelScavengeHeap::heap()->is_in_reserved(addr), "addr not in the heap");
2612 
2613   for (unsigned int id = old_space_id; id < last_space_id; ++id) {
2614     if (_space_info[id].space()->contains(addr)) {
2615       return SpaceId(id);
2616     }
2617   }
2618 
2619   assert(false, "no space contains the addr");
2620   return last_space_id;
2621 }
2622 
2623 void PSParallelCompact::update_deferred_object(ParCompactionManager* cm, HeapWord *addr) {
2624 #ifdef ASSERT
2625   ParallelCompactData& sd = summary_data();
2626   size_t region_idx = sd.addr_to_region_idx(addr);
2627   assert(sd.region(region_idx)->completed(), "first region must be completed before deferred updates");
2628   assert(sd.region(region_idx + 1)->completed(), "second region must be completed before deferred updates");
2629 #endif
2630 
2631   const SpaceInfo* const space_info = _space_info + space_id(addr);
2632   ObjectStartArray* const start_array = space_info->start_array();
2633   if (start_array != nullptr) {
2634     start_array->update_for_block(addr, addr + cast_to_oop(addr)->size());
2635   }
2636 
2637   cm->update_contents(cast_to_oop(addr));
2638   assert(oopDesc::is_oop(cast_to_oop(addr)), "Expected an oop at " PTR_FORMAT, p2i(cast_to_oop(addr)));
2639 }
2640 
2641 // Skip over count live words starting from beg, and return the address of the
2642 // next live word.  Unless marked, the word corresponding to beg is assumed to
2643 // be dead.  Callers must either ensure beg does not correspond to the middle of
2644 // an object, or account for those live words in some other way.  Callers must
2645 // also ensure that there are enough live words in the range [beg, end) to skip.
2646 HeapWord*
2647 PSParallelCompact::skip_live_words(HeapWord* beg, HeapWord* end, size_t count)
2648 {
2649   assert(count > 0, "sanity");
2650 
2651   ParMarkBitMap* m = mark_bitmap();
2652   idx_t bits_to_skip = m->words_to_bits(count);
2653   idx_t cur_beg = m->addr_to_bit(beg);
2654   const idx_t search_end = m->align_range_end(m->addr_to_bit(end));
2655 
2656   do {
2657     cur_beg = m->find_obj_beg(cur_beg, search_end);
2658     idx_t cur_end = m->find_obj_end(cur_beg, search_end);
2659     const size_t obj_bits = cur_end - cur_beg + 1;
2660     if (obj_bits > bits_to_skip) {
2661       return m->bit_to_addr(cur_beg + bits_to_skip);
2662     }
2663     bits_to_skip -= obj_bits;
2664     cur_beg = cur_end + 1;
2665   } while (bits_to_skip > 0);
2666 
2667   // Skipping the desired number of words landed just past the end of an object.
2668   // Find the start of the next object.
2669   cur_beg = m->find_obj_beg(cur_beg, search_end);
2670   assert(cur_beg < m->addr_to_bit(end), "not enough live words to skip");
2671   return m->bit_to_addr(cur_beg);
2672 }
2673 
2674 HeapWord* PSParallelCompact::first_src_addr(HeapWord* const dest_addr,
2675                                             SpaceId src_space_id,
2676                                             size_t src_region_idx)
2677 {
2678   assert(summary_data().is_region_aligned(dest_addr), "not aligned");
2679 
2680   const SplitInfo& split_info = _space_info[src_space_id].split_info();
2681   if (split_info.dest_region_addr() == dest_addr) {
2682     // The partial object ending at the split point contains the first word to
2683     // be copied to dest_addr.
2684     return split_info.first_src_addr();
2685   }
2686 
2687   const ParallelCompactData& sd = summary_data();
2688   ParMarkBitMap* const bitmap = mark_bitmap();
2689   const size_t RegionSize = ParallelCompactData::RegionSize;
2690 
2691   assert(sd.is_region_aligned(dest_addr), "not aligned");
2692   const RegionData* const src_region_ptr = sd.region(src_region_idx);
2693   const size_t partial_obj_size = src_region_ptr->partial_obj_size();
2694   HeapWord* const src_region_destination = src_region_ptr->destination();
2695 
2696   assert(dest_addr >= src_region_destination, "wrong src region");
2697   assert(src_region_ptr->data_size() > 0, "src region cannot be empty");
2698 
2699   HeapWord* const src_region_beg = sd.region_to_addr(src_region_idx);
2700   HeapWord* const src_region_end = src_region_beg + RegionSize;
2701 
2702   HeapWord* addr = src_region_beg;
2703   if (dest_addr == src_region_destination) {
2704     // Return the first live word in the source region.
2705     if (partial_obj_size == 0) {
2706       addr = bitmap->find_obj_beg(addr, src_region_end);
2707       assert(addr < src_region_end, "no objects start in src region");
2708     }
2709     return addr;
2710   }
2711 
2712   // Must skip some live data.
2713   size_t words_to_skip = dest_addr - src_region_destination;
2714   assert(src_region_ptr->data_size() > words_to_skip, "wrong src region");
2715 
2716   if (partial_obj_size >= words_to_skip) {
2717     // All the live words to skip are part of the partial object.
2718     addr += words_to_skip;
2719     if (partial_obj_size == words_to_skip) {
2720       // Find the first live word past the partial object.
2721       addr = bitmap->find_obj_beg(addr, src_region_end);
2722       assert(addr < src_region_end, "wrong src region");
2723     }
2724     return addr;
2725   }
2726 
2727   // Skip over the partial object (if any).
2728   if (partial_obj_size != 0) {
2729     words_to_skip -= partial_obj_size;
2730     addr += partial_obj_size;
2731   }
2732 
2733   // Skip over live words due to objects that start in the region.
2734   addr = skip_live_words(addr, src_region_end, words_to_skip);
2735   assert(addr < src_region_end, "wrong src region");
2736   return addr;
2737 }
2738 
2739 void PSParallelCompact::decrement_destination_counts(ParCompactionManager* cm,
2740                                                      SpaceId src_space_id,
2741                                                      size_t beg_region,
2742                                                      HeapWord* end_addr)
2743 {
2744   ParallelCompactData& sd = summary_data();
2745 
2746 #ifdef ASSERT
2747   MutableSpace* const src_space = _space_info[src_space_id].space();
2748   HeapWord* const beg_addr = sd.region_to_addr(beg_region);
2749   assert(src_space->contains(beg_addr) || beg_addr == src_space->end(),
2750          "src_space_id does not match beg_addr");
2751   assert(src_space->contains(end_addr) || end_addr == src_space->end(),
2752          "src_space_id does not match end_addr");
2753 #endif // #ifdef ASSERT
2754 
2755   RegionData* const beg = sd.region(beg_region);
2756   RegionData* const end = sd.addr_to_region_ptr(sd.region_align_up(end_addr));
2757 
2758   // Regions up to new_top() are enqueued if they become available.
2759   HeapWord* const new_top = _space_info[src_space_id].new_top();
2760   RegionData* const enqueue_end =
2761     sd.addr_to_region_ptr(sd.region_align_up(new_top));
2762 
2763   for (RegionData* cur = beg; cur < end; ++cur) {
2764     assert(cur->data_size() > 0, "region must have live data");
2765     cur->decrement_destination_count();
2766     if (cur < enqueue_end && cur->available() && cur->claim()) {
2767       if (cur->mark_normal()) {
2768         cm->push_region(sd.region(cur));
2769       } else if (cur->mark_copied()) {
2770         // Try to copy the content of the shadow region back to its corresponding
2771         // heap region if the shadow region is filled. Otherwise, the GC thread
2772         // fills the shadow region will copy the data back (see
2773         // MoveAndUpdateShadowClosure::complete_region).
2774         copy_back(sd.region_to_addr(cur->shadow_region()), sd.region_to_addr(cur));
2775         ParCompactionManager::push_shadow_region_mt_safe(cur->shadow_region());
2776         cur->set_completed();
2777       }
2778     }
2779   }
2780 }
2781 
2782 size_t PSParallelCompact::next_src_region(MoveAndUpdateClosure& closure,
2783                                           SpaceId& src_space_id,
2784                                           HeapWord*& src_space_top,
2785                                           HeapWord* end_addr)
2786 {
2787   typedef ParallelCompactData::RegionData RegionData;
2788 
2789   ParallelCompactData& sd = PSParallelCompact::summary_data();
2790   const size_t region_size = ParallelCompactData::RegionSize;
2791 
2792   size_t src_region_idx = 0;
2793 
2794   // Skip empty regions (if any) up to the top of the space.
2795   HeapWord* const src_aligned_up = sd.region_align_up(end_addr);
2796   RegionData* src_region_ptr = sd.addr_to_region_ptr(src_aligned_up);
2797   HeapWord* const top_aligned_up = sd.region_align_up(src_space_top);
2798   const RegionData* const top_region_ptr =
2799     sd.addr_to_region_ptr(top_aligned_up);
2800   while (src_region_ptr < top_region_ptr && src_region_ptr->data_size() == 0) {
2801     ++src_region_ptr;
2802   }
2803 
2804   if (src_region_ptr < top_region_ptr) {
2805     // The next source region is in the current space.  Update src_region_idx
2806     // and the source address to match src_region_ptr.
2807     src_region_idx = sd.region(src_region_ptr);
2808     HeapWord* const src_region_addr = sd.region_to_addr(src_region_idx);
2809     if (src_region_addr > closure.source()) {
2810       closure.set_source(src_region_addr);
2811     }
2812     return src_region_idx;
2813   }
2814 
2815   // Switch to a new source space and find the first non-empty region.
2816   unsigned int space_id = src_space_id + 1;
2817   assert(space_id < last_space_id, "not enough spaces");
2818 
2819   HeapWord* const destination = closure.destination();
2820 
2821   do {
2822     MutableSpace* space = _space_info[space_id].space();
2823     HeapWord* const bottom = space->bottom();
2824     const RegionData* const bottom_cp = sd.addr_to_region_ptr(bottom);
2825 
2826     // Iterate over the spaces that do not compact into themselves.
2827     if (bottom_cp->destination() != bottom) {
2828       HeapWord* const top_aligned_up = sd.region_align_up(space->top());
2829       const RegionData* const top_cp = sd.addr_to_region_ptr(top_aligned_up);
2830 
2831       for (const RegionData* src_cp = bottom_cp; src_cp < top_cp; ++src_cp) {
2832         if (src_cp->live_obj_size() > 0) {
2833           // Found it.
2834           assert(src_cp->destination() == destination,
2835                  "first live obj in the space must match the destination");
2836           assert(src_cp->partial_obj_size() == 0,
2837                  "a space cannot begin with a partial obj");
2838 
2839           src_space_id = SpaceId(space_id);
2840           src_space_top = space->top();
2841           const size_t src_region_idx = sd.region(src_cp);
2842           closure.set_source(sd.region_to_addr(src_region_idx));
2843           return src_region_idx;
2844         } else {
2845           assert(src_cp->data_size() == 0, "sanity");
2846         }
2847       }
2848     }
2849   } while (++space_id < last_space_id);
2850 
2851   assert(false, "no source region was found");
2852   return 0;
2853 }
2854 
2855 void PSParallelCompact::fill_region(ParCompactionManager* cm, MoveAndUpdateClosure& closure, size_t region_idx)
2856 {
2857   typedef ParMarkBitMap::IterationStatus IterationStatus;
2858   ParMarkBitMap* const bitmap = mark_bitmap();
2859   ParallelCompactData& sd = summary_data();
2860   RegionData* const region_ptr = sd.region(region_idx);
2861 
2862   // Get the source region and related info.
2863   size_t src_region_idx = region_ptr->source_region();
2864   SpaceId src_space_id = space_id(sd.region_to_addr(src_region_idx));
2865   HeapWord* src_space_top = _space_info[src_space_id].space()->top();
2866   HeapWord* dest_addr = sd.region_to_addr(region_idx);
2867 
2868   closure.set_source(first_src_addr(dest_addr, src_space_id, src_region_idx));
2869 
2870   // Adjust src_region_idx to prepare for decrementing destination counts (the
2871   // destination count is not decremented when a region is copied to itself).
2872   if (src_region_idx == region_idx) {
2873     src_region_idx += 1;
2874   }
2875 
2876   if (bitmap->is_unmarked(closure.source())) {
2877     // The first source word is in the middle of an object; copy the remainder
2878     // of the object or as much as will fit.  The fact that pointer updates were
2879     // deferred will be noted when the object header is processed.
2880     HeapWord* const old_src_addr = closure.source();
2881     closure.copy_partial_obj();
2882     if (closure.is_full()) {
2883       decrement_destination_counts(cm, src_space_id, src_region_idx,
2884                                    closure.source());
2885       closure.complete_region(cm, dest_addr, region_ptr);
2886       return;
2887     }
2888 
2889     HeapWord* const end_addr = sd.region_align_down(closure.source());
2890     if (sd.region_align_down(old_src_addr) != end_addr) {
2891       // The partial object was copied from more than one source region.
2892       decrement_destination_counts(cm, src_space_id, src_region_idx, end_addr);
2893 
2894       // Move to the next source region, possibly switching spaces as well.  All
2895       // args except end_addr may be modified.
2896       src_region_idx = next_src_region(closure, src_space_id, src_space_top,
2897                                        end_addr);
2898     }
2899   }
2900 
2901   do {
2902     HeapWord* const cur_addr = closure.source();
2903     HeapWord* const end_addr = MIN2(sd.region_align_up(cur_addr + 1),
2904                                     src_space_top);
2905     IterationStatus status = bitmap->iterate(&closure, cur_addr, end_addr);
2906 
2907     if (status == ParMarkBitMap::incomplete) {
2908       // The last obj that starts in the source region does not end in the
2909       // region.
2910       assert(closure.source() < end_addr, "sanity");
2911       HeapWord* const obj_beg = closure.source();
2912       HeapWord* const range_end = MIN2(obj_beg + closure.words_remaining(),
2913                                        src_space_top);
2914       HeapWord* const obj_end = bitmap->find_obj_end(obj_beg, range_end);
2915       if (obj_end < range_end) {
2916         // The end was found; the entire object will fit.
2917         status = closure.do_addr(obj_beg, bitmap->obj_size(obj_beg, obj_end));
2918         assert(status != ParMarkBitMap::would_overflow, "sanity");
2919       } else {
2920         // The end was not found; the object will not fit.
2921         assert(range_end < src_space_top, "obj cannot cross space boundary");
2922         status = ParMarkBitMap::would_overflow;
2923       }
2924     }
2925 
2926     if (status == ParMarkBitMap::would_overflow) {
2927       // The last object did not fit.  Note that interior oop updates were
2928       // deferred, then copy enough of the object to fill the region.
2929       cm->push_deferred_object(closure.destination());
2930       status = closure.copy_until_full(); // copies from closure.source()
2931 
2932       decrement_destination_counts(cm, src_space_id, src_region_idx,
2933                                    closure.source());
2934       closure.complete_region(cm, dest_addr, region_ptr);
2935       return;
2936     }
2937 
2938     if (status == ParMarkBitMap::full) {
2939       decrement_destination_counts(cm, src_space_id, src_region_idx,
2940                                    closure.source());
2941       closure.complete_region(cm, dest_addr, region_ptr);
2942       return;
2943     }
2944 
2945     decrement_destination_counts(cm, src_space_id, src_region_idx, end_addr);
2946 
2947     // Move to the next source region, possibly switching spaces as well.  All
2948     // args except end_addr may be modified.
2949     src_region_idx = next_src_region(closure, src_space_id, src_space_top,
2950                                      end_addr);
2951   } while (true);
2952 }
2953 
2954 void PSParallelCompact::fill_and_update_region(ParCompactionManager* cm, size_t region_idx)
2955 {
2956   MoveAndUpdateClosure cl(mark_bitmap(), cm, region_idx);
2957   fill_region(cm, cl, region_idx);
2958 }
2959 
2960 void PSParallelCompact::fill_and_update_shadow_region(ParCompactionManager* cm, size_t region_idx)
2961 {
2962   // Get a shadow region first
2963   ParallelCompactData& sd = summary_data();
2964   RegionData* const region_ptr = sd.region(region_idx);
2965   size_t shadow_region = ParCompactionManager::pop_shadow_region_mt_safe(region_ptr);
2966   // The InvalidShadow return value indicates the corresponding heap region is available,
2967   // so use MoveAndUpdateClosure to fill the normal region. Otherwise, use
2968   // MoveAndUpdateShadowClosure to fill the acquired shadow region.
2969   if (shadow_region == ParCompactionManager::InvalidShadow) {
2970     MoveAndUpdateClosure cl(mark_bitmap(), cm, region_idx);
2971     region_ptr->shadow_to_normal();
2972     return fill_region(cm, cl, region_idx);
2973   } else {
2974     MoveAndUpdateShadowClosure cl(mark_bitmap(), cm, region_idx, shadow_region);
2975     return fill_region(cm, cl, region_idx);
2976   }
2977 }
2978 
2979 void PSParallelCompact::copy_back(HeapWord *shadow_addr, HeapWord *region_addr)
2980 {
2981   Copy::aligned_conjoint_words(shadow_addr, region_addr, _summary_data.RegionSize);
2982 }
2983 
2984 bool PSParallelCompact::steal_unavailable_region(ParCompactionManager* cm, size_t &region_idx)
2985 {
2986   size_t next = cm->next_shadow_region();
2987   ParallelCompactData& sd = summary_data();
2988   size_t old_new_top = sd.addr_to_region_idx(_space_info[old_space_id].new_top());
2989   uint active_gc_threads = ParallelScavengeHeap::heap()->workers().active_workers();
2990 
2991   while (next < old_new_top) {
2992     if (sd.region(next)->mark_shadow()) {
2993       region_idx = next;
2994       return true;
2995     }
2996     next = cm->move_next_shadow_region_by(active_gc_threads);
2997   }
2998 
2999   return false;
3000 }
3001 
3002 // The shadow region is an optimization to address region dependencies in full GC. The basic
3003 // idea is making more regions available by temporally storing their live objects in empty
3004 // shadow regions to resolve dependencies between them and the destination regions. Therefore,
3005 // GC threads need not wait destination regions to be available before processing sources.
3006 //
3007 // A typical workflow would be:
3008 // After draining its own stack and failing to steal from others, a GC worker would pick an
3009 // unavailable region (destination count > 0) and get a shadow region. Then the worker fills
3010 // the shadow region by copying live objects from source regions of the unavailable one. Once
3011 // the unavailable region becomes available, the data in the shadow region will be copied back.
3012 // Shadow regions are empty regions in the to-space and regions between top and end of other spaces.
3013 void PSParallelCompact::initialize_shadow_regions(uint parallel_gc_threads)
3014 {
3015   const ParallelCompactData& sd = PSParallelCompact::summary_data();
3016 
3017   for (unsigned int id = old_space_id; id < last_space_id; ++id) {
3018     SpaceInfo* const space_info = _space_info + id;
3019     MutableSpace* const space = space_info->space();
3020 
3021     const size_t beg_region =
3022       sd.addr_to_region_idx(sd.region_align_up(MAX2(space_info->new_top(), space->top())));
3023     const size_t end_region =
3024       sd.addr_to_region_idx(sd.region_align_down(space->end()));
3025 
3026     for (size_t cur = beg_region; cur < end_region; ++cur) {
3027       ParCompactionManager::push_shadow_region(cur);
3028     }
3029   }
3030 
3031   size_t beg_region = sd.addr_to_region_idx(_space_info[old_space_id].dense_prefix());
3032   for (uint i = 0; i < parallel_gc_threads; i++) {
3033     ParCompactionManager *cm = ParCompactionManager::gc_thread_compaction_manager(i);
3034     cm->set_next_shadow_region(beg_region + i);
3035   }
3036 }
3037 
3038 void PSParallelCompact::fill_blocks(size_t region_idx)
3039 {
3040   // Fill in the block table elements for the specified region.  Each block
3041   // table element holds the number of live words in the region that are to the
3042   // left of the first object that starts in the block.  Thus only blocks in
3043   // which an object starts need to be filled.
3044   //
3045   // The algorithm scans the section of the bitmap that corresponds to the
3046   // region, keeping a running total of the live words.  When an object start is
3047   // found, if it's the first to start in the block that contains it, the
3048   // current total is written to the block table element.
3049   const size_t Log2BlockSize = ParallelCompactData::Log2BlockSize;
3050   const size_t Log2RegionSize = ParallelCompactData::Log2RegionSize;
3051   const size_t RegionSize = ParallelCompactData::RegionSize;
3052 
3053   ParallelCompactData& sd = summary_data();
3054   const size_t partial_obj_size = sd.region(region_idx)->partial_obj_size();
3055   if (partial_obj_size >= RegionSize) {
3056     return; // No objects start in this region.
3057   }
3058 
3059   // Ensure the first loop iteration decides that the block has changed.
3060   size_t cur_block = sd.block_count();
3061 
3062   const ParMarkBitMap* const bitmap = mark_bitmap();
3063 
3064   const size_t Log2BitsPerBlock = Log2BlockSize - LogMinObjAlignment;
3065   assert((size_t)1 << Log2BitsPerBlock ==
3066          bitmap->words_to_bits(ParallelCompactData::BlockSize), "sanity");
3067 
3068   size_t beg_bit = bitmap->words_to_bits(region_idx << Log2RegionSize);
3069   const size_t range_end = beg_bit + bitmap->words_to_bits(RegionSize);
3070   size_t live_bits = bitmap->words_to_bits(partial_obj_size);
3071   beg_bit = bitmap->find_obj_beg(beg_bit + live_bits, range_end);
3072   while (beg_bit < range_end) {
3073     const size_t new_block = beg_bit >> Log2BitsPerBlock;
3074     if (new_block != cur_block) {
3075       cur_block = new_block;
3076       sd.block(cur_block)->set_offset(bitmap->bits_to_words(live_bits));
3077     }
3078 
3079     const size_t end_bit = bitmap->find_obj_end(beg_bit, range_end);
3080     if (end_bit < range_end - 1) {
3081       live_bits += end_bit - beg_bit + 1;
3082       beg_bit = bitmap->find_obj_beg(end_bit + 1, range_end);
3083     } else {
3084       return;
3085     }
3086   }
3087 }
3088 
3089 ParMarkBitMap::IterationStatus MoveAndUpdateClosure::copy_until_full()
3090 {
3091   if (source() != copy_destination()) {
3092     DEBUG_ONLY(PSParallelCompact::check_new_location(source(), destination());)
3093     Copy::aligned_conjoint_words(source(), copy_destination(), words_remaining());
3094   }
3095   update_state(words_remaining());
3096   assert(is_full(), "sanity");
3097   return ParMarkBitMap::full;
3098 }
3099 
3100 void MoveAndUpdateClosure::copy_partial_obj()
3101 {
3102   size_t words = words_remaining();
3103 
3104   HeapWord* const range_end = MIN2(source() + words, bitmap()->region_end());
3105   HeapWord* const end_addr = bitmap()->find_obj_end(source(), range_end);
3106   if (end_addr < range_end) {
3107     words = bitmap()->obj_size(source(), end_addr);
3108   }
3109 
3110   // This test is necessary; if omitted, the pointer updates to a partial object
3111   // that crosses the dense prefix boundary could be overwritten.
3112   if (source() != copy_destination()) {
3113     DEBUG_ONLY(PSParallelCompact::check_new_location(source(), destination());)
3114     Copy::aligned_conjoint_words(source(), copy_destination(), words);
3115   }
3116   update_state(words);
3117 }
3118 
3119 void MoveAndUpdateClosure::complete_region(ParCompactionManager *cm, HeapWord *dest_addr,
3120                                            PSParallelCompact::RegionData *region_ptr) {
3121   assert(region_ptr->shadow_state() == ParallelCompactData::RegionData::NormalRegion, "Region should be finished");
3122   region_ptr->set_completed();
3123 }
3124 
3125 ParMarkBitMapClosure::IterationStatus
3126 MoveAndUpdateClosure::do_addr(HeapWord* addr, size_t words) {
3127   assert(destination() != nullptr, "sanity");
3128   assert(bitmap()->obj_size(addr) == words, "bad size");
3129 
3130   _source = addr;
3131   assert(PSParallelCompact::summary_data().calc_new_pointer(source(), compaction_manager()) ==
3132          destination(), "wrong destination");
3133 
3134   if (words > words_remaining()) {
3135     return ParMarkBitMap::would_overflow;
3136   }
3137 
3138   // The start_array must be updated even if the object is not moving.
3139   if (_start_array != nullptr) {
3140     _start_array->update_for_block(destination(), destination() + words);
3141   }
3142 
3143   if (copy_destination() != source()) {
3144     DEBUG_ONLY(PSParallelCompact::check_new_location(source(), destination());)
3145     Copy::aligned_conjoint_words(source(), copy_destination(), words);
3146   }
3147 
3148   oop moved_oop = cast_to_oop(copy_destination());
3149   compaction_manager()->update_contents(moved_oop);
3150   assert(oopDesc::is_oop_or_null(moved_oop), "Expected an oop or null at " PTR_FORMAT, p2i(moved_oop));
3151 
3152   update_state(words);
3153   assert(copy_destination() == cast_from_oop<HeapWord*>(moved_oop) + moved_oop->size(), "sanity");
3154   return is_full() ? ParMarkBitMap::full : ParMarkBitMap::incomplete;
3155 }
3156 
3157 void MoveAndUpdateShadowClosure::complete_region(ParCompactionManager *cm, HeapWord *dest_addr,
3158                                                  PSParallelCompact::RegionData *region_ptr) {
3159   assert(region_ptr->shadow_state() == ParallelCompactData::RegionData::ShadowRegion, "Region should be shadow");
3160   // Record the shadow region index
3161   region_ptr->set_shadow_region(_shadow);
3162   // Mark the shadow region as filled to indicate the data is ready to be
3163   // copied back
3164   region_ptr->mark_filled();
3165   // Try to copy the content of the shadow region back to its corresponding
3166   // heap region if available; the GC thread that decreases the destination
3167   // count to zero will do the copying otherwise (see
3168   // PSParallelCompact::decrement_destination_counts).
3169   if (((region_ptr->available() && region_ptr->claim()) || region_ptr->claimed()) && region_ptr->mark_copied()) {
3170     region_ptr->set_completed();
3171     PSParallelCompact::copy_back(PSParallelCompact::summary_data().region_to_addr(_shadow), dest_addr);
3172     ParCompactionManager::push_shadow_region_mt_safe(_shadow);
3173   }
3174 }
3175 
3176 UpdateOnlyClosure::UpdateOnlyClosure(ParMarkBitMap* mbm,
3177                                      ParCompactionManager* cm,
3178                                      PSParallelCompact::SpaceId space_id) :
3179   ParMarkBitMapClosure(mbm, cm),
3180   _start_array(PSParallelCompact::start_array(space_id))
3181 {
3182 }
3183 
3184 // Updates the references in the object to their new values.
3185 ParMarkBitMapClosure::IterationStatus
3186 UpdateOnlyClosure::do_addr(HeapWord* addr, size_t words) {
3187   do_addr(addr);
3188   return ParMarkBitMap::incomplete;
3189 }
3190 
3191 FillClosure::FillClosure(ParCompactionManager* cm, PSParallelCompact::SpaceId space_id) :
3192   ParMarkBitMapClosure(PSParallelCompact::mark_bitmap(), cm),
3193   _start_array(PSParallelCompact::start_array(space_id))
3194 {
3195   assert(space_id == PSParallelCompact::old_space_id,
3196          "cannot use FillClosure in the young gen");
3197 }
3198 
3199 ParMarkBitMapClosure::IterationStatus
3200 FillClosure::do_addr(HeapWord* addr, size_t size) {
3201   CollectedHeap::fill_with_objects(addr, size);
3202   HeapWord* const end = addr + size;
3203   do {
3204     size_t size = cast_to_oop(addr)->size();
3205     _start_array->update_for_block(addr, addr + size);
3206     addr += size;
3207   } while (addr < end);
3208   return ParMarkBitMap::incomplete;
3209 }