1 /*
   2  * Copyright (c) 1997, 2026, 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 "cds/aotCacheAccess.hpp"
  26 #include "code/aotCodeCache.hpp"
  27 #include "code/codeBlob.hpp"
  28 #include "code/codeCache.hpp"
  29 #include "code/codeHeapState.hpp"
  30 #include "code/compiledIC.hpp"
  31 #include "code/dependencies.hpp"
  32 #include "code/dependencyContext.hpp"
  33 #include "code/nmethod.hpp"
  34 #include "code/pcDesc.hpp"
  35 #include "compiler/compilationPolicy.hpp"
  36 #include "compiler/compileBroker.hpp"
  37 #include "compiler/compilerDefinitions.inline.hpp"
  38 #include "compiler/oopMap.hpp"
  39 #include "gc/shared/barrierSetNMethod.hpp"
  40 #include "gc/shared/classUnloadingContext.hpp"
  41 #include "gc/shared/collectedHeap.hpp"
  42 #include "jfr/jfrEvents.hpp"
  43 #include "jvm_io.h"
  44 #include "logging/log.hpp"
  45 #include "logging/logStream.hpp"
  46 #include "memory/allocation.inline.hpp"
  47 #include "memory/iterator.hpp"
  48 #include "memory/memoryReserver.hpp"
  49 #include "memory/resourceArea.hpp"
  50 #include "memory/universe.hpp"
  51 #include "oops/method.inline.hpp"
  52 #include "oops/objArrayOop.hpp"
  53 #include "oops/oop.inline.hpp"
  54 #include "oops/verifyOopClosure.hpp"
  55 #include "runtime/arguments.hpp"
  56 #include "runtime/atomicAccess.hpp"
  57 #include "runtime/deoptimization.hpp"
  58 #include "runtime/globals_extension.hpp"
  59 #include "runtime/handles.inline.hpp"
  60 #include "runtime/icache.hpp"
  61 #include "runtime/init.hpp"
  62 #include "runtime/java.hpp"
  63 #include "runtime/mutexLocker.hpp"
  64 #include "runtime/os.inline.hpp"
  65 #include "runtime/safepointVerifiers.hpp"
  66 #include "runtime/vmThread.hpp"
  67 #include "sanitizers/leak.hpp"
  68 #include "services/memoryService.hpp"
  69 #include "utilities/align.hpp"
  70 #include "utilities/vmError.hpp"
  71 #include "utilities/xmlstream.hpp"
  72 #ifdef COMPILER1
  73 #include "c1/c1_Compilation.hpp"
  74 #include "c1/c1_Compiler.hpp"
  75 #endif
  76 #ifdef COMPILER2
  77 #include "opto/c2compiler.hpp"
  78 #include "opto/compile.hpp"
  79 #include "opto/node.hpp"
  80 #endif
  81 
  82 // Helper class for printing in CodeCache
  83 class CodeBlob_sizes {
  84  private:
  85   int count;
  86   int total_size;
  87   int header_size;
  88   int code_size;
  89   int stub_size;
  90   int relocation_size;
  91   int scopes_oop_size;
  92   int scopes_metadata_size;
  93   int scopes_data_size;
  94   int scopes_pcs_size;
  95 
  96  public:
  97   CodeBlob_sizes() {
  98     count            = 0;
  99     total_size       = 0;
 100     header_size      = 0;
 101     code_size        = 0;
 102     stub_size        = 0;
 103     relocation_size  = 0;
 104     scopes_oop_size  = 0;
 105     scopes_metadata_size  = 0;
 106     scopes_data_size = 0;
 107     scopes_pcs_size  = 0;
 108   }
 109 
 110   int total() const                              { return total_size; }
 111   bool is_empty() const                          { return count == 0; }
 112 
 113   void print(const char* title) const {
 114     if (is_empty()) {
 115       tty->print_cr(" #%d %s = %dK",
 116                     count,
 117                     title,
 118                     total()                 / (int)K);
 119     } else {
 120       tty->print_cr(" #%d %s = %dK (hdr %dK %d%%, loc %dK %d%%, code %dK %d%%, stub %dK %d%%, [oops %dK %d%%, metadata %dK %d%%, data %dK %d%%, pcs %dK %d%%])",
 121                     count,
 122                     title,
 123                     total()                 / (int)K,
 124                     header_size             / (int)K,
 125                     header_size             * 100 / total_size,
 126                     relocation_size         / (int)K,
 127                     relocation_size         * 100 / total_size,
 128                     code_size               / (int)K,
 129                     code_size               * 100 / total_size,
 130                     stub_size               / (int)K,
 131                     stub_size               * 100 / total_size,
 132                     scopes_oop_size         / (int)K,
 133                     scopes_oop_size         * 100 / total_size,
 134                     scopes_metadata_size    / (int)K,
 135                     scopes_metadata_size    * 100 / total_size,
 136                     scopes_data_size        / (int)K,
 137                     scopes_data_size        * 100 / total_size,
 138                     scopes_pcs_size         / (int)K,
 139                     scopes_pcs_size         * 100 / total_size);
 140     }
 141   }
 142 
 143   void add(CodeBlob* cb) {
 144     count++;
 145     total_size       += cb->size();
 146     header_size      += cb->header_size();
 147     relocation_size  += cb->relocation_size();
 148     if (cb->is_nmethod()) {
 149       nmethod* nm = cb->as_nmethod_or_null();
 150       code_size        += nm->insts_size();
 151       stub_size        += nm->stub_size();
 152 
 153       scopes_oop_size  += nm->oops_size();
 154       scopes_metadata_size  += nm->metadata_size();
 155       scopes_data_size += nm->scopes_data_size();
 156       scopes_pcs_size  += nm->scopes_pcs_size();
 157     } else {
 158       code_size        += cb->code_size();
 159     }
 160   }
 161 };
 162 
 163 // Iterate over all CodeHeaps
 164 #define FOR_ALL_HEAPS(heap) for (GrowableArrayIterator<CodeHeap*> heap = _heaps->begin(); heap != _heaps->end(); ++heap)
 165 #define FOR_ALL_ALLOCABLE_HEAPS(heap) for (GrowableArrayIterator<CodeHeap*> heap = _allocable_heaps->begin(); heap != _allocable_heaps->end(); ++heap)
 166 
 167 // Iterate over all CodeBlobs (cb) on the given CodeHeap
 168 #define FOR_ALL_BLOBS(cb, heap) for (CodeBlob* cb = first_blob(heap); cb != nullptr; cb = next_blob(heap, cb))
 169 
 170 address CodeCache::_low_bound = nullptr;
 171 address CodeCache::_high_bound = nullptr;
 172 volatile int CodeCache::_number_of_nmethods_with_dependencies = 0;
 173 ExceptionCache* volatile CodeCache::_exception_cache_purge_list = nullptr;
 174 
 175 static ReservedSpace _cds_code_space;
 176 
 177 // Initialize arrays of CodeHeap subsets
 178 GrowableArray<CodeHeap*>* CodeCache::_heaps = new(mtCode) GrowableArray<CodeHeap*> (static_cast<int>(CodeBlobType::All), mtCode);
 179 GrowableArray<CodeHeap*>* CodeCache::_nmethod_heaps = new(mtCode) GrowableArray<CodeHeap*> (static_cast<int>(CodeBlobType::All), mtCode);
 180 GrowableArray<CodeHeap*>* CodeCache::_allocable_heaps = new(mtCode) GrowableArray<CodeHeap*> (static_cast<int>(CodeBlobType::All), mtCode);
 181 
 182 static void check_min_size(const char* codeheap, size_t size, size_t required_size) {
 183   if (size < required_size) {
 184     log_debug(codecache)("Code heap (%s) size %zuK below required minimal size %zuK",
 185                          codeheap, size/K, required_size/K);
 186     err_msg title("Not enough space in %s to run VM", codeheap);
 187     err_msg message("%zuK < %zuK", size/K, required_size/K);
 188     vm_exit_during_initialization(title, message);
 189   }
 190 }
 191 
 192 struct CodeHeapInfo {
 193   size_t size;
 194   bool set;
 195   bool enabled;
 196 };
 197 
 198 static void set_size_of_unset_code_heap(CodeHeapInfo* heap, size_t available_size, size_t used_size, size_t min_size) {
 199   assert(!heap->set, "sanity");
 200   heap->size = (available_size > (used_size + min_size)) ? (available_size - used_size) : min_size;
 201 }
 202 
 203 void CodeCache::initialize_heaps() {
 204   CodeHeapInfo non_nmethod = {NonNMethodCodeHeapSize, FLAG_IS_CMDLINE(NonNMethodCodeHeapSize), true};
 205   CodeHeapInfo profiled = {ProfiledCodeHeapSize, FLAG_IS_CMDLINE(ProfiledCodeHeapSize), true};
 206   CodeHeapInfo non_profiled = {NonProfiledCodeHeapSize, FLAG_IS_CMDLINE(NonProfiledCodeHeapSize), true};
 207 
 208   const bool cache_size_set   = FLAG_IS_CMDLINE(ReservedCodeCacheSize);
 209   const size_t ps             = page_size(false, 8);
 210   const size_t min_size       = MAX2(os::vm_allocation_granularity(), ps);
 211   const size_t min_cache_size = CodeCacheMinimumUseSpace DEBUG_ONLY(* 3); // Make sure we have enough space for VM internal code
 212   size_t cache_size           = align_up(ReservedCodeCacheSize, min_size);
 213 
 214   // Prerequisites
 215   if (!heap_available(CodeBlobType::MethodProfiled)) {
 216     // For compatibility reasons, disabled tiered compilation overrides
 217     // segment size even if it is set explicitly.
 218     non_profiled.size += profiled.size;
 219     // Profiled code heap is not available, forcibly set size to 0
 220     profiled.size = 0;
 221     profiled.set = true;
 222     profiled.enabled = false;
 223   }
 224 
 225   assert(heap_available(CodeBlobType::MethodNonProfiled), "MethodNonProfiled heap is always available for segmented code heap");
 226 
 227   size_t compiler_buffer_size = 0;
 228   COMPILER1_PRESENT(compiler_buffer_size += CompilationPolicy::c1_count() * Compiler::code_buffer_size());
 229   COMPILER2_PRESENT(compiler_buffer_size += CompilationPolicy::c2_count() * C2Compiler::initial_code_buffer_size());
 230 
 231   // During AOT assembly phase more compiler threads are used
 232   // and C2 temp buffer is bigger.
 233   // But due to rounding issue the total code cache size could be smaller
 234   // than during production run. We can not use AOT code in such case
 235   // because branch and call instructions will be incorrect.
 236   //
 237   // Increase code cache size to guarantee that total size
 238   // will be bigger during assembly phase.
 239   if (AOTCodeCache::maybe_dumping_code()) {
 240     cache_size += align_up(compiler_buffer_size, min_size);
 241     cache_size = MIN2(cache_size, CODE_CACHE_SIZE_LIMIT);
 242   }
 243 
 244   if (!non_nmethod.set) {
 245     non_nmethod.size += compiler_buffer_size;
 246   }
 247 
 248   if (!profiled.set && !non_profiled.set) {
 249     non_profiled.size = profiled.size = (cache_size > non_nmethod.size + 2 * min_size) ?
 250                                         (cache_size - non_nmethod.size) / 2 : min_size;
 251   }
 252 
 253   if (profiled.set && !non_profiled.set) {
 254     set_size_of_unset_code_heap(&non_profiled, cache_size, non_nmethod.size + profiled.size, min_size);
 255   }
 256 
 257   if (!profiled.set && non_profiled.set) {
 258     set_size_of_unset_code_heap(&profiled, cache_size, non_nmethod.size + non_profiled.size, min_size);
 259   }
 260 
 261   // Compatibility.
 262   size_t non_nmethod_min_size = min_cache_size + compiler_buffer_size;
 263   if (!non_nmethod.set && profiled.set && non_profiled.set) {
 264     set_size_of_unset_code_heap(&non_nmethod, cache_size, profiled.size + non_profiled.size, non_nmethod_min_size);
 265   }
 266 
 267   // Note: if large page support is enabled, min_size is at least the large
 268   // page size. This ensures that the code cache is covered by large pages.
 269   non_nmethod.size = align_up(non_nmethod.size, min_size);
 270   profiled.size = align_up(profiled.size, min_size);
 271   non_profiled.size = align_up(non_profiled.size, min_size);
 272 
 273   size_t aligned_total = non_nmethod.size + profiled.size + non_profiled.size;
 274   if (!cache_size_set) {
 275     // If ReservedCodeCacheSize is explicitly set and exceeds CODE_CACHE_SIZE_LIMIT,
 276     // it is rejected by flag validation elsewhere. Here we only handle the case
 277     // where ReservedCodeCacheSize is not set explicitly, but the computed segmented
 278     // sizes (after alignment) exceed the platform limit.
 279     if (aligned_total > CODE_CACHE_SIZE_LIMIT) {
 280       err_msg message("ReservedCodeCacheSize (%zuK), Max (%zuK)."
 281                       "Segments: NonNMethod (%zuK), NonProfiled (%zuK), Profiled (%zuK).",
 282                       aligned_total/K, CODE_CACHE_SIZE_LIMIT/K,
 283                       non_nmethod.size/K, non_profiled.size/K, profiled.size/K);
 284       vm_exit_during_initialization("Code cache size exceeds platform limit", message);
 285     }
 286     if (aligned_total != cache_size) {
 287       log_info(codecache)("ReservedCodeCache size %zuK changed to total segments size NonNMethod "
 288                           "%zuK NonProfiled %zuK Profiled %zuK = %zuK",
 289                           cache_size/K, non_nmethod.size/K, non_profiled.size/K, profiled.size/K, aligned_total/K);
 290       // Adjust ReservedCodeCacheSize as necessary because it was not set explicitly
 291       cache_size = aligned_total;
 292     }
 293   } else {
 294     check_min_size("reserved code cache", cache_size, min_cache_size);
 295     // ReservedCodeCacheSize was set explicitly, so treat it as a hard cap.
 296     // If alignment causes the total to exceed the cap, shrink unset heaps
 297     // in min_size steps, never below their minimum sizes.
 298     //
 299     // A total smaller than cache_size typically happens when all segment sizes
 300     // are explicitly set. In that case there is nothing to adjust, so we
 301     // only validate the sizes.
 302     if (aligned_total > cache_size) {
 303       size_t delta = (aligned_total - cache_size) / min_size;
 304       while (delta > 0) {
 305         size_t start_delta = delta;
 306         // Do not shrink the non-nmethod heap here: running out of non-nmethod space
 307         // is more critical and may lead to unrecoverable VM errors.
 308         if (non_profiled.enabled && !non_profiled.set && non_profiled.size > min_size) {
 309           non_profiled.size -= min_size;
 310           if (--delta == 0) break;
 311         }
 312         if (profiled.enabled && !profiled.set && profiled.size > min_size) {
 313           profiled.size -= min_size;
 314           delta--;
 315         }
 316         if (delta == start_delta) {
 317           break;
 318         }
 319       }
 320       aligned_total = non_nmethod.size + profiled.size + non_profiled.size;
 321     }
 322   }
 323 
 324   log_debug(codecache)("Initializing code heaps ReservedCodeCache %zuK NonNMethod %zuK"
 325                        " NonProfiled %zuK Profiled %zuK",
 326                        cache_size/K, non_nmethod.size/K, non_profiled.size/K, profiled.size/K);
 327 
 328   // Validation
 329   // Check minimal required sizes
 330   check_min_size("non-nmethod code heap", non_nmethod.size, non_nmethod_min_size);
 331   if (profiled.enabled) {
 332     check_min_size("profiled code heap", profiled.size, min_size);
 333   }
 334   if (non_profiled.enabled) { // non_profiled.enabled is always ON for segmented code heap, leave it checked for clarity
 335     check_min_size("non-profiled code heap", non_profiled.size, min_size);
 336   }
 337 
 338   // ReservedCodeCacheSize was set explicitly, so report an error and abort if it doesn't match the segment sizes
 339   if (aligned_total != cache_size && cache_size_set) {
 340     err_msg message("NonNMethodCodeHeapSize (%zuK)", non_nmethod.size/K);
 341     if (profiled.enabled) {
 342       message.append(" + ProfiledCodeHeapSize (%zuK)", profiled.size/K);
 343     }
 344     if (non_profiled.enabled) {
 345       message.append(" + NonProfiledCodeHeapSize (%zuK)", non_profiled.size/K);
 346     }
 347     message.append(" = %zuK", aligned_total/K);
 348     message.append((aligned_total > cache_size) ? " is greater than " : " is less than ");
 349     message.append("ReservedCodeCacheSize (%zuK).", cache_size/K);
 350 
 351     vm_exit_during_initialization("Invalid code heap sizes", message);
 352   }
 353 
 354   // Compatibility. Print warning if using large pages but not able to use the size given
 355   if (UseLargePages) {
 356     const size_t lg_ps = page_size(false, 1);
 357     if (ps < lg_ps) {
 358       log_warning(codecache)("Code cache size too small for " PROPERFMT " pages. "
 359                              "Reverting to smaller page size (" PROPERFMT ").",
 360                              PROPERFMTARGS(lg_ps), PROPERFMTARGS(ps));
 361     }
 362   }
 363 
 364   FLAG_SET_ERGO(NonNMethodCodeHeapSize, non_nmethod.size);
 365   FLAG_SET_ERGO(ProfiledCodeHeapSize, profiled.size);
 366   FLAG_SET_ERGO(NonProfiledCodeHeapSize, non_profiled.size);
 367   FLAG_SET_ERGO(ReservedCodeCacheSize, cache_size);
 368 
 369   const size_t cds_code_size = 0;
 370   // FIXME: we should not increase CodeCache size - it affects branches.
 371   // Instead we need to create separate code heap in CodeCache for AOT code.
 372   // const size_t cds_code_size = align_up(AOTCacheAccess::get_aot_code_region_size(), min_size);
 373   // cache_size += cds_code_size;
 374 
 375   ReservedSpace rs = reserve_heap_memory(cache_size, ps);
 376 
 377   // Register CodeHeaps with LSan as we sometimes embed pointers to malloc memory.
 378   LSAN_REGISTER_ROOT_REGION(rs.base(), rs.size());
 379 
 380   size_t offset = 0;
 381   if (cds_code_size > 0) {
 382     // FIXME: use CodeHeapInfo for this hack ...
 383     _cds_code_space = rs.partition(offset, cds_code_size);
 384     offset += cds_code_size;
 385   }
 386 
 387   if (profiled.enabled) {
 388     ReservedSpace profiled_space = rs.partition(offset, profiled.size);
 389     offset += profiled.size;
 390     // Tier 2 and tier 3 (profiled) methods
 391     add_heap(profiled_space, "CodeHeap 'profiled nmethods'", CodeBlobType::MethodProfiled);
 392   }
 393 
 394   ReservedSpace non_method_space = rs.partition(offset, non_nmethod.size);
 395   offset += non_nmethod.size;
 396   // Non-nmethods (stubs, adapters, ...)
 397   add_heap(non_method_space, "CodeHeap 'non-nmethods'", CodeBlobType::NonNMethod);
 398 
 399   if (non_profiled.enabled) {
 400     ReservedSpace non_profiled_space  = rs.partition(offset, non_profiled.size);
 401     // Tier 1 and tier 4 (non-profiled) methods and native methods
 402     add_heap(non_profiled_space, "CodeHeap 'non-profiled nmethods'", CodeBlobType::MethodNonProfiled);
 403   }
 404 }
 405 
 406 void* CodeCache::map_aot_code() {
 407   if (_cds_code_space.size() > 0 && AOTCacheAccess::map_aot_code_region(_cds_code_space)) {
 408     return _cds_code_space.base();
 409   } else {
 410     return nullptr;
 411   }
 412 }
 413 
 414 size_t CodeCache::page_size(bool aligned, size_t min_pages) {
 415   return aligned ? os::page_size_for_region_aligned(ReservedCodeCacheSize, min_pages) :
 416                    os::page_size_for_region_unaligned(ReservedCodeCacheSize, min_pages);
 417 }
 418 
 419 ReservedSpace CodeCache::reserve_heap_memory(size_t size, size_t rs_ps) {
 420   // Align and reserve space for code cache
 421   const size_t rs_align = MAX2(rs_ps, os::vm_allocation_granularity());
 422   const size_t rs_size = align_up(size, rs_align);
 423 
 424   ReservedSpace rs = CodeMemoryReserver::reserve(rs_size, rs_align, rs_ps);
 425   if (!rs.is_reserved()) {
 426     vm_exit_during_initialization(err_msg("Could not reserve enough space for code cache (%zuK)",
 427                                           rs_size/K));
 428   }
 429 
 430   // Initialize bounds
 431   _low_bound = (address)rs.base();
 432   _high_bound = _low_bound + rs.size();
 433   return rs;
 434 }
 435 
 436 // Heaps available for allocation
 437 bool CodeCache::heap_available(CodeBlobType code_blob_type) {
 438   if (!SegmentedCodeCache) {
 439     // No segmentation: use a single code heap
 440     return (code_blob_type == CodeBlobType::All);
 441   } else if (CompilerConfig::is_interpreter_only()) {
 442     // Interpreter only: we don't need any method code heaps
 443     return (code_blob_type == CodeBlobType::NonNMethod);
 444   } else if (CompilerConfig::is_c1_profiling()) {
 445     // Tiered compilation: use all code heaps
 446     return (code_blob_type < CodeBlobType::All);
 447   } else {
 448     // No TieredCompilation: we only need the non-nmethod and non-profiled code heap
 449     return (code_blob_type == CodeBlobType::NonNMethod) ||
 450            (code_blob_type == CodeBlobType::MethodNonProfiled);
 451   }
 452 }
 453 
 454 const char* CodeCache::get_code_heap_flag_name(CodeBlobType code_blob_type) {
 455   switch(code_blob_type) {
 456   case CodeBlobType::NonNMethod:
 457     return "NonNMethodCodeHeapSize";
 458     break;
 459   case CodeBlobType::MethodNonProfiled:
 460     return "NonProfiledCodeHeapSize";
 461     break;
 462   case CodeBlobType::MethodProfiled:
 463     return "ProfiledCodeHeapSize";
 464     break;
 465   default:
 466     ShouldNotReachHere();
 467     return nullptr;
 468   }
 469 }
 470 
 471 int CodeCache::code_heap_compare(CodeHeap* const &lhs, CodeHeap* const &rhs) {
 472   if (lhs->code_blob_type() == rhs->code_blob_type()) {
 473     return (lhs > rhs) ? 1 : ((lhs < rhs) ? -1 : 0);
 474   } else {
 475     return static_cast<int>(lhs->code_blob_type()) - static_cast<int>(rhs->code_blob_type());
 476   }
 477 }
 478 
 479 void CodeCache::add_heap(CodeHeap* heap) {
 480   assert(!Universe::is_fully_initialized(), "late heap addition?");
 481 
 482   _heaps->insert_sorted<code_heap_compare>(heap);
 483 
 484   CodeBlobType type = heap->code_blob_type();
 485   if (code_blob_type_accepts_nmethod(type)) {
 486     _nmethod_heaps->insert_sorted<code_heap_compare>(heap);
 487   }
 488   if (code_blob_type_accepts_allocable(type)) {
 489     _allocable_heaps->insert_sorted<code_heap_compare>(heap);
 490   }
 491 }
 492 
 493 void CodeCache::add_heap(ReservedSpace rs, const char* name, CodeBlobType code_blob_type) {
 494   // Check if heap is needed
 495   if (!heap_available(code_blob_type)) {
 496     return;
 497   }
 498 
 499   // Create CodeHeap
 500   CodeHeap* heap = new CodeHeap(name, code_blob_type);
 501   add_heap(heap);
 502 
 503   // Reserve Space
 504   size_t size_initial = MIN2(InitialCodeCacheSize, rs.size());
 505   size_initial = align_up(size_initial, rs.page_size());
 506   if (!heap->reserve(rs, size_initial, CodeCacheSegmentSize)) {
 507     vm_exit_during_initialization(err_msg("Could not reserve enough space in %s (%zuK)",
 508                                           heap->name(), size_initial/K));
 509   }
 510 
 511   // Register the CodeHeap
 512   MemoryService::add_code_heap_memory_pool(heap, name);
 513 }
 514 
 515 CodeHeap* CodeCache::get_code_heap_containing(void* start) {
 516   FOR_ALL_HEAPS(heap) {
 517     if ((*heap)->contains(start)) {
 518       return *heap;
 519     }
 520   }
 521   return nullptr;
 522 }
 523 
 524 CodeHeap* CodeCache::get_code_heap(const void* cb) {
 525   assert(cb != nullptr, "CodeBlob is null");
 526   FOR_ALL_HEAPS(heap) {
 527     if ((*heap)->contains(cb)) {
 528       return *heap;
 529     }
 530   }
 531   ShouldNotReachHere();
 532   return nullptr;
 533 }
 534 
 535 CodeHeap* CodeCache::get_code_heap(CodeBlobType code_blob_type) {
 536   FOR_ALL_HEAPS(heap) {
 537     if ((*heap)->accepts(code_blob_type)) {
 538       return *heap;
 539     }
 540   }
 541   return nullptr;
 542 }
 543 
 544 CodeBlob* CodeCache::first_blob(CodeHeap* heap) {
 545   assert_locked_or_safepoint(CodeCache_lock);
 546   assert(heap != nullptr, "heap is null");
 547   return (CodeBlob*)heap->first();
 548 }
 549 
 550 CodeBlob* CodeCache::first_blob(CodeBlobType code_blob_type) {
 551   if (heap_available(code_blob_type)) {
 552     return first_blob(get_code_heap(code_blob_type));
 553   } else {
 554     return nullptr;
 555   }
 556 }
 557 
 558 CodeBlob* CodeCache::next_blob(CodeHeap* heap, CodeBlob* cb) {
 559   assert_locked_or_safepoint(CodeCache_lock);
 560   assert(heap != nullptr, "heap is null");
 561   return (CodeBlob*)heap->next(cb);
 562 }
 563 
 564 /**
 565  * Do not seize the CodeCache lock here--if the caller has not
 566  * already done so, we are going to lose bigtime, since the code
 567  * cache will contain a garbage CodeBlob until the caller can
 568  * run the constructor for the CodeBlob subclass he is busy
 569  * instantiating.
 570  */
 571 CodeBlob* CodeCache::allocate(uint size, CodeBlobType code_blob_type, bool handle_alloc_failure, CodeBlobType orig_code_blob_type) {
 572   assert_locked_or_safepoint(CodeCache_lock);
 573   assert(size > 0, "Code cache allocation request must be > 0");
 574   if (size == 0) {
 575     return nullptr;
 576   }
 577   CodeBlob* cb = nullptr;
 578 
 579   // Get CodeHeap for the given CodeBlobType
 580   CodeHeap* heap = get_code_heap(code_blob_type);
 581   assert(heap != nullptr, "heap is null");
 582 
 583   while (true) {
 584     cb = (CodeBlob*)heap->allocate(size);
 585     if (cb != nullptr) break;
 586     if (!heap->expand_by(CodeCacheExpansionSize)) {
 587       // Save original type for error reporting
 588       if (orig_code_blob_type == CodeBlobType::All) {
 589         orig_code_blob_type = code_blob_type;
 590       }
 591       // Expansion failed
 592       if (SegmentedCodeCache) {
 593         // Fallback solution: Try to store code in another code heap.
 594         // NonNMethod -> MethodNonProfiled -> MethodProfiled (-> MethodNonProfiled)
 595         CodeBlobType type = code_blob_type;
 596         switch (type) {
 597         case CodeBlobType::NonNMethod:
 598           type = CodeBlobType::MethodNonProfiled;
 599           break;
 600         case CodeBlobType::MethodNonProfiled:
 601           type = CodeBlobType::MethodProfiled;
 602           break;
 603         case CodeBlobType::MethodProfiled:
 604           // Avoid loop if we already tried that code heap
 605           if (type == orig_code_blob_type) {
 606             type = CodeBlobType::MethodNonProfiled;
 607           }
 608           break;
 609         default:
 610           break;
 611         }
 612         if (type != code_blob_type && type != orig_code_blob_type && heap_available(type)) {
 613           if (PrintCodeCacheExtension) {
 614             tty->print_cr("Extension of %s failed. Trying to allocate in %s.",
 615                           heap->name(), get_code_heap(type)->name());
 616           }
 617           return allocate(size, type, handle_alloc_failure, orig_code_blob_type);
 618         }
 619       }
 620       if (handle_alloc_failure) {
 621         MutexUnlocker mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
 622         CompileBroker::handle_full_code_cache(orig_code_blob_type);
 623       }
 624       return nullptr;
 625     } else {
 626       OrderAccess::release(); // ensure heap expansion is visible to an asynchronous observer (e.g. CodeHeapPool::get_memory_usage())
 627     }
 628     if (PrintCodeCacheExtension) {
 629       ResourceMark rm;
 630       if (_nmethod_heaps->length() >= 1) {
 631         tty->print("%s", heap->name());
 632       } else {
 633         tty->print("CodeCache");
 634       }
 635       tty->print_cr(" extended to [" INTPTR_FORMAT ", " INTPTR_FORMAT "] (%zd bytes)",
 636                     (intptr_t)heap->low_boundary(), (intptr_t)heap->high(),
 637                     (address)heap->high() - (address)heap->low_boundary());
 638     }
 639   }
 640   print_trace("allocation", cb, size);
 641   return cb;
 642 }
 643 
 644 void CodeCache::free(CodeBlob* cb) {
 645   assert_locked_or_safepoint(CodeCache_lock);
 646   CodeHeap* heap = get_code_heap(cb);
 647   print_trace("free", cb);
 648   if (cb->is_nmethod()) {
 649     heap->set_nmethod_count(heap->nmethod_count() - 1);
 650     if (((nmethod *)cb)->has_dependencies()) {
 651       AtomicAccess::dec(&_number_of_nmethods_with_dependencies);
 652     }
 653   }
 654   if (cb->is_adapter_blob()) {
 655     heap->set_adapter_count(heap->adapter_count() - 1);
 656   }
 657 
 658   cb->~CodeBlob();
 659   // Get heap for given CodeBlob and deallocate
 660   heap->deallocate(cb);
 661 
 662   assert(heap->blob_count() >= 0, "sanity check");
 663 }
 664 
 665 void CodeCache::free_unused_tail(CodeBlob* cb, size_t used) {
 666   assert_locked_or_safepoint(CodeCache_lock);
 667   guarantee(cb->is_buffer_blob() && strncmp("Interpreter", cb->name(), 11) == 0, "Only possible for interpreter!");
 668   print_trace("free_unused_tail", cb);
 669 
 670   // We also have to account for the extra space (i.e. header) used by the CodeBlob
 671   // which provides the memory (see BufferBlob::create() in codeBlob.cpp).
 672   used += CodeBlob::align_code_offset(cb->header_size());
 673 
 674   // Get heap for given CodeBlob and deallocate its unused tail
 675   get_code_heap(cb)->deallocate_tail(cb, used);
 676   // Adjust the sizes of the CodeBlob
 677   cb->adjust_size(used);
 678 }
 679 
 680 void CodeCache::commit(CodeBlob* cb) {
 681   // this is called by nmethod::nmethod, which must already own CodeCache_lock
 682   assert_locked_or_safepoint(CodeCache_lock);
 683   CodeHeap* heap = get_code_heap(cb);
 684   if (cb->is_nmethod()) {
 685     heap->set_nmethod_count(heap->nmethod_count() + 1);
 686     if (((nmethod *)cb)->has_dependencies()) {
 687       AtomicAccess::inc(&_number_of_nmethods_with_dependencies);
 688     }
 689   }
 690   if (cb->is_adapter_blob()) {
 691     heap->set_adapter_count(heap->adapter_count() + 1);
 692   }
 693 }
 694 
 695 bool CodeCache::contains(void *p) {
 696   // S390 uses contains() in current_frame(), which is used before
 697   // code cache initialization if NativeMemoryTracking=detail is set.
 698   S390_ONLY(if (_heaps == nullptr) return false;)
 699   // It should be ok to call contains without holding a lock.
 700   FOR_ALL_HEAPS(heap) {
 701     if ((*heap)->contains(p)) {
 702       return true;
 703     }
 704   }
 705   return false;
 706 }
 707 
 708 bool CodeCache::contains(nmethod *nm) {
 709   return contains((void *)nm);
 710 }
 711 
 712 // This method is safe to call without holding the CodeCache_lock. It only depends on the _segmap to contain
 713 // valid indices, which it will always do, as long as the CodeBlob is not in the process of being recycled.
 714 CodeBlob* CodeCache::find_blob(void* start) {
 715   // NMT can walk the stack before code cache is created
 716   if (_heaps != nullptr) {
 717     CodeHeap* heap = get_code_heap_containing(start);
 718     if (heap != nullptr) {
 719       return heap->find_blob(start);
 720     }
 721   }
 722   return nullptr;
 723 }
 724 
 725 nmethod* CodeCache::find_nmethod(void* start) {
 726   CodeBlob* cb = find_blob(start);
 727   assert(cb == nullptr || cb->is_nmethod(), "did not find an nmethod");
 728   return (nmethod*)cb;
 729 }
 730 
 731 void CodeCache::blobs_do(void f(CodeBlob* nm)) {
 732   assert_locked_or_safepoint(CodeCache_lock);
 733   FOR_ALL_HEAPS(heap) {
 734     FOR_ALL_BLOBS(cb, *heap) {
 735       f(cb);
 736     }
 737   }
 738 }
 739 
 740 void CodeCache::nmethods_do(void f(nmethod* nm)) {
 741   assert_locked_or_safepoint(CodeCache_lock);
 742   NMethodIterator iter(NMethodIterator::all);
 743   while(iter.next()) {
 744     f(iter.method());
 745   }
 746 }
 747 
 748 void CodeCache::nmethods_do(NMethodClosure* cl) {
 749   assert_locked_or_safepoint(CodeCache_lock);
 750   NMethodIterator iter(NMethodIterator::all);
 751   while(iter.next()) {
 752     cl->do_nmethod(iter.method());
 753   }
 754 }
 755 
 756 void CodeCache::metadata_do(MetadataClosure* f) {
 757   assert_locked_or_safepoint(CodeCache_lock);
 758   NMethodIterator iter(NMethodIterator::all);
 759   while(iter.next()) {
 760     iter.method()->metadata_do(f);
 761   }
 762 }
 763 
 764 // Calculate the number of GCs after which an nmethod is expected to have been
 765 // used in order to not be classed as cold.
 766 void CodeCache::update_cold_gc_count() {
 767   if (!MethodFlushing || !UseCodeCacheFlushing || NmethodSweepActivity == 0) {
 768     // No aging
 769     return;
 770   }
 771 
 772   size_t last_used = _last_unloading_used;
 773   double last_time = _last_unloading_time;
 774 
 775   double time = os::elapsedTime();
 776 
 777   size_t free = unallocated_capacity();
 778   size_t max = max_capacity();
 779   size_t used = max - free;
 780   double gc_interval = time - last_time;
 781 
 782   _unloading_threshold_gc_requested = false;
 783   _last_unloading_time = time;
 784   _last_unloading_used = used;
 785 
 786   if (last_time == 0.0) {
 787     // The first GC doesn't have enough information to make good
 788     // decisions, so just keep everything afloat
 789     log_info(codecache)("Unknown code cache pressure; don't age code");
 790     return;
 791   }
 792 
 793   if (gc_interval <= 0.0 || last_used >= used) {
 794     // Dodge corner cases where there is no pressure or negative pressure
 795     // on the code cache. Just don't unload when this happens.
 796     _cold_gc_count = INT_MAX;
 797     log_info(codecache)("No code cache pressure; don't age code");
 798     return;
 799   }
 800 
 801   double allocation_rate = (used - last_used) / gc_interval;
 802 
 803   _unloading_allocation_rates.add(allocation_rate);
 804   _unloading_gc_intervals.add(gc_interval);
 805 
 806   size_t aggressive_sweeping_free_threshold = StartAggressiveSweepingAt / 100.0 * max;
 807   if (free < aggressive_sweeping_free_threshold) {
 808     // We are already in the red zone; be very aggressive to avoid disaster
 809     // But not more aggressive than 2. This ensures that an nmethod must
 810     // have been unused at least between two GCs to be considered cold still.
 811     _cold_gc_count = 2;
 812     log_info(codecache)("Code cache critically low; use aggressive aging");
 813     return;
 814   }
 815 
 816   // The code cache has an expected time for cold nmethods to "time out"
 817   // when they have not been used. The time for nmethods to time out
 818   // depends on how long we expect we can keep allocating code until
 819   // aggressive sweeping starts, based on sampled allocation rates.
 820   double average_gc_interval = _unloading_gc_intervals.avg();
 821   double average_allocation_rate = _unloading_allocation_rates.avg();
 822   double time_to_aggressive = ((double)(free - aggressive_sweeping_free_threshold)) / average_allocation_rate;
 823   double cold_timeout = time_to_aggressive / NmethodSweepActivity;
 824 
 825   // Convert time to GC cycles, and crop at INT_MAX. The reason for
 826   // that is that the _cold_gc_count will be added to an epoch number
 827   // and that addition must not overflow, or we can crash the VM.
 828   // But not more aggressive than 2. This ensures that an nmethod must
 829   // have been unused at least between two GCs to be considered cold still.
 830   _cold_gc_count = MAX2(MIN2((uint64_t)(cold_timeout / average_gc_interval), (uint64_t)INT_MAX), (uint64_t)2);
 831 
 832   double used_ratio = double(used) / double(max);
 833   double last_used_ratio = double(last_used) / double(max);
 834   log_info(codecache)("Allocation rate: %.3f KB/s, time to aggressive unloading: %.3f s, cold timeout: %.3f s, cold gc count: " UINT64_FORMAT
 835                       ", used: %.3f MB (%.3f%%), last used: %.3f MB (%.3f%%), gc interval: %.3f s",
 836                       average_allocation_rate / K, time_to_aggressive, cold_timeout, _cold_gc_count,
 837                       double(used) / M, used_ratio * 100.0, double(last_used) / M, last_used_ratio * 100.0, average_gc_interval);
 838 
 839 }
 840 
 841 uint64_t CodeCache::cold_gc_count() {
 842   return _cold_gc_count;
 843 }
 844 
 845 void CodeCache::gc_on_allocation() {
 846   if (!is_init_completed()) {
 847     // Let's not heuristically trigger GCs before the JVM is ready for GCs, no matter what
 848     return;
 849   }
 850 
 851   size_t free = unallocated_capacity();
 852   size_t max = max_capacity();
 853   size_t used = max - free;
 854   double free_ratio = double(free) / double(max);
 855   if (free_ratio <= StartAggressiveSweepingAt / 100.0)  {
 856     // In case the GC is concurrent, we make sure only one thread requests the GC.
 857     if (AtomicAccess::cmpxchg(&_unloading_threshold_gc_requested, false, true) == false) {
 858       log_info(codecache)("Triggering aggressive GC due to having only %.3f%% free memory", free_ratio * 100.0);
 859       Universe::heap()->collect(GCCause::_codecache_GC_aggressive);
 860     }
 861     return;
 862   }
 863 
 864   size_t last_used = _last_unloading_used;
 865   if (last_used >= used) {
 866     // No increase since last GC; no need to sweep yet
 867     return;
 868   }
 869   size_t allocated_since_last = used - last_used;
 870   double allocated_since_last_ratio = double(allocated_since_last) / double(max);
 871   double threshold = SweeperThreshold / 100.0;
 872   double used_ratio = double(used) / double(max);
 873   double last_used_ratio = double(last_used) / double(max);
 874   if (used_ratio > threshold) {
 875     // After threshold is reached, scale it by free_ratio so that more aggressive
 876     // GC is triggered as we approach code cache exhaustion
 877     threshold *= free_ratio;
 878   }
 879   // If code cache has been allocated without any GC at all, let's make sure
 880   // it is eventually invoked to avoid trouble.
 881   if (allocated_since_last_ratio > threshold) {
 882     // In case the GC is concurrent, we make sure only one thread requests the GC.
 883     if (AtomicAccess::cmpxchg(&_unloading_threshold_gc_requested, false, true) == false) {
 884       log_info(codecache)("Triggering threshold (%.3f%%) GC due to allocating %.3f%% since last unloading (%.3f%% used -> %.3f%% used)",
 885                           threshold * 100.0, allocated_since_last_ratio * 100.0, last_used_ratio * 100.0, used_ratio * 100.0);
 886       Universe::heap()->collect(GCCause::_codecache_GC_threshold);
 887     }
 888   }
 889 }
 890 
 891 // We initialize the _gc_epoch to 2, because previous_completed_gc_marking_cycle
 892 // subtracts the value by 2, and the type is unsigned. We don't want underflow.
 893 //
 894 // Odd values mean that marking is in progress, and even values mean that no
 895 // marking is currently active.
 896 uint64_t CodeCache::_gc_epoch = 2;
 897 
 898 // How many GCs after an nmethod has not been used, do we consider it cold?
 899 uint64_t CodeCache::_cold_gc_count = INT_MAX;
 900 
 901 double CodeCache::_last_unloading_time = 0.0;
 902 size_t CodeCache::_last_unloading_used = 0;
 903 volatile bool CodeCache::_unloading_threshold_gc_requested = false;
 904 TruncatedSeq CodeCache::_unloading_gc_intervals(10 /* samples */);
 905 TruncatedSeq CodeCache::_unloading_allocation_rates(10 /* samples */);
 906 
 907 uint64_t CodeCache::gc_epoch() {
 908   return _gc_epoch;
 909 }
 910 
 911 bool CodeCache::is_gc_marking_cycle_active() {
 912   // Odd means that marking is active
 913   return (_gc_epoch % 2) == 1;
 914 }
 915 
 916 uint64_t CodeCache::previous_completed_gc_marking_cycle() {
 917   if (is_gc_marking_cycle_active()) {
 918     return _gc_epoch - 2;
 919   } else {
 920     return _gc_epoch - 1;
 921   }
 922 }
 923 
 924 void CodeCache::on_gc_marking_cycle_start() {
 925   assert(!is_gc_marking_cycle_active(), "Previous marking cycle never ended");
 926   ++_gc_epoch;
 927 }
 928 
 929 // Once started the code cache marking cycle must only be finished after marking of
 930 // the java heap is complete. Otherwise nmethods could appear to be not on stack even
 931 // if they have frames in continuation StackChunks that were not yet visited.
 932 void CodeCache::on_gc_marking_cycle_finish() {
 933   assert(is_gc_marking_cycle_active(), "Marking cycle started before last one finished");
 934   ++_gc_epoch;
 935   update_cold_gc_count();
 936 }
 937 
 938 void CodeCache::arm_all_nmethods() {
 939   BarrierSet::barrier_set()->barrier_set_nmethod()->arm_all_nmethods();
 940 }
 941 
 942 // Mark nmethods for unloading if they contain otherwise unreachable oops.
 943 void CodeCache::do_unloading(bool unloading_occurred) {
 944   assert_locked_or_safepoint(CodeCache_lock);
 945   NMethodIterator iter(NMethodIterator::all);
 946   while(iter.next()) {
 947     iter.method()->do_unloading(unloading_occurred);
 948   }
 949 }
 950 
 951 void CodeCache::verify_clean_inline_caches() {
 952 #ifdef ASSERT
 953   if (!VerifyInlineCaches) return;
 954   NMethodIterator iter(NMethodIterator::not_unloading);
 955   while(iter.next()) {
 956     nmethod* nm = iter.method();
 957     nm->verify_clean_inline_caches();
 958     nm->verify();
 959   }
 960 #endif
 961 }
 962 
 963 // Defer freeing of concurrently cleaned ExceptionCache entries until
 964 // after a global handshake operation.
 965 void CodeCache::release_exception_cache(ExceptionCache* entry) {
 966   if (SafepointSynchronize::is_at_safepoint()) {
 967     delete entry;
 968   } else {
 969     for (;;) {
 970       ExceptionCache* purge_list_head = AtomicAccess::load(&_exception_cache_purge_list);
 971       entry->set_purge_list_next(purge_list_head);
 972       if (AtomicAccess::cmpxchg(&_exception_cache_purge_list, purge_list_head, entry) == purge_list_head) {
 973         break;
 974       }
 975     }
 976   }
 977 }
 978 
 979 // Delete exception caches that have been concurrently unlinked,
 980 // followed by a global handshake operation.
 981 void CodeCache::purge_exception_caches() {
 982   ExceptionCache* curr = _exception_cache_purge_list;
 983   while (curr != nullptr) {
 984     ExceptionCache* next = curr->purge_list_next();
 985     delete curr;
 986     curr = next;
 987   }
 988   _exception_cache_purge_list = nullptr;
 989 }
 990 
 991 // Restart compiler if possible and required..
 992 void CodeCache::maybe_restart_compiler(size_t freed_memory) {
 993 
 994   // Try to start the compiler again if we freed any memory
 995   if (!CompileBroker::should_compile_new_jobs() && freed_memory != 0) {
 996     CompileBroker::set_should_compile_new_jobs(CompileBroker::run_compilation);
 997     log_info(codecache)("Restarting compiler");
 998     EventJITRestart event;
 999     event.set_freedMemory(freed_memory);
1000     event.set_codeCacheMaxCapacity(CodeCache::max_capacity());
1001     event.commit();
1002   }
1003 }
1004 
1005 uint8_t CodeCache::_unloading_cycle = 1;
1006 
1007 void CodeCache::increment_unloading_cycle() {
1008   // 2-bit value (see IsUnloadingState in nmethod.cpp for details)
1009   // 0 is reserved for new methods.
1010   _unloading_cycle = (_unloading_cycle + 1) % 4;
1011   if (_unloading_cycle == 0) {
1012     _unloading_cycle = 1;
1013   }
1014 }
1015 
1016 CodeCache::UnlinkingScope::UnlinkingScope(BoolObjectClosure* is_alive)
1017   : _is_unloading_behaviour(is_alive)
1018 {
1019   _saved_behaviour = IsUnloadingBehaviour::current();
1020   IsUnloadingBehaviour::set_current(&_is_unloading_behaviour);
1021   increment_unloading_cycle();
1022   DependencyContext::cleaning_start();
1023 }
1024 
1025 CodeCache::UnlinkingScope::~UnlinkingScope() {
1026   IsUnloadingBehaviour::set_current(_saved_behaviour);
1027   DependencyContext::cleaning_end();
1028 }
1029 
1030 void CodeCache::verify_oops() {
1031   MutexLocker mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
1032   VerifyOopClosure voc;
1033   NMethodIterator iter(NMethodIterator::not_unloading);
1034   while(iter.next()) {
1035     nmethod* nm = iter.method();
1036     nm->oops_do(&voc);
1037     nm->verify_oop_relocations();
1038   }
1039 }
1040 
1041 int CodeCache::blob_count(CodeBlobType code_blob_type) {
1042   CodeHeap* heap = get_code_heap(code_blob_type);
1043   return (heap != nullptr) ? heap->blob_count() : 0;
1044 }
1045 
1046 int CodeCache::blob_count() {
1047   int count = 0;
1048   FOR_ALL_HEAPS(heap) {
1049     count += (*heap)->blob_count();
1050   }
1051   return count;
1052 }
1053 
1054 int CodeCache::nmethod_count(CodeBlobType code_blob_type) {
1055   CodeHeap* heap = get_code_heap(code_blob_type);
1056   return (heap != nullptr) ? heap->nmethod_count() : 0;
1057 }
1058 
1059 int CodeCache::nmethod_count() {
1060   int count = 0;
1061   for (CodeHeap* heap : *_nmethod_heaps) {
1062     count += heap->nmethod_count();
1063   }
1064   return count;
1065 }
1066 
1067 int CodeCache::adapter_count(CodeBlobType code_blob_type) {
1068   CodeHeap* heap = get_code_heap(code_blob_type);
1069   return (heap != nullptr) ? heap->adapter_count() : 0;
1070 }
1071 
1072 int CodeCache::adapter_count() {
1073   int count = 0;
1074   FOR_ALL_HEAPS(heap) {
1075     count += (*heap)->adapter_count();
1076   }
1077   return count;
1078 }
1079 
1080 address CodeCache::low_bound(CodeBlobType code_blob_type) {
1081   CodeHeap* heap = get_code_heap(code_blob_type);
1082   return (heap != nullptr) ? (address)heap->low_boundary() : nullptr;
1083 }
1084 
1085 address CodeCache::high_bound(CodeBlobType code_blob_type) {
1086   CodeHeap* heap = get_code_heap(code_blob_type);
1087   return (heap != nullptr) ? (address)heap->high_boundary() : nullptr;
1088 }
1089 
1090 size_t CodeCache::capacity() {
1091   size_t cap = 0;
1092   FOR_ALL_ALLOCABLE_HEAPS(heap) {
1093     cap += (*heap)->capacity();
1094   }
1095   return cap;
1096 }
1097 
1098 size_t CodeCache::unallocated_capacity(CodeBlobType code_blob_type) {
1099   CodeHeap* heap = get_code_heap(code_blob_type);
1100   return (heap != nullptr) ? heap->unallocated_capacity() : 0;
1101 }
1102 
1103 size_t CodeCache::unallocated_capacity() {
1104   size_t unallocated_cap = 0;
1105   FOR_ALL_ALLOCABLE_HEAPS(heap) {
1106     unallocated_cap += (*heap)->unallocated_capacity();
1107   }
1108   return unallocated_cap;
1109 }
1110 
1111 size_t CodeCache::max_capacity() {
1112   size_t max_cap = 0;
1113   FOR_ALL_ALLOCABLE_HEAPS(heap) {
1114     max_cap += (*heap)->max_capacity();
1115   }
1116   return max_cap;
1117 }
1118 
1119 bool CodeCache::is_non_nmethod(address addr) {
1120   CodeHeap* blob = get_code_heap(CodeBlobType::NonNMethod);
1121   return blob->contains(addr);
1122 }
1123 
1124 size_t CodeCache::max_distance_to_non_nmethod() {
1125   if (!SegmentedCodeCache) {
1126     return ReservedCodeCacheSize;
1127   } else {
1128     CodeHeap* blob = get_code_heap(CodeBlobType::NonNMethod);
1129     // the max distance is minimized by placing the NonNMethod segment
1130     // in between MethodProfiled and MethodNonProfiled segments
1131     size_t dist1 = (size_t)blob->high_boundary() - (size_t)_low_bound;
1132     size_t dist2 = (size_t)_high_bound - (size_t)blob->low_boundary();
1133     return dist1 > dist2 ? dist1 : dist2;
1134   }
1135 }
1136 
1137 // Returns the reverse free ratio. E.g., if 25% (1/4) of the code cache
1138 // is free, reverse_free_ratio() returns 4.
1139 // Since code heap for each type of code blobs falls forward to the next
1140 // type of code heap, return the reverse free ratio for the entire
1141 // code cache.
1142 double CodeCache::reverse_free_ratio() {
1143   double unallocated = MAX2((double)unallocated_capacity(), 1.0); // Avoid division by 0;
1144   double max = (double)max_capacity();
1145   double result = max / unallocated;
1146   assert (max >= unallocated, "Must be");
1147   assert (result >= 1.0, "reverse_free_ratio must be at least 1. It is %f", result);
1148   return result;
1149 }
1150 
1151 size_t CodeCache::bytes_allocated_in_freelists() {
1152   size_t allocated_bytes = 0;
1153   FOR_ALL_ALLOCABLE_HEAPS(heap) {
1154     allocated_bytes += (*heap)->allocated_in_freelist();
1155   }
1156   return allocated_bytes;
1157 }
1158 
1159 int CodeCache::allocated_segments() {
1160   int number_of_segments = 0;
1161   FOR_ALL_ALLOCABLE_HEAPS(heap) {
1162     number_of_segments += (*heap)->allocated_segments();
1163   }
1164   return number_of_segments;
1165 }
1166 
1167 size_t CodeCache::freelists_length() {
1168   size_t length = 0;
1169   FOR_ALL_ALLOCABLE_HEAPS(heap) {
1170     length += (*heap)->freelist_length();
1171   }
1172   return length;
1173 }
1174 
1175 void icache_init();
1176 
1177 void CodeCache::initialize() {
1178   assert(CodeCacheSegmentSize >= CodeEntryAlignment, "CodeCacheSegmentSize must be large enough to align entry points");
1179 #ifdef COMPILER2
1180   assert(CodeCacheSegmentSize >= (size_t)OptoLoopAlignment,  "CodeCacheSegmentSize must be large enough to align inner loops");
1181 #endif
1182   assert(CodeCacheSegmentSize >= sizeof(jdouble),    "CodeCacheSegmentSize must be large enough to align constants");
1183   // This was originally just a check of the alignment, causing failure, instead, round
1184   // the code cache to the page size.  In particular, Solaris is moving to a larger
1185   // default page size.
1186   CodeCacheExpansionSize = align_up(CodeCacheExpansionSize, os::vm_page_size());
1187 
1188   if (SegmentedCodeCache) {
1189     // Use multiple code heaps
1190     initialize_heaps();
1191   } else {
1192     // Use a single code heap
1193     FLAG_SET_ERGO(NonNMethodCodeHeapSize, (uintx)os::vm_page_size());
1194     FLAG_SET_ERGO(ProfiledCodeHeapSize, 0);
1195     FLAG_SET_ERGO(NonProfiledCodeHeapSize, 0);
1196 
1197     // If InitialCodeCacheSize is equal to ReservedCodeCacheSize, then it's more likely
1198     // users want to use the largest available page.
1199     const size_t min_pages = (InitialCodeCacheSize == ReservedCodeCacheSize) ? 1 : 8;
1200     ReservedSpace rs = reserve_heap_memory(ReservedCodeCacheSize, page_size(false, min_pages));
1201     // Register CodeHeaps with LSan as we sometimes embed pointers to malloc memory.
1202     LSAN_REGISTER_ROOT_REGION(rs.base(), rs.size());
1203     add_heap(rs, "CodeCache", CodeBlobType::All);
1204   }
1205 
1206   // Initialize ICache flush mechanism
1207   // This service is needed for os::register_code_area
1208   icache_init();
1209 
1210   // Give OS a chance to register generated code area.
1211   // This is used on Windows 64 bit platforms to register
1212   // Structured Exception Handlers for our generated code.
1213   os::register_code_area((char*)low_bound(), (char*)high_bound());
1214 }
1215 
1216 void codeCache_init() {
1217   CodeCache::initialize();
1218 }
1219 
1220 //------------------------------------------------------------------------------------------------
1221 
1222 bool CodeCache::has_nmethods_with_dependencies() {
1223   return AtomicAccess::load_acquire(&_number_of_nmethods_with_dependencies) != 0;
1224 }
1225 
1226 void CodeCache::clear_inline_caches() {
1227   assert_locked_or_safepoint(CodeCache_lock);
1228   NMethodIterator iter(NMethodIterator::not_unloading);
1229   while(iter.next()) {
1230     iter.method()->clear_inline_caches();
1231   }
1232 }
1233 
1234 // Only used by whitebox API
1235 void CodeCache::cleanup_inline_caches_whitebox() {
1236   assert_locked_or_safepoint(CodeCache_lock);
1237   NMethodIterator iter(NMethodIterator::not_unloading);
1238   while(iter.next()) {
1239     iter.method()->cleanup_inline_caches_whitebox();
1240   }
1241 }
1242 
1243 // Keeps track of time spent for checking dependencies
1244 NOT_PRODUCT(static elapsedTimer dependentCheckTime;)
1245 
1246 #ifndef PRODUCT
1247 // Check if any of live methods dependencies have been invalidated.
1248 // (this is expensive!)
1249 static void check_live_nmethods_dependencies(DepChange& changes) {
1250   // Checked dependencies are allocated into this ResourceMark
1251   ResourceMark rm;
1252 
1253   // Turn off dependency tracing while actually testing dependencies.
1254   FlagSetting fs(Dependencies::_verify_in_progress, true);
1255 
1256   typedef HashTable<DependencySignature, int, 11027,
1257                             AnyObj::RESOURCE_AREA, mtInternal,
1258                             &DependencySignature::hash,
1259                             &DependencySignature::equals> DepTable;
1260 
1261   DepTable* table = new DepTable();
1262 
1263   // Iterate over live nmethods and check dependencies of all nmethods that are not
1264   // marked for deoptimization. A particular dependency is only checked once.
1265   NMethodIterator iter(NMethodIterator::not_unloading);
1266   while(iter.next()) {
1267     nmethod* nm = iter.method();
1268     // Only notify for live nmethods
1269     if (!nm->is_marked_for_deoptimization()) {
1270       for (Dependencies::DepStream deps(nm); deps.next(); ) {
1271         // Construct abstraction of a dependency.
1272         DependencySignature* current_sig = new DependencySignature(deps);
1273 
1274         // Determine if dependency is already checked. table->put(...) returns
1275         // 'true' if the dependency is added (i.e., was not in the hashtable).
1276         if (table->put(*current_sig, 1)) {
1277           Klass* witness = deps.check_dependency();
1278           if (witness != nullptr) {
1279             // Dependency checking failed. Print out information about the failed
1280             // dependency and finally fail with an assert. We can fail here, since
1281             // dependency checking is never done in a product build.
1282             deps.print_dependency(tty, witness, true);
1283             changes.print();
1284             nm->print();
1285             nm->print_dependencies_on(tty);
1286             assert(false, "Should have been marked for deoptimization");
1287           }
1288         }
1289       }
1290     }
1291   }
1292 }
1293 #endif
1294 
1295 void CodeCache::mark_for_deoptimization(DeoptimizationScope* deopt_scope, KlassDepChange& changes) {
1296   MutexLocker mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
1297 
1298   // search the hierarchy looking for nmethods which are affected by the loading of this class
1299 
1300   // then search the interfaces this class implements looking for nmethods
1301   // which might be dependent of the fact that an interface only had one
1302   // implementor.
1303   // nmethod::check_all_dependencies works only correctly, if no safepoint
1304   // can happen
1305   NoSafepointVerifier nsv;
1306   for (DepChange::ContextStream str(changes, nsv); str.next(); ) {
1307     InstanceKlass* d = str.klass();
1308     {
1309       LogStreamHandle(Trace, dependencies) log;
1310       if (log.is_enabled()) {
1311         log.print("Processing context ");
1312         d->name()->print_value_on(&log);
1313       }
1314     }
1315     d->mark_dependent_nmethods(deopt_scope, changes);
1316   }
1317 
1318 #ifndef PRODUCT
1319   if (VerifyDependencies) {
1320     // Object pointers are used as unique identifiers for dependency arguments. This
1321     // is only possible if no safepoint, i.e., GC occurs during the verification code.
1322     dependentCheckTime.start();
1323     check_live_nmethods_dependencies(changes);
1324     dependentCheckTime.stop();
1325   }
1326 #endif
1327 }
1328 
1329 #if INCLUDE_JVMTI
1330 // RedefineClasses support for saving nmethods that are dependent on "old" methods.
1331 // We don't really expect this table to grow very large.  If it does, it can become a hashtable.
1332 static GrowableArray<nmethod*>* old_nmethod_table = nullptr;
1333 
1334 static void add_to_old_table(nmethod* c) {
1335   if (old_nmethod_table == nullptr) {
1336     old_nmethod_table = new (mtCode) GrowableArray<nmethod*>(100, mtCode);
1337   }
1338   old_nmethod_table->push(c);
1339 }
1340 
1341 static void reset_old_method_table() {
1342   if (old_nmethod_table != nullptr) {
1343     delete old_nmethod_table;
1344     old_nmethod_table = nullptr;
1345   }
1346 }
1347 
1348 // Remove this method when flushed.
1349 void CodeCache::unregister_old_nmethod(nmethod* c) {
1350   assert_lock_strong(CodeCache_lock);
1351   if (old_nmethod_table != nullptr) {
1352     int index = old_nmethod_table->find(c);
1353     if (index != -1) {
1354       old_nmethod_table->delete_at(index);
1355     }
1356   }
1357 }
1358 
1359 void CodeCache::old_nmethods_do(MetadataClosure* f) {
1360   // Walk old method table and mark those on stack.
1361   int length = 0;
1362   if (old_nmethod_table != nullptr) {
1363     length = old_nmethod_table->length();
1364     for (int i = 0; i < length; i++) {
1365       // Walk all methods saved on the last pass.  Concurrent class unloading may
1366       // also be looking at this method's metadata, so don't delete it yet if
1367       // it is marked as unloaded.
1368       old_nmethod_table->at(i)->metadata_do(f);
1369     }
1370   }
1371   log_debug(redefine, class, nmethod)("Walked %d nmethods for mark_on_stack", length);
1372 }
1373 
1374 // Walk compiled methods and mark dependent methods for deoptimization.
1375 void CodeCache::mark_dependents_for_evol_deoptimization(DeoptimizationScope* deopt_scope) {
1376   assert(SafepointSynchronize::is_at_safepoint(), "Can only do this at a safepoint!");
1377   // Each redefinition creates a new set of nmethods that have references to "old" Methods
1378   // So delete old method table and create a new one.
1379   reset_old_method_table();
1380 
1381   NMethodIterator iter(NMethodIterator::all);
1382   while(iter.next()) {
1383     nmethod* nm = iter.method();
1384     // Walk all alive nmethods to check for old Methods.
1385     // This includes methods whose inline caches point to old methods, so
1386     // inline cache clearing is unnecessary.
1387     if (nm->has_evol_metadata()) {
1388       deopt_scope->mark(nm);
1389       add_to_old_table(nm);
1390     }
1391   }
1392 }
1393 
1394 void CodeCache::mark_all_nmethods_for_evol_deoptimization(DeoptimizationScope* deopt_scope) {
1395   assert(SafepointSynchronize::is_at_safepoint(), "Can only do this at a safepoint!");
1396   NMethodIterator iter(NMethodIterator::all);
1397   while(iter.next()) {
1398     nmethod* nm = iter.method();
1399     if (!nm->method()->is_method_handle_intrinsic()) {
1400       if (nm->can_be_deoptimized()) {
1401         deopt_scope->mark(nm);
1402       }
1403       if (nm->has_evol_metadata()) {
1404         add_to_old_table(nm);
1405       }
1406     }
1407   }
1408 }
1409 
1410 #endif // INCLUDE_JVMTI
1411 
1412 // Mark methods for deopt (if safe or possible).
1413 void CodeCache::mark_all_nmethods_for_deoptimization(DeoptimizationScope* deopt_scope) {
1414   MutexLocker mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
1415   NMethodIterator iter(NMethodIterator::not_unloading);
1416   while(iter.next()) {
1417     nmethod* nm = iter.method();
1418     if (!nm->is_native_method()) {
1419       deopt_scope->mark(nm);
1420     }
1421   }
1422 }
1423 
1424 void CodeCache::mark_for_deoptimization(DeoptimizationScope* deopt_scope, Method* dependee) {
1425   MutexLocker mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
1426 
1427   NMethodIterator iter(NMethodIterator::not_unloading);
1428   while(iter.next()) {
1429     nmethod* nm = iter.method();
1430     if (nm->is_dependent_on_method(dependee)) {
1431       deopt_scope->mark(nm);
1432     }
1433   }
1434 }
1435 
1436 void CodeCache::make_marked_nmethods_deoptimized() {
1437   RelaxedNMethodIterator iter(RelaxedNMethodIterator::not_unloading);
1438   while(iter.next()) {
1439     nmethod* nm = iter.method();
1440     if (nm->is_marked_for_deoptimization() && !nm->has_been_deoptimized() && nm->can_be_deoptimized()) {
1441       nm->make_not_entrant(nmethod::InvalidationReason::MARKED_FOR_DEOPTIMIZATION);
1442       nm->make_deoptimized();
1443     }
1444   }
1445 }
1446 
1447 // Marks compiled methods dependent on dependee.
1448 void CodeCache::mark_dependents_on(DeoptimizationScope* deopt_scope, InstanceKlass* dependee) {
1449   assert_lock_strong(Compile_lock);
1450 
1451   if (!has_nmethods_with_dependencies()) {
1452     return;
1453   }
1454 
1455   if (dependee->is_linked()) {
1456     // Class initialization state change.
1457     KlassInitDepChange changes(dependee);
1458     mark_for_deoptimization(deopt_scope, changes);
1459   } else {
1460     // New class is loaded.
1461     NewKlassDepChange changes(dependee);
1462     mark_for_deoptimization(deopt_scope, changes);
1463   }
1464 }
1465 
1466 // Marks compiled methods dependent on dependee
1467 void CodeCache::mark_dependents_on_method_for_breakpoint(const methodHandle& m_h) {
1468   assert(SafepointSynchronize::is_at_safepoint(), "invariant");
1469 
1470   DeoptimizationScope deopt_scope;
1471   // Compute the dependent nmethods
1472   mark_for_deoptimization(&deopt_scope, m_h());
1473   deopt_scope.deoptimize_marked();
1474 }
1475 
1476 void CodeCache::verify() {
1477   assert_locked_or_safepoint(CodeCache_lock);
1478   FOR_ALL_HEAPS(heap) {
1479     (*heap)->verify();
1480     FOR_ALL_BLOBS(cb, *heap) {
1481       cb->verify();
1482     }
1483   }
1484 }
1485 
1486 // A CodeHeap is full. Print out warning and report event.
1487 PRAGMA_DIAG_PUSH
1488 PRAGMA_FORMAT_NONLITERAL_IGNORED
1489 void CodeCache::report_codemem_full(CodeBlobType code_blob_type, bool print) {
1490   // Get nmethod heap for the given CodeBlobType and build CodeCacheFull event
1491   CodeHeap* heap = get_code_heap(code_blob_type);
1492   assert(heap != nullptr, "heap is null");
1493 
1494   int full_count = heap->report_full();
1495 
1496   if ((full_count == 1) || print) {
1497     // Not yet reported for this heap, report
1498     if (SegmentedCodeCache) {
1499       ResourceMark rm;
1500       stringStream msg1_stream, msg2_stream;
1501       msg1_stream.print("%s is full. Compiler has been disabled.",
1502                         get_code_heap_name(code_blob_type));
1503       msg2_stream.print("Try increasing the code heap size using -XX:%s=",
1504                  get_code_heap_flag_name(code_blob_type));
1505       const char *msg1 = msg1_stream.as_string();
1506       const char *msg2 = msg2_stream.as_string();
1507 
1508       log_warning(codecache)("%s", msg1);
1509       log_warning(codecache)("%s", msg2);
1510       warning("%s", msg1);
1511       warning("%s", msg2);
1512     } else {
1513       const char *msg1 = "CodeCache is full. Compiler has been disabled.";
1514       const char *msg2 = "Try increasing the code cache size using -XX:ReservedCodeCacheSize=";
1515 
1516       log_warning(codecache)("%s", msg1);
1517       log_warning(codecache)("%s", msg2);
1518       warning("%s", msg1);
1519       warning("%s", msg2);
1520     }
1521     stringStream s;
1522     // Dump code cache into a buffer before locking the tty.
1523     {
1524       MutexLocker mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
1525       print_summary(&s);
1526     }
1527     {
1528       ttyLocker ttyl;
1529       tty->print("%s", s.freeze());
1530     }
1531 
1532     if (full_count == 1) {
1533       if (PrintCodeHeapAnalytics) {
1534         CompileBroker::print_heapinfo(tty, "all", 4096); // details, may be a lot!
1535       }
1536     }
1537   }
1538 
1539   EventCodeCacheFull event;
1540   if (event.should_commit()) {
1541     event.set_codeBlobType((u1)code_blob_type);
1542     event.set_startAddress((u8)heap->low_boundary());
1543     event.set_commitedTopAddress((u8)heap->high());
1544     event.set_reservedTopAddress((u8)heap->high_boundary());
1545     event.set_entryCount(heap->blob_count());
1546     event.set_methodCount(heap->nmethod_count());
1547     event.set_adaptorCount(heap->adapter_count());
1548     event.set_unallocatedCapacity(heap->unallocated_capacity());
1549     event.set_fullCount(heap->full_count());
1550     event.set_codeCacheMaxCapacity(CodeCache::max_capacity());
1551     event.commit();
1552   }
1553 }
1554 PRAGMA_DIAG_POP
1555 
1556 void CodeCache::print_memory_overhead() {
1557   size_t wasted_bytes = 0;
1558   FOR_ALL_ALLOCABLE_HEAPS(heap) {
1559       CodeHeap* curr_heap = *heap;
1560       for (CodeBlob* cb = (CodeBlob*)curr_heap->first(); cb != nullptr; cb = (CodeBlob*)curr_heap->next(cb)) {
1561         HeapBlock* heap_block = ((HeapBlock*)cb) - 1;
1562         wasted_bytes += heap_block->length() * CodeCacheSegmentSize - cb->size();
1563       }
1564   }
1565   // Print bytes that are allocated in the freelist
1566   ttyLocker ttl;
1567   tty->print_cr("Number of elements in freelist: %zd",       freelists_length());
1568   tty->print_cr("Allocated in freelist:          %zdkB",  bytes_allocated_in_freelists()/K);
1569   tty->print_cr("Unused bytes in CodeBlobs:      %zdkB",  (wasted_bytes/K));
1570   tty->print_cr("Segment map size:               %zdkB",  allocated_segments()/K); // 1 byte per segment
1571 }
1572 
1573 static void print_helper1(outputStream* st, const char* prefix, int total, int not_entrant, int used) {
1574   if (total > 0) {
1575     double ratio = (100.0 * used) / total;
1576     st->print("%s %3d nmethods: %3d not_entrant, %d used (%2.1f%%)", prefix, total, not_entrant, used, ratio);
1577   }
1578 }
1579 
1580 void CodeCache::print_nmethod_statistics_on(outputStream* st) {
1581   int stats     [2][6][3][2] = {0};
1582   int stats_used[2][6][3][2] = {0};
1583 
1584   int total_osr = 0;
1585   int total_entrant = 0;
1586   int total_non_entrant = 0;
1587   int total_other = 0;
1588   int total_used = 0;
1589 
1590   NMethodIterator iter(NMethodIterator::all);
1591   while (iter.next()) {
1592     nmethod* nm = iter.method();
1593     if (nm->is_in_use()) {
1594       ++total_entrant;
1595     } else if (nm->is_not_entrant()) {
1596       ++total_non_entrant;
1597     } else {
1598       ++total_other;
1599     }
1600     if (nm->is_osr_method()) {
1601       ++total_osr;
1602     }
1603     if (nm->used()) {
1604       ++total_used;
1605     }
1606     assert(!nm->preloaded() || nm->comp_level() == CompLevel_full_optimization, "");
1607 
1608     int idx1 = nm->is_aot() ? 1 : 0;
1609     int idx2 = nm->comp_level() + (nm->preloaded() ? 1 : 0);
1610     int idx3 = (nm->is_in_use()      ? 0 :
1611                (nm->is_not_entrant() ? 1 :
1612                                        2));
1613     int idx4 = (nm->is_osr_method() ? 1 : 0);
1614     stats[idx1][idx2][idx3][idx4] += 1;
1615     if (nm->used()) {
1616       stats_used[idx1][idx2][idx3][idx4] += 1;
1617     }
1618   }
1619 
1620   st->print("Total: %d methods (%d entrant / %d not_entrant; osr: %d ",
1621                total_entrant + total_non_entrant + total_other,
1622                total_entrant, total_non_entrant, total_osr);
1623   if (total_other > 0) {
1624     st->print("; %d other", total_other);
1625   }
1626   st->print_cr(")");
1627 
1628   for (int i = CompLevel_simple; i <= CompLevel_full_optimization; i++) {
1629     int total_normal = stats[0][i][0][0] + stats[0][i][1][0] + stats[0][i][2][0];
1630     int total_osr    = stats[0][i][0][1] + stats[0][i][1][1] + stats[0][i][2][1];
1631     if (total_normal + total_osr > 0) {
1632       st->print("  Tier%d:", i);
1633       print_helper1(st,      "", total_normal, stats[0][i][1][0], stats_used[0][i][0][0] + stats_used[0][i][1][0]);
1634       print_helper1(st, "; osr:", total_osr,    stats[0][i][1][1], stats_used[0][i][0][1] + stats_used[0][i][1][1]);
1635       st->cr();
1636     }
1637   }
1638   st->cr();
1639   for (int i = CompLevel_simple; i <= CompLevel_full_optimization + 1; i++) {
1640     int total_normal = stats[1][i][0][0] + stats[1][i][1][0] + stats[1][i][2][0];
1641     int total_osr    = stats[1][i][0][1] + stats[1][i][1][1] + stats[1][i][2][1];
1642     assert(total_osr == 0, "sanity");
1643     if (total_normal + total_osr > 0) {
1644       st->print("  AOT Code T%d:", i);
1645       print_helper1(st,      "", total_normal, stats[1][i][1][0], stats_used[1][i][0][0] + stats_used[1][i][1][0]);
1646       print_helper1(st, "; osr:", total_osr,    stats[1][i][1][1], stats_used[1][i][0][1] + stats_used[1][i][1][1]);
1647       st->cr();
1648     }
1649   }
1650 }
1651 
1652 //------------------------------------------------------------------------------------------------
1653 // Non-product version
1654 
1655 #ifndef PRODUCT
1656 
1657 void CodeCache::print_trace(const char* event, CodeBlob* cb, uint size) {
1658   if (PrintCodeCache2) {  // Need to add a new flag
1659     ResourceMark rm;
1660     if (size == 0) {
1661       int s = cb->size();
1662       assert(s >= 0, "CodeBlob size is negative: %d", s);
1663       size = (uint) s;
1664     }
1665     tty->print_cr("CodeCache %s:  addr: " INTPTR_FORMAT ", size: 0x%x", event, p2i(cb), size);
1666   }
1667 }
1668 
1669 void CodeCache::print_internals() {
1670   int nmethodCount = 0;
1671   int runtimeStubCount = 0;
1672   int upcallStubCount = 0;
1673   int adapterCount = 0;
1674   int mhAdapterCount = 0;
1675   int vtableBlobCount = 0;
1676   int deoptimizationStubCount = 0;
1677   int uncommonTrapStubCount = 0;
1678   int exceptionStubCount = 0;
1679   int safepointStubCount = 0;
1680   int bufferBlobCount = 0;
1681   int total = 0;
1682   int nmethodNotEntrant = 0;
1683   int nmethodJava = 0;
1684   int nmethodNative = 0;
1685   int max_nm_size = 0;
1686   ResourceMark rm;
1687 
1688   int i = 0;
1689   FOR_ALL_ALLOCABLE_HEAPS(heap) {
1690     int heap_total = 0;
1691     tty->print_cr("-- %s --", (*heap)->name());
1692     FOR_ALL_BLOBS(cb, *heap) {
1693       total++;
1694       heap_total++;
1695       if (cb->is_nmethod()) {
1696         nmethod* nm = (nmethod*)cb;
1697 
1698         tty->print("%4d: ", heap_total);
1699         CompileTask::print(tty, nm, (nm->is_not_entrant() ? "non-entrant" : ""), true, true);
1700 
1701         nmethodCount++;
1702 
1703         if(nm->is_not_entrant()) { nmethodNotEntrant++; }
1704         if(nm->method() != nullptr && nm->is_native_method()) { nmethodNative++; }
1705 
1706         if(nm->method() != nullptr && nm->is_java_method()) {
1707           nmethodJava++;
1708           max_nm_size = MAX2(max_nm_size, nm->size());
1709         }
1710       } else if (cb->is_runtime_stub()) {
1711         runtimeStubCount++;
1712       } else if (cb->is_upcall_stub()) {
1713         upcallStubCount++;
1714       } else if (cb->is_deoptimization_stub()) {
1715         deoptimizationStubCount++;
1716       } else if (cb->is_uncommon_trap_stub()) {
1717         uncommonTrapStubCount++;
1718       } else if (cb->is_exception_stub()) {
1719         exceptionStubCount++;
1720       } else if (cb->is_safepoint_stub()) {
1721         safepointStubCount++;
1722       } else if (cb->is_adapter_blob()) {
1723         adapterCount++;
1724       } else if (cb->is_method_handles_adapter_blob()) {
1725         mhAdapterCount++;
1726       } else if (cb->is_vtable_blob()) {
1727         vtableBlobCount++;
1728       } else if (cb->is_buffer_blob()) {
1729         bufferBlobCount++;
1730       }
1731     }
1732   }
1733 
1734   int bucketSize = 512;
1735   int bucketLimit = max_nm_size / bucketSize + 1;
1736   int *buckets = NEW_C_HEAP_ARRAY(int, bucketLimit, mtCode);
1737   memset(buckets, 0, sizeof(int) * bucketLimit);
1738 
1739   NMethodIterator iter(NMethodIterator::all);
1740   while(iter.next()) {
1741     nmethod* nm = iter.method();
1742     if(nm->method() != nullptr && nm->is_java_method()) {
1743       buckets[nm->size() / bucketSize]++;
1744     }
1745   }
1746 
1747   tty->print_cr("Code Cache Entries (total of %d)",total);
1748   tty->print_cr("-------------------------------------------------");
1749   tty->print_cr("nmethods: %d",nmethodCount);
1750   tty->print_cr("\tnot_entrant: %d",nmethodNotEntrant);
1751   tty->print_cr("\tjava: %d",nmethodJava);
1752   tty->print_cr("\tnative: %d",nmethodNative);
1753   tty->print_cr("runtime_stubs: %d",runtimeStubCount);
1754   tty->print_cr("upcall_stubs: %d",upcallStubCount);
1755   tty->print_cr("adapters: %d",adapterCount);
1756   tty->print_cr("MH adapters: %d",mhAdapterCount);
1757   tty->print_cr("VTables: %d",vtableBlobCount);
1758   tty->print_cr("buffer blobs: %d",bufferBlobCount);
1759   tty->print_cr("deoptimization_stubs: %d",deoptimizationStubCount);
1760   tty->print_cr("uncommon_traps: %d",uncommonTrapStubCount);
1761   tty->print_cr("exception_stubs: %d",exceptionStubCount);
1762   tty->print_cr("safepoint_stubs: %d",safepointStubCount);
1763   tty->print_cr("\nnmethod size distribution");
1764   tty->print_cr("-------------------------------------------------");
1765 
1766   for(int i=0; i<bucketLimit; i++) {
1767     if(buckets[i] != 0) {
1768       tty->print("%d - %d bytes",i*bucketSize,(i+1)*bucketSize);
1769       tty->fill_to(40);
1770       tty->print_cr("%d",buckets[i]);
1771     }
1772   }
1773 
1774   FREE_C_HEAP_ARRAY(int, buckets);
1775   print_memory_overhead();
1776 }
1777 
1778 #endif // !PRODUCT
1779 
1780 void CodeCache::print() {
1781   print_summary(tty);
1782 
1783 #ifndef PRODUCT
1784   if (!Verbose) return;
1785 
1786   CodeBlob_sizes live[CompLevel_full_optimization + 1];
1787   CodeBlob_sizes runtimeStub;
1788   CodeBlob_sizes upcallStub;
1789   CodeBlob_sizes uncommonTrapStub;
1790   CodeBlob_sizes deoptimizationStub;
1791   CodeBlob_sizes exceptionStub;
1792   CodeBlob_sizes safepointStub;
1793   CodeBlob_sizes adapter;
1794   CodeBlob_sizes mhAdapter;
1795   CodeBlob_sizes vtableBlob;
1796   CodeBlob_sizes bufferBlob;
1797   CodeBlob_sizes other;
1798 
1799   FOR_ALL_ALLOCABLE_HEAPS(heap) {
1800     FOR_ALL_BLOBS(cb, *heap) {
1801       if (cb->is_nmethod()) {
1802         const int level = cb->as_nmethod()->comp_level();
1803         assert(0 <= level && level <= CompLevel_full_optimization, "Invalid compilation level");
1804         live[level].add(cb);
1805       } else if (cb->is_runtime_stub()) {
1806         runtimeStub.add(cb);
1807       } else if (cb->is_upcall_stub()) {
1808         upcallStub.add(cb);
1809       } else if (cb->is_deoptimization_stub()) {
1810         deoptimizationStub.add(cb);
1811       } else if (cb->is_uncommon_trap_stub()) {
1812         uncommonTrapStub.add(cb);
1813       } else if (cb->is_exception_stub()) {
1814         exceptionStub.add(cb);
1815       } else if (cb->is_safepoint_stub()) {
1816         safepointStub.add(cb);
1817       } else if (cb->is_adapter_blob()) {
1818         adapter.add(cb);
1819       } else if (cb->is_method_handles_adapter_blob()) {
1820         mhAdapter.add(cb);
1821       } else if (cb->is_vtable_blob()) {
1822         vtableBlob.add(cb);
1823       } else if (cb->is_buffer_blob()) {
1824         bufferBlob.add(cb);
1825       } else {
1826         other.add(cb);
1827       }
1828     }
1829   }
1830 
1831   tty->print_cr("nmethod dependency checking time %fs", dependentCheckTime.seconds());
1832 
1833   tty->print_cr("nmethod blobs per compilation level:");
1834   for (int i = 0; i <= CompLevel_full_optimization; i++) {
1835     const char *level_name;
1836     switch (i) {
1837     case CompLevel_none:              level_name = "none";              break;
1838     case CompLevel_simple:            level_name = "simple";            break;
1839     case CompLevel_limited_profile:   level_name = "limited profile";   break;
1840     case CompLevel_full_profile:      level_name = "full profile";      break;
1841     case CompLevel_full_optimization: level_name = "full optimization"; break;
1842     default: assert(false, "invalid compilation level");
1843     }
1844     tty->print_cr("%s:", level_name);
1845     live[i].print("live");
1846   }
1847 
1848   struct {
1849     const char* name;
1850     const CodeBlob_sizes* sizes;
1851   } non_nmethod_blobs[] = {
1852     { "runtime",        &runtimeStub },
1853     { "upcall",         &upcallStub },
1854     { "uncommon trap",  &uncommonTrapStub },
1855     { "deoptimization", &deoptimizationStub },
1856     { "exception",      &exceptionStub },
1857     { "safepoint",      &safepointStub },
1858     { "adapter",        &adapter },
1859     { "mh_adapter",     &mhAdapter },
1860     { "vtable",         &vtableBlob },
1861     { "buffer blob",    &bufferBlob },
1862     { "other",          &other },
1863   };
1864   tty->print_cr("Non-nmethod blobs:");
1865   for (auto& blob: non_nmethod_blobs) {
1866     blob.sizes->print(blob.name);
1867   }
1868 
1869   if (WizardMode) {
1870      // print the oop_map usage
1871     int code_size = 0;
1872     int number_of_blobs = 0;
1873     int number_of_oop_maps = 0;
1874     int map_size = 0;
1875     FOR_ALL_ALLOCABLE_HEAPS(heap) {
1876       FOR_ALL_BLOBS(cb, *heap) {
1877         number_of_blobs++;
1878         code_size += cb->code_size();
1879         ImmutableOopMapSet* set = cb->oop_maps();
1880         if (set != nullptr) {
1881           number_of_oop_maps += set->count();
1882           map_size           += set->nr_of_bytes();
1883         }
1884       }
1885     }
1886     tty->print_cr("OopMaps");
1887     tty->print_cr("  #blobs    = %d", number_of_blobs);
1888     tty->print_cr("  code size = %d", code_size);
1889     tty->print_cr("  #oop_maps = %d", number_of_oop_maps);
1890     tty->print_cr("  map size  = %d", map_size);
1891   }
1892 
1893 #endif // !PRODUCT
1894 }
1895 
1896 void CodeCache::print_nmethods_on(outputStream* st) {
1897   ResourceMark rm;
1898   int i = 0;
1899   FOR_ALL_ALLOCABLE_HEAPS(heap) {
1900     st->print_cr("-- %s --", (*heap)->name());
1901     FOR_ALL_BLOBS(cb, *heap) {
1902       i++;
1903       if (cb->is_nmethod()) {
1904         nmethod* nm = (nmethod*)cb;
1905         st->print("%4d: ", i);
1906         CompileTask::print(st, nm, nullptr, true, false);
1907 
1908         const char non_entrant_char = (nm->is_not_entrant() ? 'N' : ' ');
1909         st->print_cr(" %c", non_entrant_char);
1910       }
1911     }
1912   }
1913 }
1914 
1915 void CodeCache::print_summary(outputStream* st, bool detailed) {
1916   int full_count = 0;
1917   julong total_used = 0;
1918   julong total_max_used = 0;
1919   julong total_free = 0;
1920   julong total_size = 0;
1921   FOR_ALL_HEAPS(heap_iterator) {
1922     CodeHeap* heap = (*heap_iterator);
1923     size_t total = (heap->high_boundary() - heap->low_boundary());
1924     if (_heaps->length() >= 1) {
1925       st->print("%s:", heap->name());
1926     } else {
1927       st->print("CodeCache:");
1928     }
1929     size_t size = total/K;
1930     size_t used = (total - heap->unallocated_capacity())/K;
1931     size_t max_used = heap->max_allocated_capacity()/K;
1932     size_t free = heap->unallocated_capacity()/K;
1933     total_size += size;
1934     total_used += used;
1935     total_max_used += max_used;
1936     total_free += free;
1937     st->print_cr(" size=%zuKb used=%zu"
1938                  "Kb max_used=%zuKb free=%zuKb",
1939                  size, used, max_used, free);
1940 
1941     if (detailed) {
1942       st->print_cr(" bounds [" INTPTR_FORMAT ", " INTPTR_FORMAT ", " INTPTR_FORMAT "]",
1943                    p2i(heap->low_boundary()),
1944                    p2i(heap->high()),
1945                    p2i(heap->high_boundary()));
1946 
1947       full_count += get_codemem_full_count(heap->code_blob_type());
1948     }
1949   }
1950 
1951   if (detailed) {
1952     if (SegmentedCodeCache) {
1953       st->print("CodeCache:");
1954       st->print_cr(" size=" JULONG_FORMAT "Kb, used=" JULONG_FORMAT
1955                    "Kb, max_used=" JULONG_FORMAT "Kb, free=" JULONG_FORMAT "Kb",
1956                    total_size, total_used, total_max_used, total_free);
1957     }
1958     st->print_cr(" total_blobs=" UINT32_FORMAT ", nmethods=" UINT32_FORMAT
1959                  ", adapters=" UINT32_FORMAT ", full_count=" UINT32_FORMAT,
1960                  blob_count(), nmethod_count(), adapter_count(), full_count);
1961     st->print_cr("Compilation: %s, stopped_count=%d, restarted_count=%d",
1962                  CompileBroker::should_compile_new_jobs() ?
1963                  "enabled" : Arguments::mode() == Arguments::_int ?
1964                  "disabled (interpreter mode)" :
1965                  "disabled (not enough contiguous free space left)",
1966                  CompileBroker::get_total_compiler_stopped_count(),
1967                  CompileBroker::get_total_compiler_restarted_count());
1968   }
1969 }
1970 
1971 void CodeCache::print_codelist(outputStream* st) {
1972   MutexLocker mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
1973 
1974   NMethodIterator iter(NMethodIterator::not_unloading);
1975   while (iter.next()) {
1976     nmethod* nm = iter.method();
1977     ResourceMark rm;
1978     char* method_name = nm->method()->name_and_sig_as_C_string();
1979     const char* jvmci_name = nullptr;
1980 #if INCLUDE_JVMCI
1981     jvmci_name = nm->jvmci_name();
1982 #endif
1983     st->print_cr("%d %d %d %s%s%s [" INTPTR_FORMAT ", " INTPTR_FORMAT " - " INTPTR_FORMAT "]",
1984                  nm->compile_id(), nm->comp_level(), nm->get_state(),
1985                  method_name, jvmci_name ? " jvmci_name=" : "", jvmci_name ? jvmci_name : "",
1986                  (intptr_t)nm->header_begin(), (intptr_t)nm->code_begin(), (intptr_t)nm->code_end());
1987   }
1988 }
1989 
1990 void CodeCache::print_layout(outputStream* st) {
1991   MutexLocker mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
1992   ResourceMark rm;
1993   print_summary(st, true);
1994 }
1995 
1996 void CodeCache::log_state(outputStream* st) {
1997   st->print(" total_blobs='" UINT32_FORMAT "' nmethods='" UINT32_FORMAT "'"
1998             " adapters='" UINT32_FORMAT "' free_code_cache='%zu'",
1999             blob_count(), nmethod_count(), adapter_count(),
2000             unallocated_capacity());
2001 }
2002 
2003 #ifdef LINUX
2004 void CodeCache::write_perf_map(const char* filename, outputStream* st) {
2005   MutexLocker mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
2006   char fname[JVM_MAXPATHLEN];
2007   if (filename == nullptr) {
2008     // Invocation outside of jcmd requires pid substitution.
2009     if (!Arguments::copy_expand_pid(DEFAULT_PERFMAP_FILENAME,
2010                                     strlen(DEFAULT_PERFMAP_FILENAME),
2011                                     fname, JVM_MAXPATHLEN)) {
2012       st->print_cr("Warning: Not writing perf map as pid substitution failed.");
2013       return;
2014     }
2015     filename = fname;
2016   }
2017   fileStream fs(filename, "w");
2018   if (!fs.is_open()) {
2019     st->print_cr("Warning: Failed to create %s for perf map", filename);
2020     return;
2021   }
2022 
2023   AllCodeBlobsIterator iter(AllCodeBlobsIterator::not_unloading);
2024   while (iter.next()) {
2025     CodeBlob *cb = iter.method();
2026     ResourceMark rm;
2027     const char* method_name = nullptr;
2028     const char* jvmci_name = nullptr;
2029     if (cb->is_nmethod()) {
2030       nmethod* nm = cb->as_nmethod();
2031       method_name = nm->method()->external_name();
2032 #if INCLUDE_JVMCI
2033       jvmci_name = nm->jvmci_name();
2034 #endif
2035     } else {
2036       method_name = cb->name();
2037     }
2038     fs.print_cr(INTPTR_FORMAT " " INTPTR_FORMAT " %s%s%s",
2039                 (intptr_t)cb->code_begin(), (intptr_t)cb->code_size(),
2040                 method_name, jvmci_name ? " jvmci_name=" : "", jvmci_name ? jvmci_name : "");
2041   }
2042 }
2043 #endif // LINUX
2044 
2045 //---<  BEGIN  >--- CodeHeap State Analytics.
2046 
2047 void CodeCache::aggregate(outputStream *out, size_t granularity) {
2048   FOR_ALL_ALLOCABLE_HEAPS(heap) {
2049     CodeHeapState::aggregate(out, (*heap), granularity);
2050   }
2051 }
2052 
2053 void CodeCache::discard(outputStream *out) {
2054   FOR_ALL_ALLOCABLE_HEAPS(heap) {
2055     CodeHeapState::discard(out, (*heap));
2056   }
2057 }
2058 
2059 void CodeCache::print_usedSpace(outputStream *out) {
2060   FOR_ALL_ALLOCABLE_HEAPS(heap) {
2061     CodeHeapState::print_usedSpace(out, (*heap));
2062   }
2063 }
2064 
2065 void CodeCache::print_freeSpace(outputStream *out) {
2066   FOR_ALL_ALLOCABLE_HEAPS(heap) {
2067     CodeHeapState::print_freeSpace(out, (*heap));
2068   }
2069 }
2070 
2071 void CodeCache::print_count(outputStream *out) {
2072   FOR_ALL_ALLOCABLE_HEAPS(heap) {
2073     CodeHeapState::print_count(out, (*heap));
2074   }
2075 }
2076 
2077 void CodeCache::print_space(outputStream *out) {
2078   FOR_ALL_ALLOCABLE_HEAPS(heap) {
2079     CodeHeapState::print_space(out, (*heap));
2080   }
2081 }
2082 
2083 void CodeCache::print_age(outputStream *out) {
2084   FOR_ALL_ALLOCABLE_HEAPS(heap) {
2085     CodeHeapState::print_age(out, (*heap));
2086   }
2087 }
2088 
2089 void CodeCache::print_names(outputStream *out) {
2090   FOR_ALL_ALLOCABLE_HEAPS(heap) {
2091     CodeHeapState::print_names(out, (*heap));
2092   }
2093 }
2094 //---<  END  >--- CodeHeap State Analytics.