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 "memory/universe.hpp"
  44 #include "oops/method.inline.hpp"
  45 #include "oops/objArrayOop.hpp"
  46 #include "oops/oop.inline.hpp"
  47 #include "oops/verifyOopClosure.hpp"
  48 #include "runtime/arguments.hpp"
  49 #include "runtime/compilationPolicy.hpp"
  50 #include "runtime/deoptimization.hpp"
  51 #include "runtime/handles.inline.hpp"
  52 #include "runtime/icache.hpp"
  53 #include "runtime/java.hpp"
  54 #include "runtime/mutexLocker.hpp"
  55 #include "runtime/safepointVerifiers.hpp"
  56 #include "runtime/sweeper.hpp"
  57 #include "runtime/vmThread.hpp"
  58 #include "services/memoryService.hpp"
  59 #include "utilities/align.hpp"
  60 #include "utilities/vmError.hpp"
  61 #include "utilities/xmlstream.hpp"
  62 #ifdef COMPILER1
  63 #include "c1/c1_Compilation.hpp"
  64 #include "c1/c1_Compiler.hpp"
  65 #endif
  66 #ifdef COMPILER2
  67 #include "opto/c2compiler.hpp"
  68 #include "opto/compile.hpp"
  69 #include "opto/node.hpp"
  70 #endif
  71 
  72 // Helper class for printing in CodeCache
  73 class CodeBlob_sizes {
  74  private:
  75   int count;
  76   int total_size;
  77   int header_size;
  78   int code_size;
  79   int stub_size;
  80   int relocation_size;
  81   int scopes_oop_size;
  82   int scopes_metadata_size;
  83   int scopes_data_size;
  84   int scopes_pcs_size;
  85 
  86  public:
  87   CodeBlob_sizes() {
  88     count            = 0;
  89     total_size       = 0;
  90     header_size      = 0;
  91     code_size        = 0;
  92     stub_size        = 0;
  93     relocation_size  = 0;
  94     scopes_oop_size  = 0;
  95     scopes_metadata_size  = 0;
  96     scopes_data_size = 0;
  97     scopes_pcs_size  = 0;
  98   }
  99 
 100   int total()                                    { return total_size; }
 101   bool is_empty()                                { return count == 0; }
 102 
 103   void print(const char* title) {
 104     tty->print_cr(" #%d %s = %dK (hdr %d%%,  loc %d%%, code %d%%, stub %d%%, [oops %d%%, metadata %d%%, data %d%%, pcs %d%%])",
 105                   count,
 106                   title,
 107                   (int)(total() / K),
 108                   header_size             * 100 / total_size,
 109                   relocation_size         * 100 / total_size,
 110                   code_size               * 100 / total_size,
 111                   stub_size               * 100 / total_size,
 112                   scopes_oop_size         * 100 / total_size,
 113                   scopes_metadata_size    * 100 / total_size,
 114                   scopes_data_size        * 100 / total_size,
 115                   scopes_pcs_size         * 100 / total_size);
 116   }
 117 
 118   void add(CodeBlob* cb) {
 119     count++;
 120     total_size       += cb->size();
 121     header_size      += cb->header_size();
 122     relocation_size  += cb->relocation_size();
 123     if (cb->is_nmethod()) {
 124       nmethod* nm = cb->as_nmethod_or_null();
 125       code_size        += nm->insts_size();
 126       stub_size        += nm->stub_size();
 127 
 128       scopes_oop_size  += nm->oops_size();
 129       scopes_metadata_size  += nm->metadata_size();
 130       scopes_data_size += nm->scopes_data_size();
 131       scopes_pcs_size  += nm->scopes_pcs_size();
 132     } else {
 133       code_size        += cb->code_size();
 134     }
 135   }
 136 };
 137 
 138 // Iterate over all CodeHeaps
 139 #define FOR_ALL_HEAPS(heap) for (GrowableArrayIterator<CodeHeap*> heap = _heaps->begin(); heap != _heaps->end(); ++heap)
 140 #define FOR_ALL_NMETHOD_HEAPS(heap) for (GrowableArrayIterator<CodeHeap*> heap = _nmethod_heaps->begin(); heap != _nmethod_heaps->end(); ++heap)
 141 #define FOR_ALL_ALLOCABLE_HEAPS(heap) for (GrowableArrayIterator<CodeHeap*> heap = _allocable_heaps->begin(); heap != _allocable_heaps->end(); ++heap)
 142 
 143 // Iterate over all CodeBlobs (cb) on the given CodeHeap
 144 #define FOR_ALL_BLOBS(cb, heap) for (CodeBlob* cb = first_blob(heap); cb != NULL; cb = next_blob(heap, cb))
 145 
 146 address CodeCache::_low_bound = 0;
 147 address CodeCache::_high_bound = 0;
 148 int CodeCache::_number_of_nmethods_with_dependencies = 0;
 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(NonNMethodCodeHeapSize, non_nmethod_size);
 287   FLAG_SET_ERGO(ProfiledCodeHeapSize, profiled_size);
 288   FLAG_SET_ERGO(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       MutexUnlocker 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 CodeBlob* CodeCache::patch_nop(NativePostCallNop* nop, void* pc, int& slot) {
 649   CodeBlob* cb = CodeCache::find_blob(pc);
 650   int oopmap_slot = cb->oop_maps()->find_slot_for_offset((intptr_t) pc - (intptr_t) cb->code_begin());
 651   intptr_t cbaddr = (intptr_t) cb;
 652   intptr_t offset = ((intptr_t) pc) - cbaddr;
 653 
 654   if (((oopmap_slot & 0xff) == oopmap_slot) && ((offset & 0xffffff) == offset)) {
 655     jint value = (oopmap_slot << 24) | (jint) offset;
 656     nop->patch(value);
 657     slot = oopmap_slot;
 658   } else {
 659     slot = -1;
 660     log_debug(codecache)("failed to encode %d %d", oopmap_slot, (int) offset);
 661   }
 662 #ifdef CONT_DOUBLE_NOP
 663   assert (!nop->is_mode2(), "");
 664 #endif
 665   return cb;
 666 }
 667 
 668 nmethod* CodeCache::find_nmethod(void* start) {
 669   CodeBlob* cb = find_blob(start);
 670   assert(cb->is_nmethod(), "did not find an nmethod");
 671   return (nmethod*)cb;
 672 }
 673 
 674 void CodeCache::blobs_do(void f(CodeBlob* nm)) {
 675   assert_locked_or_safepoint(CodeCache_lock);
 676   FOR_ALL_HEAPS(heap) {
 677     FOR_ALL_BLOBS(cb, *heap) {
 678       f(cb);
 679     }
 680   }
 681 }
 682 
 683 void CodeCache::nmethods_do(void f(nmethod* nm)) {
 684   assert_locked_or_safepoint(CodeCache_lock);
 685   NMethodIterator iter(NMethodIterator::all_blobs);
 686   while(iter.next()) {
 687     f(iter.method());
 688   }
 689 }
 690 
 691 void CodeCache::metadata_do(MetadataClosure* f) {
 692   assert_locked_or_safepoint(CodeCache_lock);
 693   NMethodIterator iter(NMethodIterator::only_alive_and_not_unloading);
 694   while(iter.next()) {
 695     iter.method()->metadata_do(f);
 696   }
 697   AOTLoader::metadata_do(f);
 698 }
 699 
 700 int CodeCache::alignment_unit() {
 701   return (int)_heaps->first()->alignment_unit();
 702 }
 703 
 704 int CodeCache::alignment_offset() {
 705   return (int)_heaps->first()->alignment_offset();
 706 }
 707 
 708 // Mark nmethods for unloading if they contain otherwise unreachable oops.
 709 void CodeCache::do_unloading(BoolObjectClosure* is_alive, bool unloading_occurred) {
 710   assert_locked_or_safepoint(CodeCache_lock);
 711   UnloadingScope scope(is_alive);
 712   CompiledMethodIterator iter(CompiledMethodIterator::only_alive);
 713   while(iter.next()) {
 714     iter.method()->do_unloading(unloading_occurred);
 715   }
 716 }
 717 
 718 void CodeCache::blobs_do(CodeBlobClosure* f) {
 719   assert_locked_or_safepoint(CodeCache_lock);
 720   FOR_ALL_ALLOCABLE_HEAPS(heap) {
 721     FOR_ALL_BLOBS(cb, *heap) {
 722       if (cb->is_alive()) {
 723         f->do_code_blob(cb);
 724 #ifdef ASSERT
 725         if (cb->is_nmethod()) {
 726           Universe::heap()->verify_nmethod((nmethod*)cb);
 727         }
 728 #endif //ASSERT
 729       }
 730     }
 731   }
 732 }
 733 
 734 void CodeCache::verify_clean_inline_caches() {
 735 #ifdef ASSERT
 736   NMethodIterator iter(NMethodIterator::only_alive_and_not_unloading);
 737   while(iter.next()) {
 738     nmethod* nm = iter.method();
 739     assert(!nm->is_unloaded(), "Tautology");
 740     nm->verify_clean_inline_caches();
 741     nm->verify();
 742   }
 743 #endif
 744 }
 745 
 746 void CodeCache::verify_icholder_relocations() {
 747 #ifdef ASSERT
 748   // make sure that we aren't leaking icholders
 749   int count = 0;
 750   FOR_ALL_HEAPS(heap) {
 751     FOR_ALL_BLOBS(cb, *heap) {
 752       CompiledMethod *nm = cb->as_compiled_method_or_null();
 753       if (nm != NULL) {
 754         count += nm->verify_icholder_relocations();
 755       }
 756     }
 757   }
 758   assert(count + InlineCacheBuffer::pending_icholder_count() + CompiledICHolder::live_not_claimed_count() ==
 759          CompiledICHolder::live_count(), "must agree");
 760 #endif
 761 }
 762 
 763 // Defer freeing of concurrently cleaned ExceptionCache entries until
 764 // after a global handshake operation.
 765 void CodeCache::release_exception_cache(ExceptionCache* entry) {
 766   if (SafepointSynchronize::is_at_safepoint()) {
 767     delete entry;
 768   } else {
 769     for (;;) {
 770       ExceptionCache* purge_list_head = Atomic::load(&_exception_cache_purge_list);
 771       entry->set_purge_list_next(purge_list_head);
 772       if (Atomic::cmpxchg(entry, &_exception_cache_purge_list, purge_list_head) == purge_list_head) {
 773         break;
 774       }
 775     }
 776   }
 777 }
 778 
 779 // Delete exception caches that have been concurrently unlinked,
 780 // followed by a global handshake operation.
 781 void CodeCache::purge_exception_caches() {
 782   ExceptionCache* curr = _exception_cache_purge_list;
 783   while (curr != NULL) {
 784     ExceptionCache* next = curr->purge_list_next();
 785     delete curr;
 786     curr = next;
 787   }
 788   _exception_cache_purge_list = NULL;
 789 }
 790 
 791 uint8_t CodeCache::_unloading_cycle = 1;
 792 
 793 void CodeCache::increment_unloading_cycle() {
 794   // 2-bit value (see IsUnloadingState in nmethod.cpp for details)
 795   // 0 is reserved for new methods.
 796   _unloading_cycle = (_unloading_cycle + 1) % 4;
 797   if (_unloading_cycle == 0) {
 798     _unloading_cycle = 1;
 799   }
 800 }
 801 
 802 CodeCache::UnloadingScope::UnloadingScope(BoolObjectClosure* is_alive)
 803   : _is_unloading_behaviour(is_alive)
 804 {
 805   _saved_behaviour = IsUnloadingBehaviour::current();
 806   IsUnloadingBehaviour::set_current(&_is_unloading_behaviour);
 807   increment_unloading_cycle();
 808   DependencyContext::cleaning_start();
 809 }
 810 
 811 CodeCache::UnloadingScope::~UnloadingScope() {
 812   IsUnloadingBehaviour::set_current(_saved_behaviour);
 813   DependencyContext::cleaning_end();
 814 }
 815 
 816 void CodeCache::verify_oops() {
 817   MutexLocker mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
 818   VerifyOopClosure voc;
 819   NMethodIterator iter(NMethodIterator::only_alive_and_not_unloading);
 820   while(iter.next()) {
 821     nmethod* nm = iter.method();
 822     nm->oops_do(&voc);
 823     nm->verify_oop_relocations();
 824   }
 825 }
 826 
 827 int CodeCache::blob_count(int code_blob_type) {
 828   CodeHeap* heap = get_code_heap(code_blob_type);
 829   return (heap != NULL) ? heap->blob_count() : 0;
 830 }
 831 
 832 int CodeCache::blob_count() {
 833   int count = 0;
 834   FOR_ALL_HEAPS(heap) {
 835     count += (*heap)->blob_count();
 836   }
 837   return count;
 838 }
 839 
 840 int CodeCache::nmethod_count(int code_blob_type) {
 841   CodeHeap* heap = get_code_heap(code_blob_type);
 842   return (heap != NULL) ? heap->nmethod_count() : 0;
 843 }
 844 
 845 int CodeCache::nmethod_count() {
 846   int count = 0;
 847   FOR_ALL_NMETHOD_HEAPS(heap) {
 848     count += (*heap)->nmethod_count();
 849   }
 850   return count;
 851 }
 852 
 853 int CodeCache::adapter_count(int code_blob_type) {
 854   CodeHeap* heap = get_code_heap(code_blob_type);
 855   return (heap != NULL) ? heap->adapter_count() : 0;
 856 }
 857 
 858 int CodeCache::adapter_count() {
 859   int count = 0;
 860   FOR_ALL_HEAPS(heap) {
 861     count += (*heap)->adapter_count();
 862   }
 863   return count;
 864 }
 865 
 866 address CodeCache::low_bound(int code_blob_type) {
 867   CodeHeap* heap = get_code_heap(code_blob_type);
 868   return (heap != NULL) ? (address)heap->low_boundary() : NULL;
 869 }
 870 
 871 address CodeCache::high_bound(int code_blob_type) {
 872   CodeHeap* heap = get_code_heap(code_blob_type);
 873   return (heap != NULL) ? (address)heap->high_boundary() : NULL;
 874 }
 875 
 876 size_t CodeCache::capacity() {
 877   size_t cap = 0;
 878   FOR_ALL_ALLOCABLE_HEAPS(heap) {
 879     cap += (*heap)->capacity();
 880   }
 881   return cap;
 882 }
 883 
 884 size_t CodeCache::unallocated_capacity(int code_blob_type) {
 885   CodeHeap* heap = get_code_heap(code_blob_type);
 886   return (heap != NULL) ? heap->unallocated_capacity() : 0;
 887 }
 888 
 889 size_t CodeCache::unallocated_capacity() {
 890   size_t unallocated_cap = 0;
 891   FOR_ALL_ALLOCABLE_HEAPS(heap) {
 892     unallocated_cap += (*heap)->unallocated_capacity();
 893   }
 894   return unallocated_cap;
 895 }
 896 
 897 size_t CodeCache::max_capacity() {
 898   size_t max_cap = 0;
 899   FOR_ALL_ALLOCABLE_HEAPS(heap) {
 900     max_cap += (*heap)->max_capacity();
 901   }
 902   return max_cap;
 903 }
 904 
 905 /**
 906  * Returns the reverse free ratio. E.g., if 25% (1/4) of the code heap
 907  * is free, reverse_free_ratio() returns 4.
 908  */
 909 double CodeCache::reverse_free_ratio(int code_blob_type) {
 910   CodeHeap* heap = get_code_heap(code_blob_type);
 911   if (heap == NULL) {
 912     return 0;
 913   }
 914 
 915   double unallocated_capacity = MAX2((double)heap->unallocated_capacity(), 1.0); // Avoid division by 0;
 916   double max_capacity = (double)heap->max_capacity();
 917   double result = max_capacity / unallocated_capacity;
 918   assert (max_capacity >= unallocated_capacity, "Must be");
 919   assert (result >= 1.0, "reverse_free_ratio must be at least 1. It is %f", result);
 920   return result;
 921 }
 922 
 923 size_t CodeCache::bytes_allocated_in_freelists() {
 924   size_t allocated_bytes = 0;
 925   FOR_ALL_ALLOCABLE_HEAPS(heap) {
 926     allocated_bytes += (*heap)->allocated_in_freelist();
 927   }
 928   return allocated_bytes;
 929 }
 930 
 931 int CodeCache::allocated_segments() {
 932   int number_of_segments = 0;
 933   FOR_ALL_ALLOCABLE_HEAPS(heap) {
 934     number_of_segments += (*heap)->allocated_segments();
 935   }
 936   return number_of_segments;
 937 }
 938 
 939 size_t CodeCache::freelists_length() {
 940   size_t length = 0;
 941   FOR_ALL_ALLOCABLE_HEAPS(heap) {
 942     length += (*heap)->freelist_length();
 943   }
 944   return length;
 945 }
 946 
 947 void icache_init();
 948 
 949 void CodeCache::initialize() {
 950   assert(CodeCacheSegmentSize >= (uintx)CodeEntryAlignment, "CodeCacheSegmentSize must be large enough to align entry points");
 951 #ifdef COMPILER2
 952   assert(CodeCacheSegmentSize >= (uintx)OptoLoopAlignment,  "CodeCacheSegmentSize must be large enough to align inner loops");
 953 #endif
 954   assert(CodeCacheSegmentSize >= sizeof(jdouble),    "CodeCacheSegmentSize must be large enough to align constants");
 955   // This was originally just a check of the alignment, causing failure, instead, round
 956   // the code cache to the page size.  In particular, Solaris is moving to a larger
 957   // default page size.
 958   CodeCacheExpansionSize = align_up(CodeCacheExpansionSize, os::vm_page_size());
 959 
 960   if (SegmentedCodeCache) {
 961     // Use multiple code heaps
 962     initialize_heaps();
 963   } else {
 964     // Use a single code heap
 965     FLAG_SET_ERGO(NonNMethodCodeHeapSize, 0);
 966     FLAG_SET_ERGO(ProfiledCodeHeapSize, 0);
 967     FLAG_SET_ERGO(NonProfiledCodeHeapSize, 0);
 968     ReservedCodeSpace rs = reserve_heap_memory(ReservedCodeCacheSize);
 969     add_heap(rs, "CodeCache", CodeBlobType::All);
 970   }
 971 
 972   // Initialize ICache flush mechanism
 973   // This service is needed for os::register_code_area
 974   icache_init();
 975 
 976   // Give OS a chance to register generated code area.
 977   // This is used on Windows 64 bit platforms to register
 978   // Structured Exception Handlers for our generated code.
 979   os::register_code_area((char*)low_bound(), (char*)high_bound());
 980 }
 981 
 982 void codeCache_init() {
 983   CodeCache::initialize();
 984   // Load AOT libraries and add AOT code heaps.
 985   AOTLoader::initialize();
 986 }
 987 
 988 //------------------------------------------------------------------------------------------------
 989 
 990 int CodeCache::number_of_nmethods_with_dependencies() {
 991   return _number_of_nmethods_with_dependencies;
 992 }
 993 
 994 void CodeCache::clear_inline_caches() {
 995   assert_locked_or_safepoint(CodeCache_lock);
 996   CompiledMethodIterator iter(CompiledMethodIterator::only_alive_and_not_unloading);
 997   while(iter.next()) {
 998     iter.method()->clear_inline_caches();
 999   }
1000 }
1001 
1002 void CodeCache::cleanup_inline_caches() {
1003   assert_locked_or_safepoint(CodeCache_lock);
1004   NMethodIterator iter(NMethodIterator::only_alive_and_not_unloading);
1005   while(iter.next()) {
1006     iter.method()->cleanup_inline_caches(/*clean_all=*/true);
1007   }
1008 }
1009 
1010 // Keeps track of time spent for checking dependencies
1011 NOT_PRODUCT(static elapsedTimer dependentCheckTime;)
1012 
1013 int CodeCache::mark_for_deoptimization(KlassDepChange& changes) {
1014   MutexLocker mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
1015   int number_of_marked_CodeBlobs = 0;
1016 
1017   // search the hierarchy looking for nmethods which are affected by the loading of this class
1018 
1019   // then search the interfaces this class implements looking for nmethods
1020   // which might be dependent of the fact that an interface only had one
1021   // implementor.
1022   // nmethod::check_all_dependencies works only correctly, if no safepoint
1023   // can happen
1024   NoSafepointVerifier nsv;
1025   for (DepChange::ContextStream str(changes, nsv); str.next(); ) {
1026     Klass* d = str.klass();
1027     number_of_marked_CodeBlobs += InstanceKlass::cast(d)->mark_dependent_nmethods(changes);
1028   }
1029 
1030 #ifndef PRODUCT
1031   if (VerifyDependencies) {
1032     // Object pointers are used as unique identifiers for dependency arguments. This
1033     // is only possible if no safepoint, i.e., GC occurs during the verification code.
1034     dependentCheckTime.start();
1035     nmethod::check_all_dependencies(changes);
1036     dependentCheckTime.stop();
1037   }
1038 #endif
1039 
1040   return number_of_marked_CodeBlobs;
1041 }
1042 
1043 CompiledMethod* CodeCache::find_compiled(void* start) {
1044   CodeBlob *cb = find_blob(start);
1045   assert(cb == NULL || cb->is_compiled(), "did not find an compiled_method");
1046   return (CompiledMethod*)cb;
1047 }
1048 
1049 bool CodeCache::is_far_target(address target) {
1050 #if INCLUDE_AOT
1051   return NativeCall::is_far_call(_low_bound,  target) ||
1052          NativeCall::is_far_call(_high_bound, target);
1053 #else
1054   return false;
1055 #endif
1056 }
1057 
1058 #ifdef INCLUDE_JVMTI
1059 // RedefineClasses support for unloading nmethods that are dependent on "old" methods.
1060 // We don't really expect this table to grow very large.  If it does, it can become a hashtable.
1061 static GrowableArray<CompiledMethod*>* old_compiled_method_table = NULL;
1062 
1063 static void add_to_old_table(CompiledMethod* c) {
1064   if (old_compiled_method_table == NULL) {
1065     old_compiled_method_table = new (ResourceObj::C_HEAP, mtCode) GrowableArray<CompiledMethod*>(100, true);
1066   }
1067   old_compiled_method_table->push(c);
1068 }
1069 
1070 static void reset_old_method_table() {
1071   if (old_compiled_method_table != NULL) {
1072     delete old_compiled_method_table;
1073     old_compiled_method_table = NULL;
1074   }
1075 }
1076 
1077 // Remove this method when zombied or unloaded.
1078 void CodeCache::unregister_old_nmethod(CompiledMethod* c) {
1079   assert_lock_strong(CodeCache_lock);
1080   if (old_compiled_method_table != NULL) {
1081     int index = old_compiled_method_table->find(c);
1082     if (index != -1) {
1083       old_compiled_method_table->delete_at(index);
1084     }
1085   }
1086 }
1087 
1088 void CodeCache::old_nmethods_do(MetadataClosure* f) {
1089   // Walk old method table and mark those on stack.
1090   int length = 0;
1091   if (old_compiled_method_table != NULL) {
1092     length = old_compiled_method_table->length();
1093     for (int i = 0; i < length; i++) {
1094       CompiledMethod* cm = old_compiled_method_table->at(i);
1095       // Only walk alive nmethods, the dead ones will get removed by the sweeper.
1096       if (cm->is_alive()) {
1097         old_compiled_method_table->at(i)->metadata_do(f);
1098       }
1099     }
1100   }
1101   log_debug(redefine, class, nmethod)("Walked %d nmethods for mark_on_stack", length);
1102 }
1103 
1104 // Just marks the methods in this class as needing deoptimization
1105 void CodeCache::mark_for_evol_deoptimization(InstanceKlass* dependee) {
1106   assert(SafepointSynchronize::is_at_safepoint(), "Can only do this at a safepoint!");
1107 
1108   // Mark dependent AOT nmethods, which are only found via the class redefined.
1109   // TODO: add dependencies to aotCompiledMethod's metadata section so this isn't
1110   // needed.
1111   AOTLoader::mark_evol_dependent_methods(dependee);
1112 }
1113 
1114 
1115 // Walk compiled methods and mark dependent methods for deoptimization.
1116 int CodeCache::mark_dependents_for_evol_deoptimization() {
1117   assert(SafepointSynchronize::is_at_safepoint(), "Can only do this at a safepoint!");
1118   // Each redefinition creates a new set of nmethods that have references to "old" Methods
1119   // So delete old method table and create a new one.
1120   reset_old_method_table();
1121 
1122   int number_of_marked_CodeBlobs = 0;
1123   CompiledMethodIterator iter(CompiledMethodIterator::only_alive_and_not_unloading);
1124   while(iter.next()) {
1125     CompiledMethod* nm = iter.method();
1126     // Walk all alive nmethods to check for old Methods.
1127     // This includes methods whose inline caches point to old methods, so
1128     // inline cache clearing is unnecessary.
1129     if (nm->has_evol_metadata()) {
1130       nm->mark_for_deoptimization();
1131       add_to_old_table(nm);
1132       number_of_marked_CodeBlobs++;
1133     }
1134   }
1135 
1136   // return total count of nmethods marked for deoptimization, if zero the caller
1137   // can skip deoptimization
1138   return number_of_marked_CodeBlobs;
1139 }
1140 
1141 void CodeCache::mark_all_nmethods_for_evol_deoptimization() {
1142   assert(SafepointSynchronize::is_at_safepoint(), "Can only do this at a safepoint!");
1143   CompiledMethodIterator iter(CompiledMethodIterator::only_alive_and_not_unloading);
1144   while(iter.next()) {
1145     CompiledMethod* nm = iter.method();
1146     if (!nm->method()->is_method_handle_intrinsic()) {
1147       nm->mark_for_deoptimization();
1148       if (nm->has_evol_metadata()) {
1149         add_to_old_table(nm);
1150       }
1151     }
1152   }
1153 }
1154 
1155 // Flushes compiled methods dependent on redefined classes, that have already been
1156 // marked for deoptimization.
1157 void CodeCache::flush_evol_dependents() {
1158   assert(SafepointSynchronize::is_at_safepoint(), "Can only do this at a safepoint!");
1159 
1160   // CodeCache can only be updated by a thread_in_VM and they will all be
1161   // stopped during the safepoint so CodeCache will be safe to update without
1162   // holding the CodeCache_lock.
1163 
1164   // At least one nmethod has been marked for deoptimization
1165 
1166   // All this already happens inside a VM_Operation, so we'll do all the work here.
1167   // Stuff copied from VM_Deoptimize and modified slightly.
1168 
1169   // We do not want any GCs to happen while we are in the middle of this VM operation
1170   ResourceMark rm;
1171   DeoptimizationMarker dm;
1172 
1173   // Deoptimize all activations depending on marked nmethods
1174   Deoptimization::deoptimize_dependents();
1175 
1176   // Make the dependent methods not entrant
1177   make_marked_nmethods_not_entrant();
1178 }
1179 #endif // INCLUDE_JVMTI
1180 
1181 // Deoptimize all methods
1182 void CodeCache::mark_all_nmethods_for_deoptimization() {
1183   MutexLocker mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
1184   CompiledMethodIterator iter(CompiledMethodIterator::only_alive_and_not_unloading);
1185   while(iter.next()) {
1186     CompiledMethod* nm = iter.method();
1187     if (!nm->method()->is_method_handle_intrinsic()) {
1188       nm->mark_for_deoptimization();
1189     }
1190   }
1191 }
1192 
1193 int CodeCache::mark_for_deoptimization(Method* dependee) {
1194   MutexLocker mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
1195   int number_of_marked_CodeBlobs = 0;
1196 
1197   CompiledMethodIterator iter(CompiledMethodIterator::only_alive_and_not_unloading);
1198   while(iter.next()) {
1199     CompiledMethod* nm = iter.method();
1200     if (nm->is_dependent_on_method(dependee)) {
1201       ResourceMark rm;
1202       nm->mark_for_deoptimization();
1203       number_of_marked_CodeBlobs++;
1204     }
1205   }
1206 
1207   return number_of_marked_CodeBlobs;
1208 }
1209 
1210 void CodeCache::make_marked_nmethods_not_entrant() {
1211   assert_locked_or_safepoint(CodeCache_lock);
1212   CompiledMethodIterator iter(CompiledMethodIterator::only_alive_and_not_unloading);
1213   while(iter.next()) {
1214     CompiledMethod* nm = iter.method();
1215     if (nm->is_marked_for_deoptimization() && !nm->is_not_entrant()) {
1216       nm->make_not_entrant();
1217     }
1218   }
1219 }
1220 
1221 // Flushes compiled methods dependent on dependee.
1222 void CodeCache::flush_dependents_on(InstanceKlass* dependee) {
1223   assert_lock_strong(Compile_lock);
1224 
1225   if (number_of_nmethods_with_dependencies() == 0) return;
1226 
1227   // CodeCache can only be updated by a thread_in_VM and they will all be
1228   // stopped during the safepoint so CodeCache will be safe to update without
1229   // holding the CodeCache_lock.
1230 
1231   KlassDepChange changes(dependee);
1232 
1233   // Compute the dependent nmethods
1234   if (mark_for_deoptimization(changes) > 0) {
1235     // At least one nmethod has been marked for deoptimization
1236     VM_Deoptimize op;
1237     VMThread::execute(&op);
1238   }
1239 }
1240 
1241 // Flushes compiled methods dependent on dependee
1242 void CodeCache::flush_dependents_on_method(const methodHandle& m_h) {
1243   // --- Compile_lock is not held. However we are at a safepoint.
1244   assert_locked_or_safepoint(Compile_lock);
1245 
1246   // CodeCache can only be updated by a thread_in_VM and they will all be
1247   // stopped dring the safepoint so CodeCache will be safe to update without
1248   // holding the CodeCache_lock.
1249 
1250   // Compute the dependent nmethods
1251   if (mark_for_deoptimization(m_h()) > 0) {
1252     // At least one nmethod has been marked for deoptimization
1253 
1254     // All this already happens inside a VM_Operation, so we'll do all the work here.
1255     // Stuff copied from VM_Deoptimize and modified slightly.
1256 
1257     // We do not want any GCs to happen while we are in the middle of this VM operation
1258     ResourceMark rm;
1259     DeoptimizationMarker dm;
1260 
1261     // Deoptimize all activations depending on marked nmethods
1262     Deoptimization::deoptimize_dependents();
1263 
1264     // Make the dependent methods not entrant
1265     make_marked_nmethods_not_entrant();
1266   }
1267 }
1268 
1269 void CodeCache::verify() {
1270   assert_locked_or_safepoint(CodeCache_lock);
1271   FOR_ALL_HEAPS(heap) {
1272     (*heap)->verify();
1273     FOR_ALL_BLOBS(cb, *heap) {
1274       if (cb->is_alive()) {
1275         cb->verify();
1276       }
1277     }
1278   }
1279 }
1280 
1281 // A CodeHeap is full. Print out warning and report event.
1282 PRAGMA_DIAG_PUSH
1283 PRAGMA_FORMAT_NONLITERAL_IGNORED
1284 void CodeCache::report_codemem_full(int code_blob_type, bool print) {
1285   // Get nmethod heap for the given CodeBlobType and build CodeCacheFull event
1286   CodeHeap* heap = get_code_heap(code_blob_type);
1287   assert(heap != NULL, "heap is null");
1288 
1289   if ((heap->full_count() == 0) || print) {
1290     // Not yet reported for this heap, report
1291     if (SegmentedCodeCache) {
1292       ResourceMark rm;
1293       stringStream msg1_stream, msg2_stream;
1294       msg1_stream.print("%s is full. Compiler has been disabled.",
1295                         get_code_heap_name(code_blob_type));
1296       msg2_stream.print("Try increasing the code heap size using -XX:%s=",
1297                  get_code_heap_flag_name(code_blob_type));
1298       const char *msg1 = msg1_stream.as_string();
1299       const char *msg2 = msg2_stream.as_string();
1300 
1301       log_warning(codecache)("%s", msg1);
1302       log_warning(codecache)("%s", msg2);
1303       warning("%s", msg1);
1304       warning("%s", msg2);
1305     } else {
1306       const char *msg1 = "CodeCache is full. Compiler has been disabled.";
1307       const char *msg2 = "Try increasing the code cache size using -XX:ReservedCodeCacheSize=";
1308 
1309       log_warning(codecache)("%s", msg1);
1310       log_warning(codecache)("%s", msg2);
1311       warning("%s", msg1);
1312       warning("%s", msg2);
1313     }
1314     ResourceMark rm;
1315     stringStream s;
1316     // Dump code cache into a buffer before locking the tty.
1317     {
1318       MutexLocker mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
1319       print_summary(&s);
1320     }
1321     {
1322       ttyLocker ttyl;
1323       tty->print("%s", s.as_string());
1324     }
1325 
1326     if (heap->full_count() == 0) {
1327       if (PrintCodeHeapAnalytics) {
1328         CompileBroker::print_heapinfo(tty, "all", 4096); // details, may be a lot!
1329       }
1330     }
1331   }
1332 
1333   heap->report_full();
1334 
1335   EventCodeCacheFull event;
1336   if (event.should_commit()) {
1337     event.set_codeBlobType((u1)code_blob_type);
1338     event.set_startAddress((u8)heap->low_boundary());
1339     event.set_commitedTopAddress((u8)heap->high());
1340     event.set_reservedTopAddress((u8)heap->high_boundary());
1341     event.set_entryCount(heap->blob_count());
1342     event.set_methodCount(heap->nmethod_count());
1343     event.set_adaptorCount(heap->adapter_count());
1344     event.set_unallocatedCapacity(heap->unallocated_capacity());
1345     event.set_fullCount(heap->full_count());
1346     event.commit();
1347   }
1348 }
1349 PRAGMA_DIAG_POP
1350 
1351 void CodeCache::print_memory_overhead() {
1352   size_t wasted_bytes = 0;
1353   FOR_ALL_ALLOCABLE_HEAPS(heap) {
1354       CodeHeap* curr_heap = *heap;
1355       for (CodeBlob* cb = (CodeBlob*)curr_heap->first(); cb != NULL; cb = (CodeBlob*)curr_heap->next(cb)) {
1356         HeapBlock* heap_block = ((HeapBlock*)cb) - 1;
1357         wasted_bytes += heap_block->length() * CodeCacheSegmentSize - cb->size();
1358       }
1359   }
1360   // Print bytes that are allocated in the freelist
1361   ttyLocker ttl;
1362   tty->print_cr("Number of elements in freelist: " SSIZE_FORMAT,       freelists_length());
1363   tty->print_cr("Allocated in freelist:          " SSIZE_FORMAT "kB",  bytes_allocated_in_freelists()/K);
1364   tty->print_cr("Unused bytes in CodeBlobs:      " SSIZE_FORMAT "kB",  (wasted_bytes/K));
1365   tty->print_cr("Segment map size:               " SSIZE_FORMAT "kB",  allocated_segments()/K); // 1 byte per segment
1366 }
1367 
1368 //------------------------------------------------------------------------------------------------
1369 // Non-product version
1370 
1371 #ifndef PRODUCT
1372 
1373 void CodeCache::print_trace(const char* event, CodeBlob* cb, int size) {
1374   if (PrintCodeCache2) {  // Need to add a new flag
1375     ResourceMark rm;
1376     if (size == 0)  size = cb->size();
1377     tty->print_cr("CodeCache %s:  addr: " INTPTR_FORMAT ", size: 0x%x", event, p2i(cb), size);
1378   }
1379 }
1380 
1381 void CodeCache::print_internals() {
1382   int nmethodCount = 0;
1383   int runtimeStubCount = 0;
1384   int adapterCount = 0;
1385   int deoptimizationStubCount = 0;
1386   int uncommonTrapStubCount = 0;
1387   int bufferBlobCount = 0;
1388   int total = 0;
1389   int nmethodAlive = 0;
1390   int nmethodNotEntrant = 0;
1391   int nmethodZombie = 0;
1392   int nmethodUnloaded = 0;
1393   int nmethodJava = 0;
1394   int nmethodNative = 0;
1395   int max_nm_size = 0;
1396   ResourceMark rm;
1397 
1398   int i = 0;
1399   FOR_ALL_ALLOCABLE_HEAPS(heap) {
1400     if ((_nmethod_heaps->length() >= 1) && Verbose) {
1401       tty->print_cr("-- %s --", (*heap)->name());
1402     }
1403     FOR_ALL_BLOBS(cb, *heap) {
1404       total++;
1405       if (cb->is_nmethod()) {
1406         nmethod* nm = (nmethod*)cb;
1407 
1408         if (Verbose && nm->method() != NULL) {
1409           ResourceMark rm;
1410           char *method_name = nm->method()->name_and_sig_as_C_string();
1411           tty->print("%s", method_name);
1412           if(nm->is_alive()) { tty->print_cr(" alive"); }
1413           if(nm->is_not_entrant()) { tty->print_cr(" not-entrant"); }
1414           if(nm->is_zombie()) { tty->print_cr(" zombie"); }
1415         }
1416 
1417         nmethodCount++;
1418 
1419         if(nm->is_alive()) { nmethodAlive++; }
1420         if(nm->is_not_entrant()) { nmethodNotEntrant++; }
1421         if(nm->is_zombie()) { nmethodZombie++; }
1422         if(nm->is_unloaded()) { nmethodUnloaded++; }
1423         if(nm->method() != NULL && nm->is_native_method()) { nmethodNative++; }
1424 
1425         if(nm->method() != NULL && nm->is_java_method()) {
1426           nmethodJava++;
1427           max_nm_size = MAX2(max_nm_size, nm->size());
1428         }
1429       } else if (cb->is_runtime_stub()) {
1430         runtimeStubCount++;
1431       } else if (cb->is_deoptimization_stub()) {
1432         deoptimizationStubCount++;
1433       } else if (cb->is_uncommon_trap_stub()) {
1434         uncommonTrapStubCount++;
1435       } else if (cb->is_adapter_blob()) {
1436         adapterCount++;
1437       } else if (cb->is_buffer_blob()) {
1438         bufferBlobCount++;
1439       }
1440     }
1441   }
1442 
1443   int bucketSize = 512;
1444   int bucketLimit = max_nm_size / bucketSize + 1;
1445   int *buckets = NEW_C_HEAP_ARRAY(int, bucketLimit, mtCode);
1446   memset(buckets, 0, sizeof(int) * bucketLimit);
1447 
1448   NMethodIterator iter(NMethodIterator::all_blobs);
1449   while(iter.next()) {
1450     nmethod* nm = iter.method();
1451     if(nm->method() != NULL && nm->is_java_method()) {
1452       buckets[nm->size() / bucketSize]++;
1453     }
1454   }
1455 
1456   tty->print_cr("Code Cache Entries (total of %d)",total);
1457   tty->print_cr("-------------------------------------------------");
1458   tty->print_cr("nmethods: %d",nmethodCount);
1459   tty->print_cr("\talive: %d",nmethodAlive);
1460   tty->print_cr("\tnot_entrant: %d",nmethodNotEntrant);
1461   tty->print_cr("\tzombie: %d",nmethodZombie);
1462   tty->print_cr("\tunloaded: %d",nmethodUnloaded);
1463   tty->print_cr("\tjava: %d",nmethodJava);
1464   tty->print_cr("\tnative: %d",nmethodNative);
1465   tty->print_cr("runtime_stubs: %d",runtimeStubCount);
1466   tty->print_cr("adapters: %d",adapterCount);
1467   tty->print_cr("buffer blobs: %d",bufferBlobCount);
1468   tty->print_cr("deoptimization_stubs: %d",deoptimizationStubCount);
1469   tty->print_cr("uncommon_traps: %d",uncommonTrapStubCount);
1470   tty->print_cr("\nnmethod size distribution (non-zombie java)");
1471   tty->print_cr("-------------------------------------------------");
1472 
1473   for(int i=0; i<bucketLimit; i++) {
1474     if(buckets[i] != 0) {
1475       tty->print("%d - %d bytes",i*bucketSize,(i+1)*bucketSize);
1476       tty->fill_to(40);
1477       tty->print_cr("%d",buckets[i]);
1478     }
1479   }
1480 
1481   FREE_C_HEAP_ARRAY(int, buckets);
1482   print_memory_overhead();
1483 }
1484 
1485 #endif // !PRODUCT
1486 
1487 void CodeCache::print() {
1488   print_summary(tty);
1489 
1490 #ifndef PRODUCT
1491   if (!Verbose) return;
1492 
1493   CodeBlob_sizes live;
1494   CodeBlob_sizes dead;
1495 
1496   FOR_ALL_ALLOCABLE_HEAPS(heap) {
1497     FOR_ALL_BLOBS(cb, *heap) {
1498       if (!cb->is_alive()) {
1499         dead.add(cb);
1500       } else {
1501         live.add(cb);
1502       }
1503     }
1504   }
1505 
1506   tty->print_cr("CodeCache:");
1507   tty->print_cr("nmethod dependency checking time %fs", dependentCheckTime.seconds());
1508 
1509   if (!live.is_empty()) {
1510     live.print("live");
1511   }
1512   if (!dead.is_empty()) {
1513     dead.print("dead");
1514   }
1515 
1516   if (WizardMode) {
1517      // print the oop_map usage
1518     int code_size = 0;
1519     int number_of_blobs = 0;
1520     int number_of_oop_maps = 0;
1521     int map_size = 0;
1522     FOR_ALL_ALLOCABLE_HEAPS(heap) {
1523       FOR_ALL_BLOBS(cb, *heap) {
1524         if (cb->is_alive()) {
1525           number_of_blobs++;
1526           code_size += cb->code_size();
1527           ImmutableOopMapSet* set = cb->oop_maps();
1528           if (set != NULL) {
1529             number_of_oop_maps += set->count();
1530             map_size           += set->nr_of_bytes();
1531           }
1532         }
1533       }
1534     }
1535     tty->print_cr("OopMaps");
1536     tty->print_cr("  #blobs    = %d", number_of_blobs);
1537     tty->print_cr("  code size = %d", code_size);
1538     tty->print_cr("  #oop_maps = %d", number_of_oop_maps);
1539     tty->print_cr("  map size  = %d", map_size);
1540   }
1541 
1542 #endif // !PRODUCT
1543 }
1544 
1545 void CodeCache::print_summary(outputStream* st, bool detailed) {
1546   int full_count = 0;
1547   FOR_ALL_HEAPS(heap_iterator) {
1548     CodeHeap* heap = (*heap_iterator);
1549     size_t total = (heap->high_boundary() - heap->low_boundary());
1550     if (_heaps->length() >= 1) {
1551       st->print("%s:", heap->name());
1552     } else {
1553       st->print("CodeCache:");
1554     }
1555     st->print_cr(" size=" SIZE_FORMAT "Kb used=" SIZE_FORMAT
1556                  "Kb max_used=" SIZE_FORMAT "Kb free=" SIZE_FORMAT "Kb",
1557                  total/K, (total - heap->unallocated_capacity())/K,
1558                  heap->max_allocated_capacity()/K, heap->unallocated_capacity()/K);
1559 
1560     if (detailed) {
1561       st->print_cr(" bounds [" INTPTR_FORMAT ", " INTPTR_FORMAT ", " INTPTR_FORMAT "]",
1562                    p2i(heap->low_boundary()),
1563                    p2i(heap->high()),
1564                    p2i(heap->high_boundary()));
1565 
1566       full_count += get_codemem_full_count(heap->code_blob_type());
1567     }
1568   }
1569 
1570   if (detailed) {
1571     st->print_cr(" total_blobs=" UINT32_FORMAT " nmethods=" UINT32_FORMAT
1572                        " adapters=" UINT32_FORMAT,
1573                        blob_count(), nmethod_count(), adapter_count());
1574     st->print_cr(" compilation: %s", CompileBroker::should_compile_new_jobs() ?
1575                  "enabled" : Arguments::mode() == Arguments::_int ?
1576                  "disabled (interpreter mode)" :
1577                  "disabled (not enough contiguous free space left)");
1578     st->print_cr("              stopped_count=%d, restarted_count=%d",
1579                  CompileBroker::get_total_compiler_stopped_count(),
1580                  CompileBroker::get_total_compiler_restarted_count());
1581     st->print_cr(" full_count=%d", full_count);
1582   }
1583 }
1584 
1585 void CodeCache::print_codelist(outputStream* st) {
1586   MutexLocker mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
1587 
1588   CompiledMethodIterator iter(CompiledMethodIterator::only_alive_and_not_unloading);
1589   while (iter.next()) {
1590     CompiledMethod* cm = iter.method();
1591     ResourceMark rm;
1592     char* method_name = cm->method()->name_and_sig_as_C_string();
1593     st->print_cr("%d %d %d %s [" INTPTR_FORMAT ", " INTPTR_FORMAT " - " INTPTR_FORMAT "]",
1594                  cm->compile_id(), cm->comp_level(), cm->get_state(),
1595                  method_name,
1596                  (intptr_t)cm->header_begin(), (intptr_t)cm->code_begin(), (intptr_t)cm->code_end());
1597   }
1598 }
1599 
1600 void CodeCache::print_layout(outputStream* st) {
1601   MutexLocker mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
1602   ResourceMark rm;
1603   print_summary(st, true);
1604 }
1605 
1606 void CodeCache::log_state(outputStream* st) {
1607   st->print(" total_blobs='" UINT32_FORMAT "' nmethods='" UINT32_FORMAT "'"
1608             " adapters='" UINT32_FORMAT "' free_code_cache='" SIZE_FORMAT "'",
1609             blob_count(), nmethod_count(), adapter_count(),
1610             unallocated_capacity());
1611 }
1612 
1613 //---<  BEGIN  >--- CodeHeap State Analytics.
1614 
1615 void CodeCache::aggregate(outputStream *out, size_t granularity) {
1616   FOR_ALL_ALLOCABLE_HEAPS(heap) {
1617     CodeHeapState::aggregate(out, (*heap), granularity);
1618   }
1619 }
1620 
1621 void CodeCache::discard(outputStream *out) {
1622   FOR_ALL_ALLOCABLE_HEAPS(heap) {
1623     CodeHeapState::discard(out, (*heap));
1624   }
1625 }
1626 
1627 void CodeCache::print_usedSpace(outputStream *out) {
1628   FOR_ALL_ALLOCABLE_HEAPS(heap) {
1629     CodeHeapState::print_usedSpace(out, (*heap));
1630   }
1631 }
1632 
1633 void CodeCache::print_freeSpace(outputStream *out) {
1634   FOR_ALL_ALLOCABLE_HEAPS(heap) {
1635     CodeHeapState::print_freeSpace(out, (*heap));
1636   }
1637 }
1638 
1639 void CodeCache::print_count(outputStream *out) {
1640   FOR_ALL_ALLOCABLE_HEAPS(heap) {
1641     CodeHeapState::print_count(out, (*heap));
1642   }
1643 }
1644 
1645 void CodeCache::print_space(outputStream *out) {
1646   FOR_ALL_ALLOCABLE_HEAPS(heap) {
1647     CodeHeapState::print_space(out, (*heap));
1648   }
1649 }
1650 
1651 void CodeCache::print_age(outputStream *out) {
1652   FOR_ALL_ALLOCABLE_HEAPS(heap) {
1653     CodeHeapState::print_age(out, (*heap));
1654   }
1655 }
1656 
1657 void CodeCache::print_names(outputStream *out) {
1658   FOR_ALL_ALLOCABLE_HEAPS(heap) {
1659     CodeHeapState::print_names(out, (*heap));
1660   }
1661 }
1662 //---<  END  >--- CodeHeap State Analytics.