1 /*
   2  * Copyright (c) 2000, 2021, 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/symbolTable.hpp"
  28 #include "classfile/stringTable.hpp"
  29 #include "classfile/vmSymbols.hpp"
  30 #include "code/codeCache.hpp"
  31 #include "code/icBuffer.hpp"
  32 #include "compiler/oopMap.hpp"
  33 #include "gc/serial/defNewGeneration.hpp"
  34 #include "gc/shared/adaptiveSizePolicy.hpp"
  35 #include "gc/shared/cardTableBarrierSet.hpp"
  36 #include "gc/shared/cardTableRS.hpp"
  37 #include "gc/shared/collectedHeap.inline.hpp"
  38 #include "gc/shared/collectorCounters.hpp"
  39 #include "gc/shared/gcId.hpp"
  40 #include "gc/shared/gcLocker.hpp"
  41 #include "gc/shared/gcPolicyCounters.hpp"
  42 #include "gc/shared/gcTrace.hpp"
  43 #include "gc/shared/gcTraceTime.inline.hpp"
  44 #include "gc/shared/genArguments.hpp"
  45 #include "gc/shared/gcVMOperations.hpp"
  46 #include "gc/shared/genCollectedHeap.hpp"
  47 #include "gc/shared/genOopClosures.inline.hpp"
  48 #include "gc/shared/generationSpec.hpp"
  49 #include "gc/shared/gcInitLogger.hpp"
  50 #include "gc/shared/locationPrinter.inline.hpp"
  51 #include "gc/shared/oopStorage.inline.hpp"
  52 #include "gc/shared/oopStorageSet.inline.hpp"
  53 #include "gc/shared/oopStorageParState.inline.hpp"
  54 #include "gc/shared/scavengableNMethods.hpp"
  55 #include "gc/shared/slidingForwarding.hpp"
  56 #include "gc/shared/space.hpp"
  57 #include "gc/shared/strongRootsScope.hpp"
  58 #include "gc/shared/weakProcessor.hpp"
  59 #include "gc/shared/workerThread.hpp"
  60 #include "memory/iterator.hpp"
  61 #include "memory/metaspaceCounters.hpp"
  62 #include "memory/metaspaceUtils.hpp"
  63 #include "memory/resourceArea.hpp"
  64 #include "memory/universe.hpp"
  65 #include "oops/oop.inline.hpp"
  66 #include "runtime/handles.hpp"
  67 #include "runtime/handles.inline.hpp"
  68 #include "runtime/java.hpp"
  69 #include "runtime/vmThread.hpp"
  70 #include "services/memoryService.hpp"
  71 #include "utilities/autoRestore.hpp"
  72 #include "utilities/debug.hpp"
  73 #include "utilities/formatBuffer.hpp"
  74 #include "utilities/macros.hpp"
  75 #include "utilities/stack.inline.hpp"
  76 #include "utilities/vmError.hpp"
  77 #if INCLUDE_JVMCI
  78 #include "jvmci/jvmci.hpp"
  79 #endif
  80 
  81 GenCollectedHeap::GenCollectedHeap(Generation::Name young,
  82                                    Generation::Name old,
  83                                    const char* policy_counters_name) :
  84   CollectedHeap(),
  85   _young_gen(NULL),
  86   _old_gen(NULL),
  87   _young_gen_spec(new GenerationSpec(young,
  88                                      NewSize,
  89                                      MaxNewSize,
  90                                      GenAlignment)),
  91   _old_gen_spec(new GenerationSpec(old,
  92                                    OldSize,
  93                                    MaxOldSize,
  94                                    GenAlignment)),
  95   _rem_set(NULL),
  96   _soft_ref_gen_policy(),
  97   _size_policy(NULL),
  98   _gc_policy_counters(new GCPolicyCounters(policy_counters_name, 2, 2)),
  99   _incremental_collection_failed(false),
 100   _full_collections_completed(0),
 101   _young_manager(NULL),
 102   _old_manager(NULL) {
 103 }
 104 
 105 jint GenCollectedHeap::initialize() {
 106   // While there are no constraints in the GC code that HeapWordSize
 107   // be any particular value, there are multiple other areas in the
 108   // system which believe this to be true (e.g. oop->object_size in some
 109   // cases incorrectly returns the size in wordSize units rather than
 110   // HeapWordSize).
 111   guarantee(HeapWordSize == wordSize, "HeapWordSize must equal wordSize");
 112 
 113   // Allocate space for the heap.
 114 
 115   ReservedHeapSpace heap_rs = allocate(HeapAlignment);
 116 
 117   if (!heap_rs.is_reserved()) {
 118     vm_shutdown_during_initialization(
 119       "Could not reserve enough space for object heap");
 120     return JNI_ENOMEM;
 121   }
 122 
 123   initialize_reserved_region(heap_rs);
 124   _forwarding = new SlidingForwarding(_reserved);
 125 
 126   _rem_set = create_rem_set(heap_rs.region());
 127   _rem_set->initialize();
 128   CardTableBarrierSet *bs = new CardTableBarrierSet(_rem_set);
 129   bs->initialize();
 130   BarrierSet::set_barrier_set(bs);
 131 
 132   ReservedSpace young_rs = heap_rs.first_part(_young_gen_spec->max_size());
 133   _young_gen = _young_gen_spec->init(young_rs, rem_set());
 134   ReservedSpace old_rs = heap_rs.last_part(_young_gen_spec->max_size());
 135 
 136   old_rs = old_rs.first_part(_old_gen_spec->max_size());
 137   _old_gen = _old_gen_spec->init(old_rs, rem_set());
 138 
 139   GCInitLogger::print();
 140 
 141   return JNI_OK;
 142 }
 143 
 144 CardTableRS* GenCollectedHeap::create_rem_set(const MemRegion& reserved_region) {
 145   return new CardTableRS(reserved_region);
 146 }
 147 
 148 void GenCollectedHeap::initialize_size_policy(size_t init_eden_size,
 149                                               size_t init_promo_size,
 150                                               size_t init_survivor_size) {
 151   const double max_gc_pause_sec = ((double) MaxGCPauseMillis) / 1000.0;
 152   _size_policy = new AdaptiveSizePolicy(init_eden_size,
 153                                         init_promo_size,
 154                                         init_survivor_size,
 155                                         max_gc_pause_sec,
 156                                         GCTimeRatio);
 157 }
 158 
 159 ReservedHeapSpace GenCollectedHeap::allocate(size_t alignment) {
 160   // Now figure out the total size.
 161   const size_t pageSize = UseLargePages ? os::large_page_size() : os::vm_page_size();
 162   assert(alignment % pageSize == 0, "Must be");
 163 
 164   // Check for overflow.
 165   size_t total_reserved = _young_gen_spec->max_size() + _old_gen_spec->max_size();
 166   if (total_reserved < _young_gen_spec->max_size()) {
 167     vm_exit_during_initialization("The size of the object heap + VM data exceeds "
 168                                   "the maximum representable size");
 169   }
 170   assert(total_reserved % alignment == 0,
 171          "Gen size; total_reserved=" SIZE_FORMAT ", alignment="
 172          SIZE_FORMAT, total_reserved, alignment);
 173 
 174   ReservedHeapSpace heap_rs = Universe::reserve_heap(total_reserved, alignment);
 175   size_t used_page_size = heap_rs.page_size();
 176 
 177   os::trace_page_sizes("Heap",
 178                        MinHeapSize,
 179                        total_reserved,
 180                        used_page_size,
 181                        heap_rs.base(),
 182                        heap_rs.size());
 183 
 184   return heap_rs;
 185 }
 186 
 187 class GenIsScavengable : public BoolObjectClosure {
 188 public:
 189   bool do_object_b(oop obj) {
 190     return GenCollectedHeap::heap()->is_in_young(obj);
 191   }
 192 };
 193 
 194 static GenIsScavengable _is_scavengable;
 195 
 196 void GenCollectedHeap::post_initialize() {
 197   CollectedHeap::post_initialize();
 198   ref_processing_init();
 199 
 200   DefNewGeneration* def_new_gen = (DefNewGeneration*)_young_gen;
 201 
 202   initialize_size_policy(def_new_gen->eden()->capacity(),
 203                          _old_gen->capacity(),
 204                          def_new_gen->from()->capacity());
 205 
 206   MarkSweep::initialize();
 207 
 208   ScavengableNMethods::initialize(&_is_scavengable);
 209 }
 210 
 211 void GenCollectedHeap::ref_processing_init() {
 212   _young_gen->ref_processor_init();
 213   _old_gen->ref_processor_init();
 214 }
 215 
 216 PreGenGCValues GenCollectedHeap::get_pre_gc_values() const {
 217   const DefNewGeneration* const def_new_gen = (DefNewGeneration*) young_gen();
 218 
 219   return PreGenGCValues(def_new_gen->used(),
 220                         def_new_gen->capacity(),
 221                         def_new_gen->eden()->used(),
 222                         def_new_gen->eden()->capacity(),
 223                         def_new_gen->from()->used(),
 224                         def_new_gen->from()->capacity(),
 225                         old_gen()->used(),
 226                         old_gen()->capacity());
 227 }
 228 
 229 GenerationSpec* GenCollectedHeap::young_gen_spec() const {
 230   return _young_gen_spec;
 231 }
 232 
 233 GenerationSpec* GenCollectedHeap::old_gen_spec() const {
 234   return _old_gen_spec;
 235 }
 236 
 237 size_t GenCollectedHeap::capacity() const {
 238   return _young_gen->capacity() + _old_gen->capacity();
 239 }
 240 
 241 size_t GenCollectedHeap::used() const {
 242   return _young_gen->used() + _old_gen->used();
 243 }
 244 
 245 void GenCollectedHeap::save_used_regions() {
 246   _old_gen->save_used_region();
 247   _young_gen->save_used_region();
 248 }
 249 
 250 size_t GenCollectedHeap::max_capacity() const {
 251   return _young_gen->max_capacity() + _old_gen->max_capacity();
 252 }
 253 
 254 // Update the _full_collections_completed counter
 255 // at the end of a stop-world full GC.
 256 unsigned int GenCollectedHeap::update_full_collections_completed() {
 257   assert(_full_collections_completed <= _total_full_collections,
 258          "Can't complete more collections than were started");
 259   _full_collections_completed = _total_full_collections;
 260   return _full_collections_completed;
 261 }
 262 
 263 // Return true if any of the following is true:
 264 // . the allocation won't fit into the current young gen heap
 265 // . gc locker is occupied (jni critical section)
 266 // . heap memory is tight -- the most recent previous collection
 267 //   was a full collection because a partial collection (would
 268 //   have) failed and is likely to fail again
 269 bool GenCollectedHeap::should_try_older_generation_allocation(size_t word_size) const {
 270   size_t young_capacity = _young_gen->capacity_before_gc();
 271   return    (word_size > heap_word_size(young_capacity))
 272          || GCLocker::is_active_and_needs_gc()
 273          || incremental_collection_failed();
 274 }
 275 
 276 HeapWord* GenCollectedHeap::expand_heap_and_allocate(size_t size, bool   is_tlab) {
 277   HeapWord* result = NULL;
 278   if (_old_gen->should_allocate(size, is_tlab)) {
 279     result = _old_gen->expand_and_allocate(size, is_tlab);
 280   }
 281   if (result == NULL) {
 282     if (_young_gen->should_allocate(size, is_tlab)) {
 283       result = _young_gen->expand_and_allocate(size, is_tlab);
 284     }
 285   }
 286   assert(result == NULL || is_in_reserved(result), "result not in heap");
 287   return result;
 288 }
 289 
 290 HeapWord* GenCollectedHeap::mem_allocate_work(size_t size,
 291                                               bool is_tlab,
 292                                               bool* gc_overhead_limit_was_exceeded) {
 293   // In general gc_overhead_limit_was_exceeded should be false so
 294   // set it so here and reset it to true only if the gc time
 295   // limit is being exceeded as checked below.
 296   *gc_overhead_limit_was_exceeded = false;
 297 
 298   HeapWord* result = NULL;
 299 
 300   // Loop until the allocation is satisfied, or unsatisfied after GC.
 301   for (uint try_count = 1, gclocker_stalled_count = 0; /* return or throw */; try_count += 1) {
 302 
 303     // First allocation attempt is lock-free.
 304     Generation *young = _young_gen;
 305     assert(young->supports_inline_contig_alloc(),
 306       "Otherwise, must do alloc within heap lock");
 307     if (young->should_allocate(size, is_tlab)) {
 308       result = young->par_allocate(size, is_tlab);
 309       if (result != NULL) {
 310         assert(is_in_reserved(result), "result not in heap");
 311         return result;
 312       }
 313     }
 314     uint gc_count_before;  // Read inside the Heap_lock locked region.
 315     {
 316       MutexLocker ml(Heap_lock);
 317       log_trace(gc, alloc)("GenCollectedHeap::mem_allocate_work: attempting locked slow path allocation");
 318       // Note that only large objects get a shot at being
 319       // allocated in later generations.
 320       bool first_only = !should_try_older_generation_allocation(size);
 321 
 322       result = attempt_allocation(size, is_tlab, first_only);
 323       if (result != NULL) {
 324         assert(is_in_reserved(result), "result not in heap");
 325         return result;
 326       }
 327 
 328       if (GCLocker::is_active_and_needs_gc()) {
 329         if (is_tlab) {
 330           return NULL;  // Caller will retry allocating individual object.
 331         }
 332         if (!is_maximal_no_gc()) {
 333           // Try and expand heap to satisfy request.
 334           result = expand_heap_and_allocate(size, is_tlab);
 335           // Result could be null if we are out of space.
 336           if (result != NULL) {
 337             return result;
 338           }
 339         }
 340 
 341         if (gclocker_stalled_count > GCLockerRetryAllocationCount) {
 342           return NULL; // We didn't get to do a GC and we didn't get any memory.
 343         }
 344 
 345         // If this thread is not in a jni critical section, we stall
 346         // the requestor until the critical section has cleared and
 347         // GC allowed. When the critical section clears, a GC is
 348         // initiated by the last thread exiting the critical section; so
 349         // we retry the allocation sequence from the beginning of the loop,
 350         // rather than causing more, now probably unnecessary, GC attempts.
 351         JavaThread* jthr = JavaThread::current();
 352         if (!jthr->in_critical()) {
 353           MutexUnlocker mul(Heap_lock);
 354           // Wait for JNI critical section to be exited
 355           GCLocker::stall_until_clear();
 356           gclocker_stalled_count += 1;
 357           continue;
 358         } else {
 359           if (CheckJNICalls) {
 360             fatal("Possible deadlock due to allocating while"
 361                   " in jni critical section");
 362           }
 363           return NULL;
 364         }
 365       }
 366 
 367       // Read the gc count while the heap lock is held.
 368       gc_count_before = total_collections();
 369     }
 370 
 371     VM_GenCollectForAllocation op(size, is_tlab, gc_count_before);
 372     VMThread::execute(&op);
 373     if (op.prologue_succeeded()) {
 374       result = op.result();
 375       if (op.gc_locked()) {
 376          assert(result == NULL, "must be NULL if gc_locked() is true");
 377          continue;  // Retry and/or stall as necessary.
 378       }
 379 
 380       // Allocation has failed and a collection
 381       // has been done.  If the gc time limit was exceeded the
 382       // this time, return NULL so that an out-of-memory
 383       // will be thrown.  Clear gc_overhead_limit_exceeded
 384       // so that the overhead exceeded does not persist.
 385 
 386       const bool limit_exceeded = size_policy()->gc_overhead_limit_exceeded();
 387       const bool softrefs_clear = soft_ref_policy()->all_soft_refs_clear();
 388 
 389       if (limit_exceeded && softrefs_clear) {
 390         *gc_overhead_limit_was_exceeded = true;
 391         size_policy()->set_gc_overhead_limit_exceeded(false);
 392         if (op.result() != NULL) {
 393           CollectedHeap::fill_with_object(op.result(), size);
 394         }
 395         return NULL;
 396       }
 397       assert(result == NULL || is_in_reserved(result),
 398              "result not in heap");
 399       return result;
 400     }
 401 
 402     // Give a warning if we seem to be looping forever.
 403     if ((QueuedAllocationWarningCount > 0) &&
 404         (try_count % QueuedAllocationWarningCount == 0)) {
 405           log_warning(gc, ergo)("GenCollectedHeap::mem_allocate_work retries %d times,"
 406                                 " size=" SIZE_FORMAT " %s", try_count, size, is_tlab ? "(TLAB)" : "");
 407     }
 408   }
 409 }
 410 
 411 HeapWord* GenCollectedHeap::attempt_allocation(size_t size,
 412                                                bool is_tlab,
 413                                                bool first_only) {
 414   HeapWord* res = NULL;
 415 
 416   if (_young_gen->should_allocate(size, is_tlab)) {
 417     res = _young_gen->allocate(size, is_tlab);
 418     if (res != NULL || first_only) {
 419       return res;
 420     }
 421   }
 422 
 423   if (_old_gen->should_allocate(size, is_tlab)) {
 424     res = _old_gen->allocate(size, is_tlab);
 425   }
 426 
 427   return res;
 428 }
 429 
 430 HeapWord* GenCollectedHeap::mem_allocate(size_t size,
 431                                          bool* gc_overhead_limit_was_exceeded) {
 432   return mem_allocate_work(size,
 433                            false /* is_tlab */,
 434                            gc_overhead_limit_was_exceeded);
 435 }
 436 
 437 bool GenCollectedHeap::must_clear_all_soft_refs() {
 438   return _gc_cause == GCCause::_metadata_GC_clear_soft_refs ||
 439          _gc_cause == GCCause::_wb_full_gc;
 440 }
 441 
 442 void GenCollectedHeap::collect_generation(Generation* gen, bool full, size_t size,
 443                                           bool is_tlab, bool run_verification, bool clear_soft_refs) {
 444   FormatBuffer<> title("Collect gen: %s", gen->short_name());
 445   GCTraceTime(Trace, gc, phases) t1(title);
 446   TraceCollectorStats tcs(gen->counters());
 447   TraceMemoryManagerStats tmms(gen->gc_manager(), gc_cause());
 448 
 449   gen->stat_record()->invocations++;
 450   gen->stat_record()->accumulated_time.start();
 451 
 452   // Must be done anew before each collection because
 453   // a previous collection will do mangling and will
 454   // change top of some spaces.
 455   record_gen_tops_before_GC();
 456 
 457   log_trace(gc)("%s invoke=%d size=" SIZE_FORMAT, heap()->is_young_gen(gen) ? "Young" : "Old", gen->stat_record()->invocations, size * HeapWordSize);
 458 
 459   if (run_verification && VerifyBeforeGC) {
 460     Universe::verify("Before GC");
 461   }
 462   COMPILER2_OR_JVMCI_PRESENT(DerivedPointerTable::clear());
 463 
 464   // Do collection work
 465   {
 466     // Note on ref discovery: For what appear to be historical reasons,
 467     // GCH enables and disabled (by enqueing) refs discovery.
 468     // In the future this should be moved into the generation's
 469     // collect method so that ref discovery and enqueueing concerns
 470     // are local to a generation. The collect method could return
 471     // an appropriate indication in the case that notification on
 472     // the ref lock was needed. This will make the treatment of
 473     // weak refs more uniform (and indeed remove such concerns
 474     // from GCH). XXX
 475 
 476     save_marks();   // save marks for all gens
 477     // We want to discover references, but not process them yet.
 478     // This mode is disabled in process_discovered_references if the
 479     // generation does some collection work, or in
 480     // enqueue_discovered_references if the generation returns
 481     // without doing any work.
 482     ReferenceProcessor* rp = gen->ref_processor();
 483     rp->start_discovery(clear_soft_refs);
 484 
 485     gen->collect(full, clear_soft_refs, size, is_tlab);
 486 
 487     rp->disable_discovery();
 488     rp->verify_no_references_recorded();
 489   }
 490 
 491   COMPILER2_OR_JVMCI_PRESENT(DerivedPointerTable::update_pointers());
 492 
 493   gen->stat_record()->accumulated_time.stop();
 494 
 495   update_gc_stats(gen, full);
 496 
 497   if (run_verification && VerifyAfterGC) {
 498     Universe::verify("After GC");
 499   }
 500 }
 501 
 502 void GenCollectedHeap::do_collection(bool           full,
 503                                      bool           clear_all_soft_refs,
 504                                      size_t         size,
 505                                      bool           is_tlab,
 506                                      GenerationType max_generation) {
 507   ResourceMark rm;
 508   DEBUG_ONLY(Thread* my_thread = Thread::current();)
 509 
 510   assert(SafepointSynchronize::is_at_safepoint(), "should be at safepoint");
 511   assert(my_thread->is_VM_thread(), "only VM thread");
 512   assert(Heap_lock->is_locked(),
 513          "the requesting thread should have the Heap_lock");
 514   guarantee(!is_gc_active(), "collection is not reentrant");
 515 
 516   if (GCLocker::check_active_before_gc()) {
 517     return; // GC is disabled (e.g. JNI GetXXXCritical operation)
 518   }
 519 
 520   const bool do_clear_all_soft_refs = clear_all_soft_refs ||
 521                           soft_ref_policy()->should_clear_all_soft_refs();
 522 
 523   ClearedAllSoftRefs casr(do_clear_all_soft_refs, soft_ref_policy());
 524 
 525   AutoModifyRestore<bool> temporarily(_is_gc_active, true);
 526 
 527   bool complete = full && (max_generation == OldGen);
 528   bool old_collects_young = complete && !ScavengeBeforeFullGC;
 529   bool do_young_collection = !old_collects_young && _young_gen->should_collect(full, size, is_tlab);
 530 
 531   const PreGenGCValues pre_gc_values = get_pre_gc_values();
 532 
 533   bool run_verification = total_collections() >= VerifyGCStartAt;
 534   bool prepared_for_verification = false;
 535   bool do_full_collection = false;
 536 
 537   if (do_young_collection) {
 538     GCIdMark gc_id_mark;
 539     GCTraceCPUTime tcpu;
 540     GCTraceTime(Info, gc) t("Pause Young", NULL, gc_cause(), true);
 541 
 542     print_heap_before_gc();
 543 
 544     if (run_verification && VerifyGCLevel <= 0 && VerifyBeforeGC) {
 545       prepare_for_verify();
 546       prepared_for_verification = true;
 547     }
 548 
 549     gc_prologue(complete);
 550     increment_total_collections(complete);
 551 
 552     collect_generation(_young_gen,
 553                        full,
 554                        size,
 555                        is_tlab,
 556                        run_verification && VerifyGCLevel <= 0,
 557                        do_clear_all_soft_refs);
 558 
 559     if (size > 0 && (!is_tlab || _young_gen->supports_tlab_allocation()) &&
 560         size * HeapWordSize <= _young_gen->unsafe_max_alloc_nogc()) {
 561       // Allocation request was met by young GC.
 562       size = 0;
 563     }
 564 
 565     // Ask if young collection is enough. If so, do the final steps for young collection,
 566     // and fallthrough to the end.
 567     do_full_collection = should_do_full_collection(size, full, is_tlab, max_generation);
 568     if (!do_full_collection) {
 569       // Adjust generation sizes.
 570       _young_gen->compute_new_size();
 571 
 572       print_heap_change(pre_gc_values);
 573 
 574       // Track memory usage and detect low memory after GC finishes
 575       MemoryService::track_memory_usage();
 576 
 577       gc_epilogue(complete);
 578     }
 579 
 580     print_heap_after_gc();
 581 
 582   } else {
 583     // No young collection, ask if we need to perform Full collection.
 584     do_full_collection = should_do_full_collection(size, full, is_tlab, max_generation);
 585   }
 586 
 587   if (do_full_collection) {
 588     GCIdMark gc_id_mark;
 589     GCTraceCPUTime tcpu;
 590     GCTraceTime(Info, gc) t("Pause Full", NULL, gc_cause(), true);
 591 
 592     print_heap_before_gc();
 593 
 594     if (!prepared_for_verification && run_verification &&
 595         VerifyGCLevel <= 1 && VerifyBeforeGC) {
 596       prepare_for_verify();
 597     }
 598 
 599     if (!do_young_collection) {
 600       gc_prologue(complete);
 601       increment_total_collections(complete);
 602     }
 603 
 604     // Accounting quirk: total full collections would be incremented when "complete"
 605     // is set, by calling increment_total_collections above. However, we also need to
 606     // account Full collections that had "complete" unset.
 607     if (!complete) {
 608       increment_total_full_collections();
 609     }
 610 
 611     collect_generation(_old_gen,
 612                        full,
 613                        size,
 614                        is_tlab,
 615                        run_verification && VerifyGCLevel <= 1,
 616                        do_clear_all_soft_refs);
 617 
 618     // Adjust generation sizes.
 619     _old_gen->compute_new_size();
 620     _young_gen->compute_new_size();
 621 
 622     // Delete metaspaces for unloaded class loaders and clean up loader_data graph
 623     ClassLoaderDataGraph::purge(/*at_safepoint*/true);
 624     DEBUG_ONLY(MetaspaceUtils::verify();)
 625     // Resize the metaspace capacity after full collections
 626     MetaspaceGC::compute_new_size();
 627     update_full_collections_completed();
 628 
 629     print_heap_change(pre_gc_values);
 630 
 631     // Track memory usage and detect low memory after GC finishes
 632     MemoryService::track_memory_usage();
 633 
 634     // Need to tell the epilogue code we are done with Full GC, regardless what was
 635     // the initial value for "complete" flag.
 636     gc_epilogue(true);
 637 
 638     print_heap_after_gc();
 639   }
 640 }
 641 
 642 bool GenCollectedHeap::should_do_full_collection(size_t size, bool full, bool is_tlab,
 643                                                  GenCollectedHeap::GenerationType max_gen) const {
 644   return max_gen == OldGen && _old_gen->should_collect(full, size, is_tlab);
 645 }
 646 
 647 void GenCollectedHeap::register_nmethod(nmethod* nm) {
 648   ScavengableNMethods::register_nmethod(nm);
 649 }
 650 
 651 void GenCollectedHeap::unregister_nmethod(nmethod* nm) {
 652   ScavengableNMethods::unregister_nmethod(nm);
 653 }
 654 
 655 void GenCollectedHeap::verify_nmethod(nmethod* nm) {
 656   ScavengableNMethods::verify_nmethod(nm);
 657 }
 658 
 659 void GenCollectedHeap::flush_nmethod(nmethod* nm) {
 660   // Do nothing.
 661 }
 662 
 663 void GenCollectedHeap::prune_scavengable_nmethods() {
 664   ScavengableNMethods::prune_nmethods();
 665 }
 666 
 667 HeapWord* GenCollectedHeap::satisfy_failed_allocation(size_t size, bool is_tlab) {
 668   GCCauseSetter x(this, GCCause::_allocation_failure);
 669   HeapWord* result = NULL;
 670 
 671   assert(size != 0, "Precondition violated");
 672   if (GCLocker::is_active_and_needs_gc()) {
 673     // GC locker is active; instead of a collection we will attempt
 674     // to expand the heap, if there's room for expansion.
 675     if (!is_maximal_no_gc()) {
 676       result = expand_heap_and_allocate(size, is_tlab);
 677     }
 678     return result;   // Could be null if we are out of space.
 679   } else if (!incremental_collection_will_fail(false /* don't consult_young */)) {
 680     // Do an incremental collection.
 681     do_collection(false,                     // full
 682                   false,                     // clear_all_soft_refs
 683                   size,                      // size
 684                   is_tlab,                   // is_tlab
 685                   GenCollectedHeap::OldGen); // max_generation
 686   } else {
 687     log_trace(gc)(" :: Trying full because partial may fail :: ");
 688     // Try a full collection; see delta for bug id 6266275
 689     // for the original code and why this has been simplified
 690     // with from-space allocation criteria modified and
 691     // such allocation moved out of the safepoint path.
 692     do_collection(true,                      // full
 693                   false,                     // clear_all_soft_refs
 694                   size,                      // size
 695                   is_tlab,                   // is_tlab
 696                   GenCollectedHeap::OldGen); // max_generation
 697   }
 698 
 699   result = attempt_allocation(size, is_tlab, false /*first_only*/);
 700 
 701   if (result != NULL) {
 702     assert(is_in_reserved(result), "result not in heap");
 703     return result;
 704   }
 705 
 706   // OK, collection failed, try expansion.
 707   result = expand_heap_and_allocate(size, is_tlab);
 708   if (result != NULL) {
 709     return result;
 710   }
 711 
 712   // If we reach this point, we're really out of memory. Try every trick
 713   // we can to reclaim memory. Force collection of soft references. Force
 714   // a complete compaction of the heap. Any additional methods for finding
 715   // free memory should be here, especially if they are expensive. If this
 716   // attempt fails, an OOM exception will be thrown.
 717   {
 718     UIntFlagSetting flag_change(MarkSweepAlwaysCompactCount, 1); // Make sure the heap is fully compacted
 719 
 720     do_collection(true,                      // full
 721                   true,                      // clear_all_soft_refs
 722                   size,                      // size
 723                   is_tlab,                   // is_tlab
 724                   GenCollectedHeap::OldGen); // max_generation
 725   }
 726 
 727   result = attempt_allocation(size, is_tlab, false /* first_only */);
 728   if (result != NULL) {
 729     assert(is_in_reserved(result), "result not in heap");
 730     return result;
 731   }
 732 
 733   assert(!soft_ref_policy()->should_clear_all_soft_refs(),
 734     "Flag should have been handled and cleared prior to this point");
 735 
 736   // What else?  We might try synchronous finalization later.  If the total
 737   // space available is large enough for the allocation, then a more
 738   // complete compaction phase than we've tried so far might be
 739   // appropriate.
 740   return NULL;
 741 }
 742 
 743 #ifdef ASSERT
 744 class AssertNonScavengableClosure: public OopClosure {
 745 public:
 746   virtual void do_oop(oop* p) {
 747     assert(!GenCollectedHeap::heap()->is_in_partial_collection(*p),
 748       "Referent should not be scavengable.");  }
 749   virtual void do_oop(narrowOop* p) { ShouldNotReachHere(); }
 750 };
 751 static AssertNonScavengableClosure assert_is_non_scavengable_closure;
 752 #endif
 753 
 754 void GenCollectedHeap::process_roots(ScanningOption so,
 755                                      OopClosure* strong_roots,
 756                                      CLDClosure* strong_cld_closure,
 757                                      CLDClosure* weak_cld_closure,
 758                                      CodeBlobToOopClosure* code_roots) {
 759   // General roots.
 760   assert(code_roots != NULL, "code root closure should always be set");
 761 
 762   ClassLoaderDataGraph::roots_cld_do(strong_cld_closure, weak_cld_closure);
 763 
 764   // Only process code roots from thread stacks if we aren't visiting the entire CodeCache anyway
 765   CodeBlobToOopClosure* roots_from_code_p = (so & SO_AllCodeCache) ? NULL : code_roots;
 766 
 767   Threads::oops_do(strong_roots, roots_from_code_p);
 768 
 769   OopStorageSet::strong_oops_do(strong_roots);
 770 
 771   if (so & SO_ScavengeCodeCache) {
 772     assert(code_roots != NULL, "must supply closure for code cache");
 773 
 774     // We only visit parts of the CodeCache when scavenging.
 775     ScavengableNMethods::nmethods_do(code_roots);
 776   }
 777   if (so & SO_AllCodeCache) {
 778     assert(code_roots != NULL, "must supply closure for code cache");
 779 
 780     // CMSCollector uses this to do intermediate-strength collections.
 781     // We scan the entire code cache, since CodeCache::do_unloading is not called.
 782     CodeCache::blobs_do(code_roots);
 783   }
 784   // Verify that the code cache contents are not subject to
 785   // movement by a scavenging collection.
 786   DEBUG_ONLY(CodeBlobToOopClosure assert_code_is_non_scavengable(&assert_is_non_scavengable_closure, !CodeBlobToOopClosure::FixRelocations));
 787   DEBUG_ONLY(ScavengableNMethods::asserted_non_scavengable_nmethods_do(&assert_code_is_non_scavengable));
 788 }
 789 
 790 void GenCollectedHeap::full_process_roots(bool is_adjust_phase,
 791                                           ScanningOption so,
 792                                           bool only_strong_roots,
 793                                           OopClosure* root_closure,
 794                                           CLDClosure* cld_closure) {
 795   MarkingCodeBlobClosure mark_code_closure(root_closure, is_adjust_phase);
 796   CLDClosure* weak_cld_closure = only_strong_roots ? NULL : cld_closure;
 797 
 798   process_roots(so, root_closure, cld_closure, weak_cld_closure, &mark_code_closure);
 799 }
 800 
 801 void GenCollectedHeap::gen_process_weak_roots(OopClosure* root_closure) {
 802   WeakProcessor::oops_do(root_closure);
 803 }
 804 
 805 bool GenCollectedHeap::no_allocs_since_save_marks() {
 806   return _young_gen->no_allocs_since_save_marks() &&
 807          _old_gen->no_allocs_since_save_marks();
 808 }
 809 
 810 bool GenCollectedHeap::supports_inline_contig_alloc() const {
 811   return _young_gen->supports_inline_contig_alloc();
 812 }
 813 
 814 HeapWord* volatile* GenCollectedHeap::top_addr() const {
 815   return _young_gen->top_addr();
 816 }
 817 
 818 HeapWord** GenCollectedHeap::end_addr() const {
 819   return _young_gen->end_addr();
 820 }
 821 
 822 // public collection interfaces
 823 
 824 void GenCollectedHeap::collect(GCCause::Cause cause) {
 825   if ((cause == GCCause::_wb_young_gc) ||
 826       (cause == GCCause::_gc_locker)) {
 827     // Young collection for WhiteBox or GCLocker.
 828     collect(cause, YoungGen);
 829   } else {
 830 #ifdef ASSERT
 831   if (cause == GCCause::_scavenge_alot) {
 832     // Young collection only.
 833     collect(cause, YoungGen);
 834   } else {
 835     // Stop-the-world full collection.
 836     collect(cause, OldGen);
 837   }
 838 #else
 839     // Stop-the-world full collection.
 840     collect(cause, OldGen);
 841 #endif
 842   }
 843 }
 844 
 845 void GenCollectedHeap::collect(GCCause::Cause cause, GenerationType max_generation) {
 846   // The caller doesn't have the Heap_lock
 847   assert(!Heap_lock->owned_by_self(), "this thread should not own the Heap_lock");
 848   MutexLocker ml(Heap_lock);
 849   collect_locked(cause, max_generation);
 850 }
 851 
 852 void GenCollectedHeap::collect_locked(GCCause::Cause cause) {
 853   // The caller has the Heap_lock
 854   assert(Heap_lock->owned_by_self(), "this thread should own the Heap_lock");
 855   collect_locked(cause, OldGen);
 856 }
 857 
 858 // this is the private collection interface
 859 // The Heap_lock is expected to be held on entry.
 860 
 861 void GenCollectedHeap::collect_locked(GCCause::Cause cause, GenerationType max_generation) {
 862   // Read the GC count while holding the Heap_lock
 863   unsigned int gc_count_before      = total_collections();
 864   unsigned int full_gc_count_before = total_full_collections();
 865 
 866   if (GCLocker::should_discard(cause, gc_count_before)) {
 867     return;
 868   }
 869 
 870   {
 871     MutexUnlocker mu(Heap_lock);  // give up heap lock, execute gets it back
 872     VM_GenCollectFull op(gc_count_before, full_gc_count_before,
 873                          cause, max_generation);
 874     VMThread::execute(&op);
 875   }
 876 }
 877 
 878 void GenCollectedHeap::do_full_collection(bool clear_all_soft_refs) {
 879    do_full_collection(clear_all_soft_refs, OldGen);
 880 }
 881 
 882 void GenCollectedHeap::do_full_collection(bool clear_all_soft_refs,
 883                                           GenerationType last_generation) {
 884   do_collection(true,                   // full
 885                 clear_all_soft_refs,    // clear_all_soft_refs
 886                 0,                      // size
 887                 false,                  // is_tlab
 888                 last_generation);       // last_generation
 889   // Hack XXX FIX ME !!!
 890   // A scavenge may not have been attempted, or may have
 891   // been attempted and failed, because the old gen was too full
 892   if (gc_cause() == GCCause::_gc_locker && incremental_collection_failed()) {
 893     log_debug(gc, jni)("GC locker: Trying a full collection because scavenge failed");
 894     // This time allow the old gen to be collected as well
 895     do_collection(true,                // full
 896                   clear_all_soft_refs, // clear_all_soft_refs
 897                   0,                   // size
 898                   false,               // is_tlab
 899                   OldGen);             // last_generation
 900   }
 901 }
 902 
 903 bool GenCollectedHeap::is_in_young(oop p) {
 904   bool result = cast_from_oop<HeapWord*>(p) < _old_gen->reserved().start();
 905   assert(result == _young_gen->is_in_reserved(p),
 906          "incorrect test - result=%d, p=" INTPTR_FORMAT, result, p2i((void*)p));
 907   return result;
 908 }
 909 
 910 // Returns "TRUE" iff "p" points into the committed areas of the heap.
 911 bool GenCollectedHeap::is_in(const void* p) const {
 912   return _young_gen->is_in(p) || _old_gen->is_in(p);
 913 }
 914 
 915 #ifdef ASSERT
 916 // Don't implement this by using is_in_young().  This method is used
 917 // in some cases to check that is_in_young() is correct.
 918 bool GenCollectedHeap::is_in_partial_collection(const void* p) {
 919   assert(is_in_reserved(p) || p == NULL,
 920     "Does not work if address is non-null and outside of the heap");
 921   return p < _young_gen->reserved().end() && p != NULL;
 922 }
 923 #endif
 924 
 925 void GenCollectedHeap::oop_iterate(OopIterateClosure* cl) {
 926   _young_gen->oop_iterate(cl);
 927   _old_gen->oop_iterate(cl);
 928 }
 929 
 930 void GenCollectedHeap::object_iterate(ObjectClosure* cl) {
 931   _young_gen->object_iterate(cl);
 932   _old_gen->object_iterate(cl);
 933 }
 934 
 935 Space* GenCollectedHeap::space_containing(const void* addr) const {
 936   Space* res = _young_gen->space_containing(addr);
 937   if (res != NULL) {
 938     return res;
 939   }
 940   res = _old_gen->space_containing(addr);
 941   assert(res != NULL, "Could not find containing space");
 942   return res;
 943 }
 944 
 945 HeapWord* GenCollectedHeap::block_start(const void* addr) const {
 946   assert(is_in_reserved(addr), "block_start of address outside of heap");
 947   if (_young_gen->is_in_reserved(addr)) {
 948     assert(_young_gen->is_in(addr), "addr should be in allocated part of generation");
 949     return _young_gen->block_start(addr);
 950   }
 951 
 952   assert(_old_gen->is_in_reserved(addr), "Some generation should contain the address");
 953   assert(_old_gen->is_in(addr), "addr should be in allocated part of generation");
 954   return _old_gen->block_start(addr);
 955 }
 956 
 957 bool GenCollectedHeap::block_is_obj(const HeapWord* addr) const {
 958   assert(is_in_reserved(addr), "block_is_obj of address outside of heap");
 959   assert(block_start(addr) == addr, "addr must be a block start");
 960   if (_young_gen->is_in_reserved(addr)) {
 961     return _young_gen->block_is_obj(addr);
 962   }
 963 
 964   assert(_old_gen->is_in_reserved(addr), "Some generation should contain the address");
 965   return _old_gen->block_is_obj(addr);
 966 }
 967 
 968 size_t GenCollectedHeap::tlab_capacity(Thread* thr) const {
 969   assert(!_old_gen->supports_tlab_allocation(), "Old gen supports TLAB allocation?!");
 970   assert(_young_gen->supports_tlab_allocation(), "Young gen doesn't support TLAB allocation?!");
 971   return _young_gen->tlab_capacity();
 972 }
 973 
 974 size_t GenCollectedHeap::tlab_used(Thread* thr) const {
 975   assert(!_old_gen->supports_tlab_allocation(), "Old gen supports TLAB allocation?!");
 976   assert(_young_gen->supports_tlab_allocation(), "Young gen doesn't support TLAB allocation?!");
 977   return _young_gen->tlab_used();
 978 }
 979 
 980 size_t GenCollectedHeap::unsafe_max_tlab_alloc(Thread* thr) const {
 981   assert(!_old_gen->supports_tlab_allocation(), "Old gen supports TLAB allocation?!");
 982   assert(_young_gen->supports_tlab_allocation(), "Young gen doesn't support TLAB allocation?!");
 983   return _young_gen->unsafe_max_tlab_alloc();
 984 }
 985 
 986 HeapWord* GenCollectedHeap::allocate_new_tlab(size_t min_size,
 987                                               size_t requested_size,
 988                                               size_t* actual_size) {
 989   bool gc_overhead_limit_was_exceeded;
 990   HeapWord* result = mem_allocate_work(requested_size /* size */,
 991                                        true /* is_tlab */,
 992                                        &gc_overhead_limit_was_exceeded);
 993   if (result != NULL) {
 994     *actual_size = requested_size;
 995   }
 996 
 997   return result;
 998 }
 999 
