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