1 /*
   2  * Copyright (c) 1997, 2019, 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 "aot/aotLoader.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/icBuffer.hpp"
  34 #include "code/nmethod.hpp"
  35 #include "code/pcDesc.hpp"
  36 #include "compiler/compileBroker.hpp"
  37 #include "jfr/jfrEvents.hpp"
  38 #include "logging/log.hpp"
  39 #include "logging/logStream.hpp"
  40 #include "memory/allocation.inline.hpp"
  41 #include "memory/iterator.hpp"
  42 #include "memory/resourceArea.hpp"
  43 #include "oops/method.inline.hpp"
  44 #include "oops/objArrayOop.hpp"
  45 #include "oops/oop.inline.hpp"
  46 #include "oops/verifyOopClosure.hpp"
  47 #include "runtime/arguments.hpp"
  48 #include "runtime/compilationPolicy.hpp"
  49 #include "runtime/deoptimization.hpp"
  50 #include "runtime/handles.inline.hpp"
  51 #include "runtime/icache.hpp"
  52 #include "runtime/java.hpp"
  53 #include "runtime/mutexLocker.hpp"
  54 #include "runtime/safepointVerifiers.hpp"
  55 #include "runtime/sweeper.hpp"
  56 #include "runtime/vmThread.hpp"
  57 #include "services/memoryService.hpp"
  58 #include "utilities/align.hpp"
  59 #include "utilities/vmError.hpp"
  60 #include "utilities/xmlstream.hpp"
  61 #ifdef COMPILER1
  62 #include "c1/c1_Compilation.hpp"
  63 #include "c1/c1_Compiler.hpp"
  64 #endif
  65 #ifdef COMPILER2
  66 #include "opto/c2compiler.hpp"
  67 #include "opto/compile.hpp"
  68 #include "opto/node.hpp"
  69 #endif
  70 
  71 // Helper class for printing in CodeCache
  72 class CodeBlob_sizes {
  73  private:
  74   int count;
  75   int total_size;
  76   int header_size;
  77   int code_size;
  78   int stub_size;
  79   int relocation_size;
  80   int scopes_oop_size;
  81   int scopes_metadata_size;
  82   int scopes_data_size;
  83   int scopes_pcs_size;
  84 
  85  public:
  86   CodeBlob_sizes() {
  87     count            = 0;
  88     total_size       = 0;
  89     header_size      = 0;
  90     code_size        = 0;
  91     stub_size        = 0;
  92     relocation_size  = 0;
  93     scopes_oop_size  = 0;
  94     scopes_metadata_size  = 0;
  95     scopes_data_size = 0;
  96     scopes_pcs_size  = 0;
  97   }
  98 
  99   int total()                                    { return total_size; }
 100   bool is_empty()                                { return count == 0; }
 101 
 102   void print(const char* title) {
 103     tty->print_cr(" #%d %s = %dK (hdr %d%%,  loc %d%%, code %d%%, stub %d%%, [oops %d%%, metadata %d%%, data %d%%, pcs %d%%])",
 104                   count,
 105                   title,
 106                   (int)(total() / K),
 107                   header_size             * 100 / total_size,
 108                   relocation_size         * 100 / total_size,
 109                   code_size               * 100 / total_size,
 110                   stub_size               * 100 / total_size,
 111                   scopes_oop_size         * 100 / total_size,
 112                   scopes_metadata_size    * 100 / total_size,
 113                   scopes_data_size        * 100 / total_size,
 114                   scopes_pcs_size         * 100 / total_size);
 115   }
 116 
 117   void add(CodeBlob* cb) {
 118     count++;
 119     total_size       += cb->size();
 120     header_size      += cb->header_size();
 121     relocation_size  += cb->relocation_size();
 122     if (cb->is_nmethod()) {
 123       nmethod* nm = cb->as_nmethod_or_null();
 124       code_size        += nm->insts_size();
 125       stub_size        += nm->stub_size();
 126 
 127       scopes_oop_size  += nm->oops_size();
 128       scopes_metadata_size  += nm->metadata_size();
 129       scopes_data_size += nm->scopes_data_size();
 130       scopes_pcs_size  += nm->scopes_pcs_size();
 131     } else {
 132       code_size        += cb->code_size();
 133     }
 134   }
 135 };
 136 
 137 // Iterate over all CodeHeaps
 138 #define FOR_ALL_HEAPS(heap) for (GrowableArrayIterator<CodeHeap*> heap = _heaps->begin(); heap != _heaps->end(); ++heap)
 139 #define FOR_ALL_NMETHOD_HEAPS(heap) for (GrowableArrayIterator<CodeHeap*> heap = _nmethod_heaps->begin(); heap != _nmethod_heaps->end(); ++heap)
 140 #define FOR_ALL_ALLOCABLE_HEAPS(heap) for (GrowableArrayIterator<CodeHeap*> heap = _allocable_heaps->begin(); heap != _allocable_heaps->end(); ++heap)
 141 
 142 // Iterate over all CodeBlobs (cb) on the given CodeHeap
 143 #define FOR_ALL_BLOBS(cb, heap) for (CodeBlob* cb = first_blob(heap); cb != NULL; cb = next_blob(heap, cb))
 144 
 145 address CodeCache::_low_bound = 0;
 146 address CodeCache::_high_bound = 0;
 147 int CodeCache::_number_of_nmethods_with_dependencies = 0;
 148 nmethod* CodeCache::_scavenge_root_nmethods = NULL;
 149 ExceptionCache* volatile CodeCache::_exception_cache_purge_list = NULL;
 150 
 151 // Initialize arrays of CodeHeap subsets
 152 GrowableArray<CodeHeap*>* CodeCache::_heaps = new(ResourceObj::C_HEAP, mtCode) GrowableArray<CodeHeap*> (CodeBlobType::All, true);
 153 GrowableArray<CodeHeap*>* CodeCache::_compiled_heaps = new(ResourceObj::C_HEAP, mtCode) GrowableArray<CodeHeap*> (CodeBlobType::All, true);
 154 GrowableArray<CodeHeap*>* CodeCache::_nmethod_heaps = new(ResourceObj::C_HEAP, mtCode) GrowableArray<CodeHeap*> (CodeBlobType::All, true);
 155 GrowableArray<CodeHeap*>* CodeCache::_allocable_heaps = new(ResourceObj::C_HEAP, mtCode) GrowableArray<CodeHeap*> (CodeBlobType::All, true);
 156 
 157 void CodeCache::check_heap_sizes(size_t non_nmethod_size, size_t profiled_size, size_t non_profiled_size, size_t cache_size, bool all_set) {
 158   size_t total_size = non_nmethod_size + profiled_size + non_profiled_size;
 159   // Prepare error message
 160   const char* error = "Invalid code heap sizes";
 161   err_msg message("NonNMethodCodeHeapSize (" SIZE_FORMAT "K) + ProfiledCodeHeapSize (" SIZE_FORMAT "K)"
 162                   " + NonProfiledCodeHeapSize (" SIZE_FORMAT "K) = " SIZE_FORMAT "K",
 163           non_nmethod_size/K, profiled_size/K, non_profiled_size/K, total_size/K);
 164 
 165   if (total_size > cache_size) {
 166     // Some code heap sizes were explicitly set: total_size must be <= cache_size
 167     message.append(" is greater than ReservedCodeCacheSize (" SIZE_FORMAT "K).", cache_size/K);
 168     vm_exit_during_initialization(error, message);
 169   } else if (all_set && total_size != cache_size) {
 170     // All code heap sizes were explicitly set: total_size must equal cache_size
 171     message.append(" is not equal to ReservedCodeCacheSize (" SIZE_FORMAT "K).", cache_size/K);
 172     vm_exit_during_initialization(error, message);
 173   }
 174 }
 175 
 176 void CodeCache::initialize_heaps() {
 177   bool non_nmethod_set      = FLAG_IS_CMDLINE(NonNMethodCodeHeapSize);
 178   bool profiled_set         = FLAG_IS_CMDLINE(ProfiledCodeHeapSize);
 179   bool non_profiled_set     = FLAG_IS_CMDLINE(NonProfiledCodeHeapSize);
 180   size_t min_size           = os::vm_page_size();
 181   size_t cache_size         = ReservedCodeCacheSize;
 182   size_t non_nmethod_size   = NonNMethodCodeHeapSize;
 183   size_t profiled_size      = ProfiledCodeHeapSize;
 184   size_t non_profiled_size  = NonProfiledCodeHeapSize;
 185   // Check if total size set via command line flags exceeds the reserved size
 186   check_heap_sizes((non_nmethod_set  ? non_nmethod_size  : min_size),
 187                    (profiled_set     ? profiled_size     : min_size),
 188                    (non_profiled_set ? non_profiled_size : min_size),
 189                    cache_size,
 190                    non_nmethod_set && profiled_set && non_profiled_set);
 191 
 192   // Determine size of compiler buffers
 193   size_t code_buffers_size = 0;
 194 #ifdef COMPILER1
 195   // C1 temporary code buffers (see Compiler::init_buffer_blob())
 196   const int c1_count = CompilationPolicy::policy()->compiler_count(CompLevel_simple);
 197   code_buffers_size += c1_count * Compiler::code_buffer_size();
 198 #endif
 199 #ifdef COMPILER2
 200   // C2 scratch buffers (see Compile::init_scratch_buffer_blob())
 201   const int c2_count = CompilationPolicy::policy()->compiler_count(CompLevel_full_optimization);
 202   // Initial size of constant table (this may be increased if a compiled method needs more space)
 203   code_buffers_size += c2_count * C2Compiler::initial_code_buffer_size();
 204 #endif
 205 
 206   // Increase default non_nmethod_size to account for compiler buffers
 207   if (!non_nmethod_set) {
 208     non_nmethod_size += code_buffers_size;
 209   }
 210   // Calculate default CodeHeap sizes if not set by user
 211   if (!non_nmethod_set && !profiled_set && !non_profiled_set) {
 212     // Check if we have enough space for the non-nmethod code heap
 213     if (cache_size > non_nmethod_size) {
 214       // Use the default value for non_nmethod_size and one half of the
 215       // remaining size for non-profiled and one half for profiled methods
 216       size_t remaining_size = cache_size - non_nmethod_size;
 217       profiled_size = remaining_size / 2;
 218       non_profiled_size = remaining_size - profiled_size;
 219     } else {
 220       // Use all space for the non-nmethod heap and set other heaps to minimal size
 221       non_nmethod_size = cache_size - 2 * min_size;
 222       profiled_size = min_size;
 223       non_profiled_size = min_size;
 224     }
 225   } else if (!non_nmethod_set || !profiled_set || !non_profiled_set) {
 226     // The user explicitly set some code heap sizes. Increase or decrease the (default)
 227     // sizes of the other code heaps accordingly. First adapt non-profiled and profiled
 228     // code heap sizes and then only change non-nmethod code heap size if still necessary.
 229     intx diff_size = cache_size - (non_nmethod_size + profiled_size + non_profiled_size);
 230     if (non_profiled_set) {
 231       if (!profiled_set) {
 232         // Adapt size of profiled code heap
 233         if (diff_size < 0 && ((intx)profiled_size + diff_size) <= 0) {
 234           // Not enough space available, set to minimum size
 235           diff_size += profiled_size - min_size;
 236           profiled_size = min_size;
 237         } else {
 238           profiled_size += diff_size;
 239           diff_size = 0;
 240         }
 241       }
 242     } else if (profiled_set) {
 243       // Adapt size of non-profiled code heap
 244       if (diff_size < 0 && ((intx)non_profiled_size + diff_size) <= 0) {
 245         // Not enough space available, set to minimum size
 246         diff_size += non_profiled_size - min_size;
 247         non_profiled_size = min_size;
 248       } else {
 249         non_profiled_size += diff_size;
 250         diff_size = 0;
 251       }
 252     } else if (non_nmethod_set) {
 253       // Distribute remaining size between profiled and non-profiled code heaps
 254       diff_size = cache_size - non_nmethod_size;
 255       profiled_size = diff_size / 2;
 256       non_profiled_size = diff_size - profiled_size;
 257       diff_size = 0;
 258     }
 259     if (diff_size != 0) {
 260       // Use non-nmethod code heap for remaining space requirements
 261       assert(!non_nmethod_set && ((intx)non_nmethod_size + diff_size) > 0, "sanity");
 262       non_nmethod_size += diff_size;
 263     }
 264   }
 265 
 266   // We do not need the profiled CodeHeap, use all space for the non-profiled CodeHeap
 267   if (!heap_available(CodeBlobType::MethodProfiled)) {
 268     non_profiled_size += profiled_size;
 269     profiled_size = 0;
 270   }
 271   // We do not need the non-profiled CodeHeap, use all space for the non-nmethod CodeHeap
 272   if (!heap_available(CodeBlobType::MethodNonProfiled)) {
 273     non_nmethod_size += non_profiled_size;
 274     non_profiled_size = 0;
 275   }
 276   // Make sure we have enough space for VM internal code
 277   uint min_code_cache_size = CodeCacheMinimumUseSpace DEBUG_ONLY(* 3);
 278   if (non_nmethod_size < min_code_cache_size) {
 279     vm_exit_during_initialization(err_msg(
 280         "Not enough space in non-nmethod code heap to run VM: " SIZE_FORMAT "K < " SIZE_FORMAT "K",
 281         non_nmethod_size/K, min_code_cache_size/K));
 282   }
 283 
 284   // Verify sizes and update flag values
 285   assert(non_profiled_size + profiled_size + non_nmethod_size == cache_size, "Invalid code heap sizes");
 286   FLAG_SET_ERGO(uintx, NonNMethodCodeHeapSize, non_nmethod_size);
 287   FLAG_SET_ERGO(uintx, ProfiledCodeHeapSize, profiled_size);
 288   FLAG_SET_ERGO(uintx, NonProfiledCodeHeapSize, non_profiled_size);
 289 
 290   // If large page support is enabled, align code heaps according to large
 291   // page size to make sure that code cache is covered by large pages.
 292   const size_t alignment = MAX2(page_size(false, 8), (size_t) os::vm_allocation_granularity());
 293   non_nmethod_size = align_up(non_nmethod_size, alignment);
 294   profiled_size    = align_down(profiled_size, alignment);
 295 
 296   // Reserve one continuous chunk of memory for CodeHeaps and split it into
 297   // parts for the individual heaps. The memory layout looks like this:
 298   // ---------- high -----------
 299   //    Non-profiled nmethods
 300   //      Profiled nmethods
 301   //         Non-nmethods
 302   // ---------- low ------------
 303   ReservedCodeSpace rs = reserve_heap_memory(cache_size);
 304   ReservedSpace non_method_space    = rs.first_part(non_nmethod_size);
 305   ReservedSpace rest                = rs.last_part(non_nmethod_size);
 306   ReservedSpace profiled_space      = rest.first_part(profiled_size);
 307   ReservedSpace non_profiled_space  = rest.last_part(profiled_size);
 308 
 309   // Non-nmethods (stubs, adapters, ...)
 310   add_heap(non_method_space, "CodeHeap 'non-nmethods'", CodeBlobType::NonNMethod);
 311   // Tier 2 and tier 3 (profiled) methods
 312   add_heap(profiled_space, "CodeHeap 'profiled nmethods'", CodeBlobType::MethodProfiled);
 313   // Tier 1 and tier 4 (non-profiled) methods and native methods
 314   add_heap(non_profiled_space, "CodeHeap 'non-profiled nmethods'", CodeBlobType::MethodNonProfiled);
 315 }
 316 
 317 size_t CodeCache::page_size(bool aligned, size_t min_pages) {
 318   if (os::can_execute_large_page_memory()) {
 319     if (InitialCodeCacheSize < ReservedCodeCacheSize) {
 320       // Make sure that the page size allows for an incremental commit of the reserved space
 321       min_pages = MAX2(min_pages, (size_t)8);
 322     }
 323     return aligned ? os::page_size_for_region_aligned(ReservedCodeCacheSize, min_pages) :
 324                      os::page_size_for_region_unaligned(ReservedCodeCacheSize, min_pages);
 325   } else {
 326     return os::vm_page_size();
 327   }
 328 }
 329 
 330 ReservedCodeSpace CodeCache::reserve_heap_memory(size_t size) {
 331   // Align and reserve space for code cache
 332   const size_t rs_ps = page_size();
 333   const size_t rs_align = MAX2(rs_ps, (size_t) os::vm_allocation_granularity());
 334   const size_t rs_size = align_up(size, rs_align);
 335   ReservedCodeSpace rs(rs_size, rs_align, rs_ps > (size_t) os::vm_page_size());
 336   if (!rs.is_reserved()) {
 337     vm_exit_during_initialization(err_msg("Could not reserve enough space for code cache (" SIZE_FORMAT "K)",
 338                                           rs_size/K));
 339   }
 340 
 341   // Initialize bounds
 342   _low_bound = (address)rs.base();
 343   _high_bound = _low_bound + rs.size();
 344   return rs;
 345 }
 346 
 347 // Heaps available for allocation
 348 bool CodeCache::heap_available(int code_blob_type) {
 349   if (!SegmentedCodeCache) {
 350     // No segmentation: use a single code heap
 351     return (code_blob_type == CodeBlobType::All);
 352   } else if (Arguments::is_interpreter_only()) {
 353     // Interpreter only: we don't need any method code heaps
 354     return (code_blob_type == CodeBlobType::NonNMethod);
 355   } else if (TieredCompilation && (TieredStopAtLevel > CompLevel_simple)) {
 356     // Tiered compilation: use all code heaps
 357     return (code_blob_type < CodeBlobType::All);
 358   } else {
 359     // No TieredCompilation: we only need the non-nmethod and non-profiled code heap
 360     return (code_blob_type == CodeBlobType::NonNMethod) ||
 361            (code_blob_type == CodeBlobType::MethodNonProfiled);
 362   }
 363 }
 364 
 365 const char* CodeCache::get_code_heap_flag_name(int code_blob_type) {
 366   switch(code_blob_type) {
 367   case CodeBlobType::NonNMethod:
 368     return "NonNMethodCodeHeapSize";
 369     break;
 370   case CodeBlobType::MethodNonProfiled:
 371     return "NonProfiledCodeHeapSize";
 372     break;
 373   case CodeBlobType::MethodProfiled:
 374     return "ProfiledCodeHeapSize";
 375     break;
 376   }
 377   ShouldNotReachHere();
 378   return NULL;
 379 }
 380 
 381 int CodeCache::code_heap_compare(CodeHeap* const &lhs, CodeHeap* const &rhs) {
 382   if (lhs->code_blob_type() == rhs->code_blob_type()) {
 383     return (lhs > rhs) ? 1 : ((lhs < rhs) ? -1 : 0);
 384   } else {
 385     return lhs->code_blob_type() - rhs->code_blob_type();
 386   }
 387 }
 388 
 389 void CodeCache::add_heap(CodeHeap* heap) {
 390   assert(!Universe::is_fully_initialized(), "late heap addition?");
 391 
 392   _heaps->insert_sorted<code_heap_compare>(heap);
 393 
 394   int type = heap->code_blob_type();
 395   if (code_blob_type_accepts_compiled(type)) {
 396     _compiled_heaps->insert_sorted<code_heap_compare>(heap);
 397   }
 398   if (code_blob_type_accepts_nmethod(type)) {
 399     _nmethod_heaps->insert_sorted<code_heap_compare>(heap);
 400   }
 401   if (code_blob_type_accepts_allocable(type)) {
 402     _allocable_heaps->insert_sorted<code_heap_compare>(heap);
 403   }
 404 }
 405 
 406 void CodeCache::add_heap(ReservedSpace rs, const char* name, int code_blob_type) {
 407   // Check if heap is needed
 408   if (!heap_available(code_blob_type)) {
 409     return;
 410   }
 411 
 412   // Create CodeHeap
 413   CodeHeap* heap = new CodeHeap(name, code_blob_type);
 414   add_heap(heap);
 415 
 416   // Reserve Space
 417   size_t size_initial = MIN2((size_t)InitialCodeCacheSize, rs.size());
 418   size_initial = align_up(size_initial, os::vm_page_size());
 419   if (!heap->reserve(rs, size_initial, CodeCacheSegmentSize)) {
 420     vm_exit_during_initialization(err_msg("Could not reserve enough space in %s (" SIZE_FORMAT "K)",
 421                                           heap->name(), size_initial/K));
 422   }
 423 
 424   // Register the CodeHeap
 425   MemoryService::add_code_heap_memory_pool(heap, name);
 426 }
 427 
 428 CodeHeap* CodeCache::get_code_heap_containing(void* start) {
 429   FOR_ALL_HEAPS(heap) {
 430     if ((*heap)->contains(start)) {
 431       return *heap;
 432     }
 433   }
 434   return NULL;
 435 }
 436 
 437 CodeHeap* CodeCache::get_code_heap(const CodeBlob* cb) {
 438   assert(cb != NULL, "CodeBlob is null");
 439   FOR_ALL_HEAPS(heap) {
 440     if ((*heap)->contains_blob(cb)) {
 441       return *heap;
 442     }
 443   }
 444   ShouldNotReachHere();
 445   return NULL;
 446 }
 447 
 448 CodeHeap* CodeCache::get_code_heap(int code_blob_type) {
 449   FOR_ALL_HEAPS(heap) {
 450     if ((*heap)->accepts(code_blob_type)) {
 451       return *heap;
 452     }
 453   }
 454   return NULL;
 455 }
 456 
 457 CodeBlob* CodeCache::first_blob(CodeHeap* heap) {
 458   assert_locked_or_safepoint(CodeCache_lock);
 459   assert(heap != NULL, "heap is null");
 460   return (CodeBlob*)heap->first();
 461 }
 462 
 463 CodeBlob* CodeCache::first_blob(int code_blob_type) {
 464   if (heap_available(code_blob_type)) {
 465     return first_blob(get_code_heap(code_blob_type));
 466   } else {
 467     return NULL;
 468   }
 469 }
 470 
 471 CodeBlob* CodeCache::next_blob(CodeHeap* heap, CodeBlob* cb) {
 472   assert_locked_or_safepoint(CodeCache_lock);
 473   assert(heap != NULL, "heap is null");
 474   return (CodeBlob*)heap->next(cb);
 475 }
 476 
 477 /**
 478  * Do not seize the CodeCache lock here--if the caller has not
 479  * already done so, we are going to lose bigtime, since the code
 480  * cache will contain a garbage CodeBlob until the caller can
 481  * run the constructor for the CodeBlob subclass he is busy
 482  * instantiating.
 483  */
 484 CodeBlob* CodeCache::allocate(int size, int code_blob_type, int orig_code_blob_type) {
 485   // Possibly wakes up the sweeper thread.
 486   NMethodSweeper::notify(code_blob_type);
 487   assert_locked_or_safepoint(CodeCache_lock);
 488   assert(size > 0, "Code cache allocation request must be > 0 but is %d", size);
 489   if (size <= 0) {
 490     return NULL;
 491   }
 492   CodeBlob* cb = NULL;
 493 
 494   // Get CodeHeap for the given CodeBlobType
 495   CodeHeap* heap = get_code_heap(code_blob_type);
 496   assert(heap != NULL, "heap is null");
 497 
 498   while (true) {
 499     cb = (CodeBlob*)heap->allocate(size);
 500     if (cb != NULL) break;
 501     if (!heap->expand_by(CodeCacheExpansionSize)) {
 502       // Save original type for error reporting
 503       if (orig_code_blob_type == CodeBlobType::All) {
 504         orig_code_blob_type = code_blob_type;
 505       }
 506       // Expansion failed
 507       if (SegmentedCodeCache) {
 508         // Fallback solution: Try to store code in another code heap.
 509         // NonNMethod -> MethodNonProfiled -> MethodProfiled (-> MethodNonProfiled)
 510         // Note that in the sweeper, we check the reverse_free_ratio of the code heap
 511         // and force stack scanning if less than 10% of the code heap are free.
 512         int type = code_blob_type;
 513         switch (type) {
 514         case CodeBlobType::NonNMethod:
 515           type = CodeBlobType::MethodNonProfiled;
 516           break;
 517         case CodeBlobType::MethodNonProfiled:
 518           type = CodeBlobType::MethodProfiled;
 519           break;
 520         case CodeBlobType::MethodProfiled:
 521           // Avoid loop if we already tried that code heap
 522           if (type == orig_code_blob_type) {
 523             type = CodeBlobType::MethodNonProfiled;
 524           }
 525           break;
 526         }
 527         if (type != code_blob_type && type != orig_code_blob_type && heap_available(type)) {
 528           if (PrintCodeCacheExtension) {
 529             tty->print_cr("Extension of %s failed. Trying to allocate in %s.",
 530                           heap->name(), get_code_heap(type)->name());
 531           }
 532           return allocate(size, type, orig_code_blob_type);
 533         }
 534       }
 535       MutexUnlockerEx mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
 536       CompileBroker::handle_full_code_cache(orig_code_blob_type);
 537       return NULL;
 538     }
 539     if (PrintCodeCacheExtension) {
 540       ResourceMark rm;
 541       if (_nmethod_heaps->length() >= 1) {
 542         tty->print("%s", heap->name());
 543       } else {
 544         tty->print("CodeCache");
 545       }
 546       tty->print_cr(" extended to [" INTPTR_FORMAT ", " INTPTR_FORMAT "] (" SSIZE_FORMAT " bytes)",
 547                     (intptr_t)heap->low_boundary(), (intptr_t)heap->high(),
 548                     (address)heap->high() - (address)heap->low_boundary());
 549     }
 550   }
 551   print_trace("allocation", cb, size);
 552   return cb;
 553 }
 554 
 555 void CodeCache::free(CodeBlob* cb) {
 556   assert_locked_or_safepoint(CodeCache_lock);
 557   CodeHeap* heap = get_code_heap(cb);
 558   print_trace("free", cb);
 559   if (cb->is_nmethod()) {
 560     heap->set_nmethod_count(heap->nmethod_count() - 1);
 561     if (((nmethod *)cb)->has_dependencies()) {
 562       _number_of_nmethods_with_dependencies--;
 563     }
 564   }
 565   if (cb->is_adapter_blob()) {
 566     heap->set_adapter_count(heap->adapter_count() - 1);
 567   }
 568 
 569   // Get heap for given CodeBlob and deallocate
 570   get_code_heap(cb)->deallocate(cb);
 571 
 572   assert(heap->blob_count() >= 0, "sanity check");
 573 }
 574 
 575 void CodeCache::free_unused_tail(CodeBlob* cb, size_t used) {
 576   assert_locked_or_safepoint(CodeCache_lock);
 577   guarantee(cb->is_buffer_blob() && strncmp("Interpreter", cb->name(), 11) == 0, "Only possible for interpreter!");
 578   print_trace("free_unused_tail", cb);
 579 
 580   // We also have to account for the extra space (i.e. header) used by the CodeBlob
 581   // which provides the memory (see BufferBlob::create() in codeBlob.cpp).
 582   used += CodeBlob::align_code_offset(cb->header_size());
 583 
 584   // Get heap for given CodeBlob and deallocate its unused tail
 585   get_code_heap(cb)->deallocate_tail(cb, used);
 586   // Adjust the sizes of the CodeBlob
 587   cb->adjust_size(used);
 588 }
 589 
 590 void CodeCache::commit(CodeBlob* cb) {
 591   // this is called by nmethod::nmethod, which must already own CodeCache_lock
 592   assert_locked_or_safepoint(CodeCache_lock);
 593   CodeHeap* heap = get_code_heap(cb);
 594   if (cb->is_nmethod()) {
 595     heap->set_nmethod_count(heap->nmethod_count() + 1);
 596     if (((nmethod *)cb)->has_dependencies()) {
 597       _number_of_nmethods_with_dependencies++;
 598     }
 599   }
 600   if (cb->is_adapter_blob()) {
 601     heap->set_adapter_count(heap->adapter_count() + 1);
 602   }
 603 
 604   // flush the hardware I-cache
 605   ICache::invalidate_range(cb->content_begin(), cb->content_size());
 606 }
 607 
 608 bool CodeCache::contains(void *p) {
 609   // S390 uses contains() in current_frame(), which is used before
 610   // code cache initialization if NativeMemoryTracking=detail is set.
 611   S390_ONLY(if (_heaps == NULL) return false;)
 612   // It should be ok to call contains without holding a lock.
 613   FOR_ALL_HEAPS(heap) {
 614     if ((*heap)->contains(p)) {
 615       return true;
 616     }
 617   }
 618   return false;
 619 }
 620 
 621 bool CodeCache::contains(nmethod *nm) {
 622   return contains((void *)nm);
 623 }
 624 
 625 // This method is safe to call without holding the CodeCache_lock, as long as a dead CodeBlob is not
 626 // looked up (i.e., one that has been marked for deletion). It only depends on the _segmap to contain
 627 // valid indices, which it will always do, as long as the CodeBlob is not in the process of being recycled.
 628 CodeBlob* CodeCache::find_blob(void* start) {
 629   CodeBlob* result = find_blob_unsafe(start);
 630   // We could potentially look up non_entrant methods
 631   guarantee(result == NULL || !result->is_zombie() || result->is_locked_by_vm() || VMError::is_error_reported(), "unsafe access to zombie method");
 632   return result;
 633 }
 634 
 635 // Lookup that does not fail if you lookup a zombie method (if you call this, be sure to know
 636 // what you are doing)
 637 CodeBlob* CodeCache::find_blob_unsafe(void* start) {
 638   // NMT can walk the stack before code cache is created
 639   if (_heaps != NULL) {
 640     CodeHeap* heap = get_code_heap_containing(start);
 641     if (heap != NULL) {
 642       return heap->find_blob_unsafe(start);
 643     }
 644   }
 645   return NULL;
 646 }
 647 
 648 nmethod* CodeCache::find_nmethod(void* start) {
 649   CodeBlob* cb = find_blob(start);
 650   assert(cb->is_nmethod(), "did not find an nmethod");
 651   return (nmethod*)cb;
 652 }
 653 
 654 void CodeCache::blobs_do(void f(CodeBlob* nm)) {
 655   assert_locked_or_safepoint(CodeCache_lock);
 656   FOR_ALL_HEAPS(heap) {
 657     FOR_ALL_BLOBS(cb, *heap) {
 658       f(cb);
 659     }
 660   }
 661 }
 662 
 663 void CodeCache::nmethods_do(void f(nmethod* nm)) {
 664   assert_locked_or_safepoint(CodeCache_lock);
 665   NMethodIterator iter(NMethodIterator::all_blobs);
 666   while(iter.next()) {
 667     f(iter.method());
 668   }
 669 }
 670 
 671 void CodeCache::metadata_do(void f(Metadata* m)) {
 672   assert_locked_or_safepoint(CodeCache_lock);
 673   NMethodIterator iter(NMethodIterator::only_alive_and_not_unloading);
 674   while(iter.next()) {
 675     iter.method()->metadata_do(f);
 676   }
 677   AOTLoader::metadata_do(f);
 678 }
 679 
 680 int CodeCache::alignment_unit() {
 681   return (int)_heaps->first()->alignment_unit();
 682 }
 683 
 684 int CodeCache::alignment_offset() {
 685   return (int)_heaps->first()->alignment_offset();
 686 }
 687 
 688 // Mark nmethods for unloading if they contain otherwise unreachable oops.
 689 void CodeCache::do_unloading(BoolObjectClosure* is_alive, bool unloading_occurred) {
 690   assert_locked_or_safepoint(CodeCache_lock);
 691   UnloadingScope scope(is_alive);
 692   CompiledMethodIterator iter(CompiledMethodIterator::only_alive);
 693   while(iter.next()) {
 694     iter.method()->do_unloading(unloading_occurred);
 695   }
 696 }
 697 
 698 void CodeCache::blobs_do(CodeBlobClosure* f) {
 699   assert_locked_or_safepoint(CodeCache_lock);
 700   FOR_ALL_ALLOCABLE_HEAPS(heap) {
 701     FOR_ALL_BLOBS(cb, *heap) {
 702       if (cb->is_alive()) {
 703         f->do_code_blob(cb);
 704 #ifdef ASSERT
 705         if (cb->is_nmethod()) {
 706           Universe::heap()->verify_nmethod((nmethod*)cb);
 707         }
 708 #endif //ASSERT
 709       }
 710     }
 711   }
 712 }
 713 
 714 // Walk the list of methods which might contain oops to the java heap.
 715 void CodeCache::scavenge_root_nmethods_do(CodeBlobToOopClosure* f) {
 716   assert_locked_or_safepoint(CodeCache_lock);
 717 
 718   const bool fix_relocations = f->fix_relocations();
 719   debug_only(mark_scavenge_root_nmethods());
 720 
 721   nmethod* prev = NULL;
 722   nmethod* cur = scavenge_root_nmethods();
 723   while (cur != NULL) {
 724     debug_only(cur->clear_scavenge_root_marked());
 725     assert(cur->scavenge_root_not_marked(), "");
 726     assert(cur->on_scavenge_root_list(), "else shouldn't be on this list");
 727 
 728     bool is_live = (!cur->is_zombie() && !cur->is_unloaded());
 729     LogTarget(Trace, gc, nmethod) lt;
 730     if (lt.is_enabled()) {
 731       LogStream ls(lt);
 732       CompileTask::print(&ls, cur,
 733         is_live ? "scavenge root " : "dead scavenge root", /*short_form:*/ true);
 734     }
 735     if (is_live) {
 736       // Perform cur->oops_do(f), maybe just once per nmethod.
 737       f->do_code_blob(cur);
 738     }
 739     nmethod* const next = cur->scavenge_root_link();
 740     // The scavengable nmethod list must contain all methods with scavengable
 741     // oops. It is safe to include more nmethod on the list, but we do not
 742     // expect any live non-scavengable nmethods on the list.
 743     if (fix_relocations) {
 744       if (!is_live || !cur->detect_scavenge_root_oops()) {
 745         unlink_scavenge_root_nmethod(cur, prev);
 746       } else {
 747         prev = cur;
 748       }
 749     }
 750     cur = next;
 751   }
 752 
 753   // Check for stray marks.
 754   debug_only(verify_perm_nmethods(NULL));
 755 }
 756 
 757 void CodeCache::register_scavenge_root_nmethod(nmethod* nm) {
 758   assert_locked_or_safepoint(CodeCache_lock);
 759   if (!nm->on_scavenge_root_list() && nm->detect_scavenge_root_oops()) {
 760     add_scavenge_root_nmethod(nm);
 761   }
 762 }
 763 
 764 void CodeCache::verify_scavenge_root_nmethod(nmethod* nm) {
 765   nm->verify_scavenge_root_oops();
 766 }
 767 
 768 void CodeCache::add_scavenge_root_nmethod(nmethod* nm) {
 769   assert_locked_or_safepoint(CodeCache_lock);
 770 
 771   nm->set_on_scavenge_root_list();
 772   nm->set_scavenge_root_link(_scavenge_root_nmethods);
 773   set_scavenge_root_nmethods(nm);
 774   print_trace("add_scavenge_root", nm);
 775 }
 776 
 777 void CodeCache::unlink_scavenge_root_nmethod(nmethod* nm, nmethod* prev) {
 778   assert_locked_or_safepoint(CodeCache_lock);
 779 
 780   assert((prev == NULL && scavenge_root_nmethods() == nm) ||
 781          (prev != NULL && prev->scavenge_root_link() == nm), "precondition");
 782 
 783   print_trace("unlink_scavenge_root", nm);
 784   if (prev == NULL) {
 785     set_scavenge_root_nmethods(nm->scavenge_root_link());
 786   } else {
 787     prev->set_scavenge_root_link(nm->scavenge_root_link());
 788   }
 789   nm->set_scavenge_root_link(NULL);
 790   nm->clear_on_scavenge_root_list();
 791 }
 792 
 793 void CodeCache::drop_scavenge_root_nmethod(nmethod* nm) {
 794   assert_locked_or_safepoint(CodeCache_lock);
 795 
 796   print_trace("drop_scavenge_root", nm);
 797   nmethod* prev = NULL;
 798   for (nmethod* cur = scavenge_root_nmethods(); cur != NULL; cur = cur->scavenge_root_link()) {
 799     if (cur == nm) {
 800       unlink_scavenge_root_nmethod(cur, prev);
 801       return;
 802     }
 803     prev = cur;
 804   }
 805   assert(false, "should have been on list");
 806 }
 807 
 808 void CodeCache::prune_scavenge_root_nmethods() {
 809   assert_locked_or_safepoint(CodeCache_lock);
 810 
 811   debug_only(mark_scavenge_root_nmethods());
 812 
 813   nmethod* last = NULL;
 814   nmethod* cur = scavenge_root_nmethods();
 815   while (cur != NULL) {
 816     nmethod* next = cur->scavenge_root_link();
 817     debug_only(cur->clear_scavenge_root_marked());
 818     assert(cur->scavenge_root_not_marked(), "");
 819     assert(cur->on_scavenge_root_list(), "else shouldn't be on this list");
 820 
 821     if (!cur->is_zombie() && !cur->is_unloaded()
 822         && cur->detect_scavenge_root_oops()) {
 823       // Keep it.  Advance 'last' to prevent deletion.
 824       last = cur;
 825     } else {
 826       // Prune it from the list, so we don't have to look at it any more.
 827       print_trace("prune_scavenge_root", cur);
 828       unlink_scavenge_root_nmethod(cur, last);
 829     }
 830     cur = next;
 831   }
 832 
 833   // Check for stray marks.
 834   debug_only(verify_perm_nmethods(NULL));
 835 }
 836 
 837 #ifndef PRODUCT
 838 void CodeCache::asserted_non_scavengable_nmethods_do(CodeBlobClosure* f) {
 839   // While we are here, verify the integrity of the list.
 840   mark_scavenge_root_nmethods();
 841   for (nmethod* cur = scavenge_root_nmethods(); cur != NULL; cur = cur->scavenge_root_link()) {
 842     assert(cur->on_scavenge_root_list(), "else shouldn't be on this list");
 843     cur->clear_scavenge_root_marked();
 844   }
 845   verify_perm_nmethods(f);
 846 }
 847 
 848 // Temporarily mark nmethods that are claimed to be on the scavenge list.
 849 void CodeCache::mark_scavenge_root_nmethods() {
 850   NMethodIterator iter(NMethodIterator::only_alive);
 851   while(iter.next()) {
 852     nmethod* nm = iter.method();
 853     assert(nm->scavenge_root_not_marked(), "clean state");
 854     if (nm->on_scavenge_root_list())
 855       nm->set_scavenge_root_marked();
 856   }
 857 }
 858 
 859 // If the closure is given, run it on the unlisted nmethods.
 860 // Also make sure that the effects of mark_scavenge_root_nmethods is gone.
 861 void CodeCache::verify_perm_nmethods(CodeBlobClosure* f_or_null) {
 862   NMethodIterator iter(NMethodIterator::only_alive);
 863   while(iter.next()) {
 864     nmethod* nm = iter.method();
 865     bool call_f = (f_or_null != NULL);
 866     assert(nm->scavenge_root_not_marked(), "must be already processed");
 867     if (nm->on_scavenge_root_list())
 868       call_f = false;  // don't show this one to the client
 869     Universe::heap()->verify_nmethod(nm);
 870     if (call_f)  f_or_null->do_code_blob(nm);
 871   }
 872 }
 873 #endif //PRODUCT
 874 
 875 void CodeCache::verify_clean_inline_caches() {
 876 #ifdef ASSERT
 877   NMethodIterator iter(NMethodIterator::only_alive_and_not_unloading);
 878   while(iter.next()) {
 879     nmethod* nm = iter.method();
 880     assert(!nm->is_unloaded(), "Tautology");
 881     nm->verify_clean_inline_caches();
 882     nm->verify();
 883   }
 884 #endif
 885 }
 886 
 887 void CodeCache::verify_icholder_relocations() {
 888 #ifdef ASSERT
 889   // make sure that we aren't leaking icholders
 890   int count = 0;
 891   FOR_ALL_HEAPS(heap) {
 892     FOR_ALL_BLOBS(cb, *heap) {
 893       CompiledMethod *nm = cb->as_compiled_method_or_null();
 894       if (nm != NULL) {
 895         count += nm->verify_icholder_relocations();
 896       }
 897     }
 898   }
 899   assert(count + InlineCacheBuffer::pending_icholder_count() + CompiledICHolder::live_not_claimed_count() ==
 900          CompiledICHolder::live_count(), "must agree");
 901 #endif
 902 }
 903 
 904 // Defer freeing of concurrently cleaned ExceptionCache entries until
 905 // after a global handshake operation.
 906 void CodeCache::release_exception_cache(ExceptionCache* entry) {
 907   if (SafepointSynchronize::is_at_safepoint()) {
 908     delete entry;
 909   } else {
 910     for (;;) {
 911       ExceptionCache* purge_list_head = Atomic::load(&_exception_cache_purge_list);
 912       entry->set_purge_list_next(purge_list_head);
 913       if (Atomic::cmpxchg(entry, &_exception_cache_purge_list, purge_list_head) == purge_list_head) {
 914         break;
 915       }
 916     }
 917   }
 918 }
 919 
 920 // Delete exception caches that have been concurrently unlinked,
 921 // followed by a global handshake operation.
 922 void CodeCache::purge_exception_caches() {
 923   ExceptionCache* curr = _exception_cache_purge_list;
 924   while (curr != NULL) {
 925     ExceptionCache* next = curr->purge_list_next();
 926     delete curr;
 927     curr = next;
 928   }
 929   _exception_cache_purge_list = NULL;
 930 }
 931 
 932 void CodeCache::gc_prologue() { }
 933 
 934 void CodeCache::gc_epilogue() {
 935   prune_scavenge_root_nmethods();
 936 }
 937 
 938 uint8_t CodeCache::_unloading_cycle = 1;
 939 
 940 void CodeCache::increment_unloading_cycle() {
 941   if (_unloading_cycle == 1) {
 942     _unloading_cycle = 2;
 943   } else {
 944     _unloading_cycle = 1;
 945   }
 946 }
 947 
 948 CodeCache::UnloadingScope::UnloadingScope(BoolObjectClosure* is_alive)
 949   : _is_unloading_behaviour(is_alive)
 950 {
 951   IsUnloadingBehaviour::set_current(&_is_unloading_behaviour);
 952   increment_unloading_cycle();
 953   DependencyContext::cleaning_start();
 954 }
 955 
 956 CodeCache::UnloadingScope::~UnloadingScope() {
 957   IsUnloadingBehaviour::set_current(NULL);
 958   DependencyContext::cleaning_end();
 959 }
 960 
 961 void CodeCache::verify_oops() {
 962   MutexLockerEx mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
 963   VerifyOopClosure voc;
 964   NMethodIterator iter(NMethodIterator::only_alive_and_not_unloading);
 965   while(iter.next()) {
 966     nmethod* nm = iter.method();
 967     nm->oops_do(&voc);
 968     nm->verify_oop_relocations();
 969   }
 970 }
 971 
 972 int CodeCache::blob_count(int code_blob_type) {
 973   CodeHeap* heap = get_code_heap(code_blob_type);
 974   return (heap != NULL) ? heap->blob_count() : 0;
 975 }
 976 
 977 int CodeCache::blob_count() {
 978   int count = 0;
 979   FOR_ALL_HEAPS(heap) {
 980     count += (*heap)->blob_count();
 981   }
 982   return count;
 983 }
 984 
 985 int CodeCache::nmethod_count(int code_blob_type) {
 986   CodeHeap* heap = get_code_heap(code_blob_type);
 987   return (heap != NULL) ? heap->nmethod_count() : 0;
 988 }
 989 
 990 int CodeCache::nmethod_count() {
 991   int count = 0;
 992   FOR_ALL_NMETHOD_HEAPS(heap) {
 993     count += (*heap)->nmethod_count();
 994   }
 995   return count;
 996 }
 997 
 998 int CodeCache::adapter_count(int code_blob_type) {
 999   CodeHeap* heap = get_code_heap(code_blob_type);
1000   return (heap != NULL) ? heap->adapter_count() : 0;
1001 }
1002 
1003 int CodeCache::adapter_count() {
1004   int count = 0;
1005   FOR_ALL_HEAPS(heap) {
1006     count += (*heap)->adapter_count();
1007   }
1008   return count;
1009 }
1010 
1011 address CodeCache::low_bound(int code_blob_type) {
1012   CodeHeap* heap = get_code_heap(code_blob_type);
1013   return (heap != NULL) ? (address)heap->low_boundary() : NULL;
1014 }
1015 
1016 address CodeCache::high_bound(int code_blob_type) {
1017   CodeHeap* heap = get_code_heap(code_blob_type);
1018   return (heap != NULL) ? (address)heap->high_boundary() : NULL;
1019 }
1020 
1021 size_t CodeCache::capacity() {
1022   size_t cap = 0;
1023   FOR_ALL_ALLOCABLE_HEAPS(heap) {
1024     cap += (*heap)->capacity();
1025   }
1026   return cap;
1027 }
1028 
1029 size_t CodeCache::unallocated_capacity(int code_blob_type) {
1030   CodeHeap* heap = get_code_heap(code_blob_type);
1031   return (heap != NULL) ? heap->unallocated_capacity() : 0;
1032 }
1033 
1034 size_t CodeCache::unallocated_capacity() {
1035   size_t unallocated_cap = 0;
1036   FOR_ALL_ALLOCABLE_HEAPS(heap) {
1037     unallocated_cap += (*heap)->unallocated_capacity();
1038   }
1039   return unallocated_cap;
1040 }
1041 
1042 size_t CodeCache::max_capacity() {
1043   size_t max_cap = 0;
1044   FOR_ALL_ALLOCABLE_HEAPS(heap) {
1045     max_cap += (*heap)->max_capacity();
1046   }
1047   return max_cap;
1048 }
1049 
1050 /**
1051  * Returns the reverse free ratio. E.g., if 25% (1/4) of the code heap
1052  * is free, reverse_free_ratio() returns 4.
1053  */
1054 double CodeCache::reverse_free_ratio(int code_blob_type) {
1055   CodeHeap* heap = get_code_heap(code_blob_type);
1056   if (heap == NULL) {
1057     return 0;
1058   }
1059 
1060   double unallocated_capacity = MAX2((double)heap->unallocated_capacity(), 1.0); // Avoid division by 0;
1061   double max_capacity = (double)heap->max_capacity();
1062   double result = max_capacity / unallocated_capacity;
1063   assert (max_capacity >= unallocated_capacity, "Must be");
1064   assert (result >= 1.0, "reverse_free_ratio must be at least 1. It is %f", result);
1065   return result;
1066 }
1067 
1068 size_t CodeCache::bytes_allocated_in_freelists() {
1069   size_t allocated_bytes = 0;
1070   FOR_ALL_ALLOCABLE_HEAPS(heap) {
1071     allocated_bytes += (*heap)->allocated_in_freelist();
1072   }
1073   return allocated_bytes;
1074 }
1075 
1076 int CodeCache::allocated_segments() {
1077   int number_of_segments = 0;
1078   FOR_ALL_ALLOCABLE_HEAPS(heap) {
1079     number_of_segments += (*heap)->allocated_segments();
1080   }
1081   return number_of_segments;
1082 }
1083 
1084 size_t CodeCache::freelists_length() {
1085   size_t length = 0;
1086   FOR_ALL_ALLOCABLE_HEAPS(heap) {
1087     length += (*heap)->freelist_length();
1088   }
1089   return length;
1090 }
1091 
1092 void icache_init();
1093 
1094 void CodeCache::initialize() {
1095   assert(CodeCacheSegmentSize >= (uintx)CodeEntryAlignment, "CodeCacheSegmentSize must be large enough to align entry points");
1096 #ifdef COMPILER2
1097   assert(CodeCacheSegmentSize >= (uintx)OptoLoopAlignment,  "CodeCacheSegmentSize must be large enough to align inner loops");
1098 #endif
1099   assert(CodeCacheSegmentSize >= sizeof(jdouble),    "CodeCacheSegmentSize must be large enough to align constants");
1100   // This was originally just a check of the alignment, causing failure, instead, round
1101   // the code cache to the page size.  In particular, Solaris is moving to a larger
1102   // default page size.
1103   CodeCacheExpansionSize = align_up(CodeCacheExpansionSize, os::vm_page_size());
1104 
1105   if (SegmentedCodeCache) {
1106     // Use multiple code heaps
1107     initialize_heaps();
1108   } else {
1109     // Use a single code heap
1110     FLAG_SET_ERGO(uintx, NonNMethodCodeHeapSize, 0);
1111     FLAG_SET_ERGO(uintx, ProfiledCodeHeapSize, 0);
1112     FLAG_SET_ERGO(uintx, NonProfiledCodeHeapSize, 0);
1113     ReservedCodeSpace rs = reserve_heap_memory(ReservedCodeCacheSize);
1114     add_heap(rs, "CodeCache", CodeBlobType::All);
1115   }
1116 
1117   // Initialize ICache flush mechanism
1118   // This service is needed for os::register_code_area
1119   icache_init();
1120 
1121   // Give OS a chance to register generated code area.
1122   // This is used on Windows 64 bit platforms to register
1123   // Structured Exception Handlers for our generated code.
1124   os::register_code_area((char*)low_bound(), (char*)high_bound());
1125 }
1126 
1127 void codeCache_init() {
1128   CodeCache::initialize();
1129   // Load AOT libraries and add AOT code heaps.
1130   AOTLoader::initialize();
1131 }
1132 
1133 //------------------------------------------------------------------------------------------------
1134 
1135 int CodeCache::number_of_nmethods_with_dependencies() {
1136   return _number_of_nmethods_with_dependencies;
1137 }
1138 
1139 void CodeCache::clear_inline_caches() {
1140   assert_locked_or_safepoint(CodeCache_lock);
1141   CompiledMethodIterator iter(CompiledMethodIterator::only_alive_and_not_unloading);
1142   while(iter.next()) {
1143     iter.method()->clear_inline_caches();
1144   }
1145 }
1146 
1147 void CodeCache::cleanup_inline_caches() {
1148   assert_locked_or_safepoint(CodeCache_lock);
1149   NMethodIterator iter(NMethodIterator::only_alive_and_not_unloading);
1150   while(iter.next()) {
1151     iter.method()->cleanup_inline_caches(/*clean_all=*/true);
1152   }
1153 }
1154 
1155 // Keeps track of time spent for checking dependencies
1156 NOT_PRODUCT(static elapsedTimer dependentCheckTime;)
1157 
1158 int CodeCache::mark_for_deoptimization(KlassDepChange& changes) {
1159   MutexLockerEx mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
1160   int number_of_marked_CodeBlobs = 0;
1161 
1162   // search the hierarchy looking for nmethods which are affected by the loading of this class
1163 
1164   // then search the interfaces this class implements looking for nmethods
1165   // which might be dependent of the fact that an interface only had one
1166   // implementor.
1167   // nmethod::check_all_dependencies works only correctly, if no safepoint
1168   // can happen
1169   NoSafepointVerifier nsv;
1170   for (DepChange::ContextStream str(changes, nsv); str.next(); ) {
1171     Klass* d = str.klass();
1172     number_of_marked_CodeBlobs += InstanceKlass::cast(d)->mark_dependent_nmethods(changes);
1173   }
1174 
1175 #ifndef PRODUCT
1176   if (VerifyDependencies) {
1177     // Object pointers are used as unique identifiers for dependency arguments. This
1178     // is only possible if no safepoint, i.e., GC occurs during the verification code.
1179     dependentCheckTime.start();
1180     nmethod::check_all_dependencies(changes);
1181     dependentCheckTime.stop();
1182   }
1183 #endif
1184 
1185   return number_of_marked_CodeBlobs;
1186 }
1187 
1188 CompiledMethod* CodeCache::find_compiled(void* start) {
1189   CodeBlob *cb = find_blob(start);
1190   assert(cb == NULL || cb->is_compiled(), "did not find an compiled_method");
1191   return (CompiledMethod*)cb;
1192 }
1193 
1194 bool CodeCache::is_far_target(address target) {
1195 #if INCLUDE_AOT
1196   return NativeCall::is_far_call(_low_bound,  target) ||
1197          NativeCall::is_far_call(_high_bound, target);
1198 #else
1199   return false;
1200 #endif
1201 }
1202 
1203 // Just marks the methods in this class as needing deoptimization
1204 void CodeCache::mark_for_evol_deoptimization(InstanceKlass* dependee) {
1205   MutexLockerEx mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
1206 
1207   // Deoptimize all methods of the evolving class itself
1208   Array<Method*>* old_methods = dependee->methods();
1209   for (int i = 0; i < old_methods->length(); i++) {
1210     ResourceMark rm;
1211     Method* old_method = old_methods->at(i);
1212     CompiledMethod* nm = old_method->code();
1213     if (nm != NULL) {
1214       nm->mark_for_deoptimization();
1215     }
1216   }
1217 
1218   // Mark dependent AOT nmethods, which are only found via the class redefined.
1219   AOTLoader::mark_evol_dependent_methods(dependee);
1220 }
1221 
1222 // Walk compiled methods and mark dependent methods for deoptimization.
1223 int CodeCache::mark_dependents_for_evol_deoptimization() {
1224   int number_of_marked_CodeBlobs = 0;
1225   CompiledMethodIterator iter(CompiledMethodIterator::only_alive_and_not_unloading);
1226   while(iter.next()) {
1227     CompiledMethod* nm = iter.method();
1228     if (nm->is_marked_for_deoptimization()) {
1229       // ...Already marked in the previous pass; count it here.
1230       // Also counts AOT compiled methods, already marked.
1231       number_of_marked_CodeBlobs++;
1232     } else if (nm->is_evol_dependent()) {
1233       ResourceMark rm;
1234       nm->mark_for_deoptimization();
1235       number_of_marked_CodeBlobs++;
1236     } else  {
1237       // flush caches in case they refer to a redefined Method*
1238       nm->clear_inline_caches();
1239     }
1240   }
1241 
1242   // return total count of nmethods marked for deoptimization, if zero the caller
1243   // can skip deoptimization
1244   return number_of_marked_CodeBlobs;
1245 }
1246 
1247 // Deoptimize all methods
1248 void CodeCache::mark_all_nmethods_for_deoptimization() {
1249   MutexLockerEx mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
1250   CompiledMethodIterator iter(CompiledMethodIterator::only_alive_and_not_unloading);
1251   while(iter.next()) {
1252     CompiledMethod* nm = iter.method();
1253     if (!nm->method()->is_method_handle_intrinsic()) {
1254       nm->mark_for_deoptimization();
1255     }
1256   }
1257 }
1258 
1259 int CodeCache::mark_for_deoptimization(Method* dependee) {
1260   MutexLockerEx mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
1261   int number_of_marked_CodeBlobs = 0;
1262 
1263   CompiledMethodIterator iter(CompiledMethodIterator::only_alive_and_not_unloading);
1264   while(iter.next()) {
1265     CompiledMethod* nm = iter.method();
1266     if (nm->is_dependent_on_method(dependee)) {
1267       ResourceMark rm;
1268       nm->mark_for_deoptimization();
1269       number_of_marked_CodeBlobs++;
1270     }
1271   }
1272 
1273   return number_of_marked_CodeBlobs;
1274 }
1275 
1276 void CodeCache::make_marked_nmethods_not_entrant() {
1277   assert_locked_or_safepoint(CodeCache_lock);
1278   CompiledMethodIterator iter(CompiledMethodIterator::only_alive_and_not_unloading);
1279   while(iter.next()) {
1280     CompiledMethod* nm = iter.method();
1281     if (nm->is_marked_for_deoptimization() && !nm->is_not_entrant()) {
1282       nm->make_not_entrant();
1283     }
1284   }
1285 }
1286 
1287 // Flushes compiled methods dependent on dependee.
1288 void CodeCache::flush_dependents_on(InstanceKlass* dependee) {
1289   assert_lock_strong(Compile_lock);
1290 
1291   if (number_of_nmethods_with_dependencies() == 0) return;
1292 
1293   // CodeCache can only be updated by a thread_in_VM and they will all be
1294   // stopped during the safepoint so CodeCache will be safe to update without
1295   // holding the CodeCache_lock.
1296 
1297   KlassDepChange changes(dependee);
1298 
1299   // Compute the dependent nmethods
1300   if (mark_for_deoptimization(changes) > 0) {
1301     // At least one nmethod has been marked for deoptimization
1302     VM_Deoptimize op;
1303     VMThread::execute(&op);
1304   }
1305 }
1306 
1307 // Flushes compiled methods dependent on redefined classes, that have already been
1308 // marked for deoptimization.
1309 void CodeCache::flush_evol_dependents() {
1310   // --- Compile_lock is not held. However we are at a safepoint.
1311   assert_locked_or_safepoint(Compile_lock);
1312 
1313   // CodeCache can only be updated by a thread_in_VM and they will all be
1314   // stopped during the safepoint so CodeCache will be safe to update without
1315   // holding the CodeCache_lock.
1316 
1317   // At least one nmethod has been marked for deoptimization
1318 
1319   // All this already happens inside a VM_Operation, so we'll do all the work here.
1320   // Stuff copied from VM_Deoptimize and modified slightly.
1321 
1322   // We do not want any GCs to happen while we are in the middle of this VM operation
1323   ResourceMark rm;
1324   DeoptimizationMarker dm;
1325 
1326   // Deoptimize all activations depending on marked nmethods
1327   Deoptimization::deoptimize_dependents();
1328 
1329   // Make the dependent methods not entrant
1330   make_marked_nmethods_not_entrant();
1331 }
1332 
1333 // Flushes compiled methods dependent on dependee
1334 void CodeCache::flush_dependents_on_method(const methodHandle& m_h) {
1335   // --- Compile_lock is not held. However we are at a safepoint.
1336   assert_locked_or_safepoint(Compile_lock);
1337 
1338   // CodeCache can only be updated by a thread_in_VM and they will all be
1339   // stopped dring the safepoint so CodeCache will be safe to update without
1340   // holding the CodeCache_lock.
1341 
1342   // Compute the dependent nmethods
1343   if (mark_for_deoptimization(m_h()) > 0) {
1344     // At least one nmethod has been marked for deoptimization
1345 
1346     // All this already happens inside a VM_Operation, so we'll do all the work here.
1347     // Stuff copied from VM_Deoptimize and modified slightly.
1348 
1349     // We do not want any GCs to happen while we are in the middle of this VM operation
1350     ResourceMark rm;
1351     DeoptimizationMarker dm;
1352 
1353     // Deoptimize all activations depending on marked nmethods
1354     Deoptimization::deoptimize_dependents();
1355 
1356     // Make the dependent methods not entrant
1357     make_marked_nmethods_not_entrant();
1358   }
1359 }
1360 
1361 void CodeCache::verify() {
1362   assert_locked_or_safepoint(CodeCache_lock);
1363   FOR_ALL_HEAPS(heap) {
1364     (*heap)->verify();
1365     FOR_ALL_BLOBS(cb, *heap) {
1366       if (cb->is_alive()) {
1367         cb->verify();
1368       }
1369     }
1370   }
1371 }
1372 
1373 // A CodeHeap is full. Print out warning and report event.
1374 PRAGMA_DIAG_PUSH
1375 PRAGMA_FORMAT_NONLITERAL_IGNORED
1376 void CodeCache::report_codemem_full(int code_blob_type, bool print) {
1377   // Get nmethod heap for the given CodeBlobType and build CodeCacheFull event
1378   CodeHeap* heap = get_code_heap(code_blob_type);
1379   assert(heap != NULL, "heap is null");
1380 
1381   if ((heap->full_count() == 0) || print) {
1382     // Not yet reported for this heap, report
1383     if (SegmentedCodeCache) {
1384       ResourceMark rm;
1385       stringStream msg1_stream, msg2_stream;
1386       msg1_stream.print("%s is full. Compiler has been disabled.",
1387                         get_code_heap_name(code_blob_type));
1388       msg2_stream.print("Try increasing the code heap size using -XX:%s=",
1389                  get_code_heap_flag_name(code_blob_type));
1390       const char *msg1 = msg1_stream.as_string();
1391       const char *msg2 = msg2_stream.as_string();
1392 
1393       log_warning(codecache)("%s", msg1);
1394       log_warning(codecache)("%s", msg2);
1395       warning("%s", msg1);
1396       warning("%s", msg2);
1397     } else {
1398       const char *msg1 = "CodeCache is full. Compiler has been disabled.";
1399       const char *msg2 = "Try increasing the code cache size using -XX:ReservedCodeCacheSize=";
1400 
1401       log_warning(codecache)("%s", msg1);
1402       log_warning(codecache)("%s", msg2);
1403       warning("%s", msg1);
1404       warning("%s", msg2);
1405     }
1406     ResourceMark rm;
1407     stringStream s;
1408     // Dump code cache into a buffer before locking the tty.
1409     {
1410       MutexLockerEx mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
1411       print_summary(&s);
1412     }
1413     {
1414       ttyLocker ttyl;
1415       tty->print("%s", s.as_string());
1416     }
1417 
1418     if (heap->full_count() == 0) {
1419       if (PrintCodeHeapAnalytics) {
1420         CompileBroker::print_heapinfo(tty, "all", "4096"); // details, may be a lot!
1421       }
1422     }
1423   }
1424 
1425   heap->report_full();
1426 
1427   EventCodeCacheFull event;
1428   if (event.should_commit()) {
1429     event.set_codeBlobType((u1)code_blob_type);
1430     event.set_startAddress((u8)heap->low_boundary());
1431     event.set_commitedTopAddress((u8)heap->high());
1432     event.set_reservedTopAddress((u8)heap->high_boundary());
1433     event.set_entryCount(heap->blob_count());
1434     event.set_methodCount(heap->nmethod_count());
1435     event.set_adaptorCount(heap->adapter_count());
1436     event.set_unallocatedCapacity(heap->unallocated_capacity());
1437     event.set_fullCount(heap->full_count());
1438     event.commit();
1439   }
1440 }
1441 PRAGMA_DIAG_POP
1442 
1443 void CodeCache::print_memory_overhead() {
1444   size_t wasted_bytes = 0;
1445   FOR_ALL_ALLOCABLE_HEAPS(heap) {
1446       CodeHeap* curr_heap = *heap;
1447       for (CodeBlob* cb = (CodeBlob*)curr_heap->first(); cb != NULL; cb = (CodeBlob*)curr_heap->next(cb)) {
1448         HeapBlock* heap_block = ((HeapBlock*)cb) - 1;
1449         wasted_bytes += heap_block->length() * CodeCacheSegmentSize - cb->size();
1450       }
1451   }
1452   // Print bytes that are allocated in the freelist
1453   ttyLocker ttl;
1454   tty->print_cr("Number of elements in freelist: " SSIZE_FORMAT,       freelists_length());
1455   tty->print_cr("Allocated in freelist:          " SSIZE_FORMAT "kB",  bytes_allocated_in_freelists()/K);
1456   tty->print_cr("Unused bytes in CodeBlobs:      " SSIZE_FORMAT "kB",  (wasted_bytes/K));
1457   tty->print_cr("Segment map size:               " SSIZE_FORMAT "kB",  allocated_segments()/K); // 1 byte per segment
1458 }
1459 
1460 //------------------------------------------------------------------------------------------------
1461 // Non-product version
1462 
1463 #ifndef PRODUCT
1464 
1465 void CodeCache::print_trace(const char* event, CodeBlob* cb, int size) {
1466   if (PrintCodeCache2) {  // Need to add a new flag
1467     ResourceMark rm;
1468     if (size == 0)  size = cb->size();
1469     tty->print_cr("CodeCache %s:  addr: " INTPTR_FORMAT ", size: 0x%x", event, p2i(cb), size);
1470   }
1471 }
1472 
1473 void CodeCache::print_internals() {
1474   int nmethodCount = 0;
1475   int runtimeStubCount = 0;
1476   int adapterCount = 0;
1477   int deoptimizationStubCount = 0;
1478   int uncommonTrapStubCount = 0;
1479   int bufferBlobCount = 0;
1480   int total = 0;
1481   int nmethodAlive = 0;
1482   int nmethodNotEntrant = 0;
1483   int nmethodZombie = 0;
1484   int nmethodUnloaded = 0;
1485   int nmethodJava = 0;
1486   int nmethodNative = 0;
1487   int max_nm_size = 0;
1488   ResourceMark rm;
1489 
1490   int i = 0;
1491   FOR_ALL_ALLOCABLE_HEAPS(heap) {
1492     if ((_nmethod_heaps->length() >= 1) && Verbose) {
1493       tty->print_cr("-- %s --", (*heap)->name());
1494     }
1495     FOR_ALL_BLOBS(cb, *heap) {
1496       total++;
1497       if (cb->is_nmethod()) {
1498         nmethod* nm = (nmethod*)cb;
1499 
1500         if (Verbose && nm->method() != NULL) {
1501           ResourceMark rm;
1502           char *method_name = nm->method()->name_and_sig_as_C_string();
1503           tty->print("%s", method_name);
1504           if(nm->is_alive()) { tty->print_cr(" alive"); }
1505           if(nm->is_not_entrant()) { tty->print_cr(" not-entrant"); }
1506           if(nm->is_zombie()) { tty->print_cr(" zombie"); }
1507         }
1508 
1509         nmethodCount++;
1510 
1511         if(nm->is_alive()) { nmethodAlive++; }
1512         if(nm->is_not_entrant()) { nmethodNotEntrant++; }
1513         if(nm->is_zombie()) { nmethodZombie++; }
1514         if(nm->is_unloaded()) { nmethodUnloaded++; }
1515         if(nm->method() != NULL && nm->is_native_method()) { nmethodNative++; }
1516 
1517         if(nm->method() != NULL && nm->is_java_method()) {
1518           nmethodJava++;
1519           max_nm_size = MAX2(max_nm_size, nm->size());
1520         }
1521       } else if (cb->is_runtime_stub()) {
1522         runtimeStubCount++;
1523       } else if (cb->is_deoptimization_stub()) {
1524         deoptimizationStubCount++;
1525       } else if (cb->is_uncommon_trap_stub()) {
1526         uncommonTrapStubCount++;
1527       } else if (cb->is_adapter_blob()) {
1528         adapterCount++;
1529       } else if (cb->is_buffer_blob()) {
1530         bufferBlobCount++;
1531       }
1532     }
1533   }
1534 
1535   int bucketSize = 512;
1536   int bucketLimit = max_nm_size / bucketSize + 1;
1537   int *buckets = NEW_C_HEAP_ARRAY(int, bucketLimit, mtCode);
1538   memset(buckets, 0, sizeof(int) * bucketLimit);
1539 
1540   NMethodIterator iter(NMethodIterator::all_blobs);
1541   while(iter.next()) {
1542     nmethod* nm = iter.method();
1543     if(nm->method() != NULL && nm->is_java_method()) {
1544       buckets[nm->size() / bucketSize]++;
1545     }
1546   }
1547 
1548   tty->print_cr("Code Cache Entries (total of %d)",total);
1549   tty->print_cr("-------------------------------------------------");
1550   tty->print_cr("nmethods: %d",nmethodCount);
1551   tty->print_cr("\talive: %d",nmethodAlive);
1552   tty->print_cr("\tnot_entrant: %d",nmethodNotEntrant);
1553   tty->print_cr("\tzombie: %d",nmethodZombie);
1554   tty->print_cr("\tunloaded: %d",nmethodUnloaded);
1555   tty->print_cr("\tjava: %d",nmethodJava);
1556   tty->print_cr("\tnative: %d",nmethodNative);
1557   tty->print_cr("runtime_stubs: %d",runtimeStubCount);
1558   tty->print_cr("adapters: %d",adapterCount);
1559   tty->print_cr("buffer blobs: %d",bufferBlobCount);
1560   tty->print_cr("deoptimization_stubs: %d",deoptimizationStubCount);
1561   tty->print_cr("uncommon_traps: %d",uncommonTrapStubCount);
1562   tty->print_cr("\nnmethod size distribution (non-zombie java)");
1563   tty->print_cr("-------------------------------------------------");
1564 
1565   for(int i=0; i<bucketLimit; i++) {
1566     if(buckets[i] != 0) {
1567       tty->print("%d - %d bytes",i*bucketSize,(i+1)*bucketSize);
1568       tty->fill_to(40);
1569       tty->print_cr("%d",buckets[i]);
1570     }
1571   }
1572 
1573   FREE_C_HEAP_ARRAY(int, buckets);
1574   print_memory_overhead();
1575 }
1576 
1577 #endif // !PRODUCT
1578 
1579 void CodeCache::print() {
1580   print_summary(tty);
1581 
1582 #ifndef PRODUCT
1583   if (!Verbose) return;
1584 
1585   CodeBlob_sizes live;
1586   CodeBlob_sizes dead;
1587 
1588   FOR_ALL_ALLOCABLE_HEAPS(heap) {
1589     FOR_ALL_BLOBS(cb, *heap) {
1590       if (!cb->is_alive()) {
1591         dead.add(cb);
1592       } else {
1593         live.add(cb);
1594       }
1595     }
1596   }
1597 
1598   tty->print_cr("CodeCache:");
1599   tty->print_cr("nmethod dependency checking time %fs", dependentCheckTime.seconds());
1600 
1601   if (!live.is_empty()) {
1602     live.print("live");
1603   }
1604   if (!dead.is_empty()) {
1605     dead.print("dead");
1606   }
1607 
1608   if (WizardMode) {
1609      // print the oop_map usage
1610     int code_size = 0;
1611     int number_of_blobs = 0;
1612     int number_of_oop_maps = 0;
1613     int map_size = 0;
1614     FOR_ALL_ALLOCABLE_HEAPS(heap) {
1615       FOR_ALL_BLOBS(cb, *heap) {
1616         if (cb->is_alive()) {
1617           number_of_blobs++;
1618           code_size += cb->code_size();
1619           ImmutableOopMapSet* set = cb->oop_maps();
1620           if (set != NULL) {
1621             number_of_oop_maps += set->count();
1622             map_size           += set->nr_of_bytes();
1623           }
1624         }
1625       }
1626     }
1627     tty->print_cr("OopMaps");
1628     tty->print_cr("  #blobs    = %d", number_of_blobs);
1629     tty->print_cr("  code size = %d", code_size);
1630     tty->print_cr("  #oop_maps = %d", number_of_oop_maps);
1631     tty->print_cr("  map size  = %d", map_size);
1632   }
1633 
1634 #endif // !PRODUCT
1635 }
1636 
1637 void CodeCache::print_summary(outputStream* st, bool detailed) {
1638   int full_count = 0;
1639   FOR_ALL_HEAPS(heap_iterator) {
1640     CodeHeap* heap = (*heap_iterator);
1641     size_t total = (heap->high_boundary() - heap->low_boundary());
1642     if (_heaps->length() >= 1) {
1643       st->print("%s:", heap->name());
1644     } else {
1645       st->print("CodeCache:");
1646     }
1647     st->print_cr(" size=" SIZE_FORMAT "Kb used=" SIZE_FORMAT
1648                  "Kb max_used=" SIZE_FORMAT "Kb free=" SIZE_FORMAT "Kb",
1649                  total/K, (total - heap->unallocated_capacity())/K,
1650                  heap->max_allocated_capacity()/K, heap->unallocated_capacity()/K);
1651 
1652     if (detailed) {
1653       st->print_cr(" bounds [" INTPTR_FORMAT ", " INTPTR_FORMAT ", " INTPTR_FORMAT "]",
1654                    p2i(heap->low_boundary()),
1655                    p2i(heap->high()),
1656                    p2i(heap->high_boundary()));
1657 
1658       full_count += get_codemem_full_count(heap->code_blob_type());
1659     }
1660   }
1661 
1662   if (detailed) {
1663     st->print_cr(" total_blobs=" UINT32_FORMAT " nmethods=" UINT32_FORMAT
1664                        " adapters=" UINT32_FORMAT,
1665                        blob_count(), nmethod_count(), adapter_count());
1666     st->print_cr(" compilation: %s", CompileBroker::should_compile_new_jobs() ?
1667                  "enabled" : Arguments::mode() == Arguments::_int ?
1668                  "disabled (interpreter mode)" :
1669                  "disabled (not enough contiguous free space left)");
1670     st->print_cr("              stopped_count=%d, restarted_count=%d",
1671                  CompileBroker::get_total_compiler_stopped_count(),
1672                  CompileBroker::get_total_compiler_restarted_count());
1673     st->print_cr(" full_count=%d", full_count);
1674   }
1675 }
1676 
1677 void CodeCache::print_codelist(outputStream* st) {
1678   MutexLockerEx mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
1679 
1680   CompiledMethodIterator iter(CompiledMethodIterator::only_alive_and_not_unloading);
1681   while (iter.next()) {
1682     CompiledMethod* cm = iter.method();
1683     ResourceMark rm;
1684     char* method_name = cm->method()->name_and_sig_as_C_string();
1685     st->print_cr("%d %d %d %s [" INTPTR_FORMAT ", " INTPTR_FORMAT " - " INTPTR_FORMAT "]",
1686                  cm->compile_id(), cm->comp_level(), cm->get_state(),
1687                  method_name,
1688                  (intptr_t)cm->header_begin(), (intptr_t)cm->code_begin(), (intptr_t)cm->code_end());
1689   }
1690 }
1691 
1692 void CodeCache::print_layout(outputStream* st) {
1693   MutexLockerEx mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
1694   ResourceMark rm;
1695   print_summary(st, true);
1696 }
1697 
1698 void CodeCache::log_state(outputStream* st) {
1699   st->print(" total_blobs='" UINT32_FORMAT "' nmethods='" UINT32_FORMAT "'"
1700             " adapters='" UINT32_FORMAT "' free_code_cache='" SIZE_FORMAT "'",
1701             blob_count(), nmethod_count(), adapter_count(),
1702             unallocated_capacity());
1703 }
1704 
1705 //---<  BEGIN  >--- CodeHeap State Analytics.
1706 
1707 void CodeCache::aggregate(outputStream *out, const char* granularity) {
1708   FOR_ALL_ALLOCABLE_HEAPS(heap) {
1709     CodeHeapState::aggregate(out, (*heap), granularity);
1710   }
1711 }
1712 
1713 void CodeCache::discard(outputStream *out) {
1714   FOR_ALL_ALLOCABLE_HEAPS(heap) {
1715     CodeHeapState::discard(out, (*heap));
1716   }
1717 }
1718 
1719 void CodeCache::print_usedSpace(outputStream *out) {
1720   FOR_ALL_ALLOCABLE_HEAPS(heap) {
1721     CodeHeapState::print_usedSpace(out, (*heap));
1722   }
1723 }
1724 
1725 void CodeCache::print_freeSpace(outputStream *out) {
1726   FOR_ALL_ALLOCABLE_HEAPS(heap) {
1727     CodeHeapState::print_freeSpace(out, (*heap));
1728   }
1729 }
1730 
1731 void CodeCache::print_count(outputStream *out) {
1732   FOR_ALL_ALLOCABLE_HEAPS(heap) {
1733     CodeHeapState::print_count(out, (*heap));
1734   }
1735 }
1736 
1737 void CodeCache::print_space(outputStream *out) {
1738   FOR_ALL_ALLOCABLE_HEAPS(heap) {
1739     CodeHeapState::print_space(out, (*heap));
1740   }
1741 }
1742 
1743 void CodeCache::print_age(outputStream *out) {
1744   FOR_ALL_ALLOCABLE_HEAPS(heap) {
1745     CodeHeapState::print_age(out, (*heap));
1746   }
1747 }
1748 
1749 void CodeCache::print_names(outputStream *out) {
1750   FOR_ALL_ALLOCABLE_HEAPS(heap) {
1751     CodeHeapState::print_names(out, (*heap));
1752   }
1753 }
1754 //---<  END  >--- CodeHeap State Analytics.