1000 // Requires "*prev_ptr" to be non-NULL.  Deletes and a block of minimal size
1001 // from the list headed by "*prev_ptr".
1002 static ScratchBlock *removeSmallestScratch(ScratchBlock **prev_ptr) {
1003   bool first = true;
1004   size_t min_size = 0;   // "first" makes this conceptually infinite.
1005   ScratchBlock **smallest_ptr, *smallest;
1006   ScratchBlock  *cur = *prev_ptr;
1007   while (cur) {
1008     assert(*prev_ptr == cur, "just checking");
1009     if (first || cur->num_words < min_size) {
1010       smallest_ptr = prev_ptr;
1011       smallest     = cur;
1012       min_size     = smallest->num_words;
1013       first        = false;
1014     }
1015     prev_ptr = &cur->next;
1016     cur     =  cur->next;
1017   }
1018   smallest      = *smallest_ptr;
1019   *smallest_ptr = smallest->next;
1020   return smallest;
1021 }
1022 
1023 // Sort the scratch block list headed by res into decreasing size order,
1024 // and set "res" to the result.
1025 static void sort_scratch_list(ScratchBlock*& list) {
1026   ScratchBlock* sorted = NULL;
1027   ScratchBlock* unsorted = list;
1028   while (unsorted) {
1029     ScratchBlock *smallest = removeSmallestScratch(&unsorted);
1030     smallest->next  = sorted;
1031     sorted          = smallest;
1032   }
1033   list = sorted;
1034 }
1035 
1036 ScratchBlock* GenCollectedHeap::gather_scratch(Generation* requestor,
1037                                                size_t max_alloc_words) {
1038   ScratchBlock* res = NULL;
1039   _young_gen->contribute_scratch(res, requestor, max_alloc_words);
1040   _old_gen->contribute_scratch(res, requestor, max_alloc_words);
1041   sort_scratch_list(res);
1042   return res;
1043 }
1044 
1045 void GenCollectedHeap::release_scratch() {
1046   _young_gen->reset_scratch();
1047   _old_gen->reset_scratch();
1048 }
1049 
1050 class GenPrepareForVerifyClosure: public GenCollectedHeap::GenClosure {
1051   void do_generation(Generation* gen) {
1052     gen->prepare_for_verify();
1053   }
1054 };
1055 
1056 void GenCollectedHeap::prepare_for_verify() {
1057   ensure_parsability(false);        // no need to retire TLABs
1058   GenPrepareForVerifyClosure blk;
1059   generation_iterate(&blk, false);
1060 }
1061 
1062 void GenCollectedHeap::generation_iterate(GenClosure* cl,
1063                                           bool old_to_young) {
1064   if (old_to_young) {
1065     cl->do_generation(_old_gen);
1066     cl->do_generation(_young_gen);
1067   } else {
1068     cl->do_generation(_young_gen);
1069     cl->do_generation(_old_gen);
1070   }
1071 }
1072 
1073 bool GenCollectedHeap::is_maximal_no_gc() const {
1074   return _young_gen->is_maximal_no_gc() && _old_gen->is_maximal_no_gc();
1075 }
1076 
1077 void GenCollectedHeap::save_marks() {
1078   _young_gen->save_marks();
1079   _old_gen->save_marks();
1080 }
1081 
1082 GenCollectedHeap* GenCollectedHeap::heap() {
1083   // SerialHeap is the only subtype of GenCollectedHeap.
1084   return named_heap<GenCollectedHeap>(CollectedHeap::Serial);
1085 }
1086 
1087 #if INCLUDE_SERIALGC
1088 void GenCollectedHeap::prepare_for_compaction() {
1089   // Start by compacting into same gen.
1090   CompactPoint cp(_old_gen);
1091   _forwarding->clear();
1092   _old_gen->prepare_for_compaction(&cp);
1093   _young_gen->prepare_for_compaction(&cp);
1094 }
1095 #endif // INCLUDE_SERIALGC
1096 
1097 void GenCollectedHeap::verify(VerifyOption option /* ignored */) {
1098   log_debug(gc, verify)("%s", _old_gen->name());
1099   _old_gen->verify();
1100 
1101   log_debug(gc, verify)("%s", _old_gen->name());
1102   _young_gen->verify();
1103 
1104   log_debug(gc, verify)("RemSet");
1105   rem_set()->verify();
1106 }
1107 
1108 void GenCollectedHeap::print_on(outputStream* st) const {
1109   if (_young_gen != NULL) {
1110     _young_gen->print_on(st);
1111   }
1112   if (_old_gen != NULL) {
1113     _old_gen->print_on(st);
1114   }
1115   MetaspaceUtils::print_on(st);
1116 }
1117 
1118 void GenCollectedHeap::gc_threads_do(ThreadClosure* tc) const {
1119 }
1120 
1121 bool GenCollectedHeap::print_location(outputStream* st, void* addr) const {
1122   return BlockLocationPrinter<GenCollectedHeap>::print_location(st, addr);
1123 }
1124 
1125 void GenCollectedHeap::print_tracing_info() const {
1126   if (log_is_enabled(Debug, gc, heap, exit)) {
1127     LogStreamHandle(Debug, gc, heap, exit) lsh;
1128     _young_gen->print_summary_info_on(&lsh);
1129     _old_gen->print_summary_info_on(&lsh);
1130   }
1131 }
1132 
1133 void GenCollectedHeap::print_heap_change(const PreGenGCValues& pre_gc_values) const {
1134   const DefNewGeneration* const def_new_gen = (DefNewGeneration*) young_gen();
1135 
1136   log_info(gc, heap)(HEAP_CHANGE_FORMAT" "
1137                      HEAP_CHANGE_FORMAT" "
1138                      HEAP_CHANGE_FORMAT,
1139                      HEAP_CHANGE_FORMAT_ARGS(def_new_gen->short_name(),
1140                                              pre_gc_values.young_gen_used(),
1141                                              pre_gc_values.young_gen_capacity(),
1142                                              def_new_gen->used(),
1143                                              def_new_gen->capacity()),
1144                      HEAP_CHANGE_FORMAT_ARGS("Eden",
1145                                              pre_gc_values.eden_used(),
1146                                              pre_gc_values.eden_capacity(),
1147                                              def_new_gen->eden()->used(),
1148                                              def_new_gen->eden()->capacity()),
1149                      HEAP_CHANGE_FORMAT_ARGS("From",
1150                                              pre_gc_values.from_used(),
1151                                              pre_gc_values.from_capacity(),
1152                                              def_new_gen->from()->used(),
1153                                              def_new_gen->from()->capacity()));
1154   log_info(gc, heap)(HEAP_CHANGE_FORMAT,
1155                      HEAP_CHANGE_FORMAT_ARGS(old_gen()->short_name(),
1156                                              pre_gc_values.old_gen_used(),
1157                                              pre_gc_values.old_gen_capacity(),
1158                                              old_gen()->used(),
1159                                              old_gen()->capacity()));
1160   MetaspaceUtils::print_metaspace_change(pre_gc_values.metaspace_sizes());
1161 }
1162 
1163 class GenGCPrologueClosure: public GenCollectedHeap::GenClosure {
1164  private:
1165   bool _full;
1166  public:
1167   void do_generation(Generation* gen) {
1168     gen->gc_prologue(_full);
1169   }
1170   GenGCPrologueClosure(bool full) : _full(full) {};
1171 };
1172 
1173 void GenCollectedHeap::gc_prologue(bool full) {
1174   assert(InlineCacheBuffer::is_empty(), "should have cleaned up ICBuffer");
1175 
1176   // Fill TLAB's and such
1177   ensure_parsability(true);   // retire TLABs
1178 
1179   // Walk generations
1180   GenGCPrologueClosure blk(full);
1181   generation_iterate(&blk, false);  // not old-to-young.
1182 };
1183 
1184 class GenGCEpilogueClosure: public GenCollectedHeap::GenClosure {
1185  private:
1186   bool _full;
1187  public:
1188   void do_generation(Generation* gen) {
1189     gen->gc_epilogue(_full);
1190   }
1191   GenGCEpilogueClosure(bool full) : _full(full) {};
1192 };
1193 
1194 void GenCollectedHeap::gc_epilogue(bool full) {
1195 #if COMPILER2_OR_JVMCI
1196   assert(DerivedPointerTable::is_empty(), "derived pointer present");
1197   size_t actual_gap = pointer_delta((HeapWord*) (max_uintx-3), *(end_addr()));
1198   guarantee(!CompilerConfig::is_c2_or_jvmci_compiler_enabled() || actual_gap > (size_t)FastAllocateSizeLimit, "inline allocation wraps");
1199 #endif // COMPILER2_OR_JVMCI
1200 
1201   resize_all_tlabs();
1202 
1203   GenGCEpilogueClosure blk(full);
1204   generation_iterate(&blk, false);  // not old-to-young.
1205 
1206   MetaspaceCounters::update_performance_counters();
1207 };
1208 
1209 #ifndef PRODUCT
1210 class GenGCSaveTopsBeforeGCClosure: public GenCollectedHeap::GenClosure {
1211  private:
1212  public:
1213   void do_generation(Generation* gen) {
1214     gen->record_spaces_top();
1215   }
1216 };
1217 
1218 void GenCollectedHeap::record_gen_tops_before_GC() {
1219   if (ZapUnusedHeapArea) {
1220     GenGCSaveTopsBeforeGCClosure blk;
1221     generation_iterate(&blk, false);  // not old-to-young.
1222   }
1223 }
1224 #endif  // not PRODUCT
1225 
1226 class GenEnsureParsabilityClosure: public GenCollectedHeap::GenClosure {
1227  public:
1228   void do_generation(Generation* gen) {
1229     gen->ensure_parsability();
1230   }
1231 };
1232 
1233 void GenCollectedHeap::ensure_parsability(bool retire_tlabs) {
1234   CollectedHeap::ensure_parsability(retire_tlabs);
1235   GenEnsureParsabilityClosure ep_cl;
1236   generation_iterate(&ep_cl, false);
1237 }
1238 
1239 oop GenCollectedHeap::handle_failed_promotion(Generation* old_gen,
1240                                               oop obj,
1241                                               size_t obj_size) {
1242   guarantee(old_gen == _old_gen, "We only get here with an old generation");
1243   assert(obj_size == obj->size(), "bad obj_size passed in");
1244   HeapWord* result = NULL;
1245 
1246   result = old_gen->expand_and_allocate(obj_size, false);
1247 
1248   if (result != NULL) {
1249     Copy::aligned_disjoint_words(cast_from_oop<HeapWord*>(obj), result, obj_size);
1250   }
1251   return cast_to_oop(result);
1252 }