1 /*
   2  * Copyright (c) 1997, 2015, 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 "code/codeBlob.hpp"
  27 #include "code/codeCache.hpp"
  28 #include "code/compiledIC.hpp"
  29 #include "code/dependencies.hpp"
  30 #include "code/icBuffer.hpp"
  31 #include "code/nmethod.hpp"
  32 #include "code/pcDesc.hpp"
  33 #include "compiler/compileBroker.hpp"
  34 #include "gc_implementation/shared/markSweep.hpp"
  35 #include "memory/allocation.inline.hpp"
  36 #include "memory/gcLocker.hpp"
  37 #include "memory/iterator.hpp"
  38 #include "memory/resourceArea.hpp"
  39 #include "oops/method.hpp"
  40 #include "oops/objArrayOop.hpp"
  41 #include "oops/oop.inline.hpp"
  42 #include "oops/verifyOop.hpp"
  43 #include "runtime/handles.inline.hpp"
  44 #include "runtime/arguments.hpp"
  45 #include "runtime/icache.hpp"
  46 #include "runtime/java.hpp"
  47 #include "runtime/mutexLocker.hpp"
  48 #include "runtime/sweeper.hpp"
  49 #include "runtime/compilationPolicy.hpp"
  50 #include "services/memoryService.hpp"
  51 #include "trace/tracing.hpp"
  52 #include "utilities/xmlstream.hpp"
  53 #ifdef COMPILER1
  54 #include "c1/c1_Compilation.hpp"
  55 #include "c1/c1_Compiler.hpp"
  56 #endif
  57 #ifdef COMPILER2
  58 #include "opto/c2compiler.hpp"
  59 #include "opto/compile.hpp"
  60 #include "opto/node.hpp"
  61 #endif
  62 
  63 // Helper class for printing in CodeCache
  64 class CodeBlob_sizes {
  65  private:
  66   int count;
  67   int total_size;
  68   int header_size;
  69   int code_size;
  70   int stub_size;
  71   int relocation_size;
  72   int scopes_oop_size;
  73   int scopes_metadata_size;
  74   int scopes_data_size;
  75   int scopes_pcs_size;
  76 
  77  public:
  78   CodeBlob_sizes() {
  79     count            = 0;
  80     total_size       = 0;
  81     header_size      = 0;
  82     code_size        = 0;
  83     stub_size        = 0;
  84     relocation_size  = 0;
  85     scopes_oop_size  = 0;
  86     scopes_metadata_size  = 0;
  87     scopes_data_size = 0;
  88     scopes_pcs_size  = 0;
  89   }
  90 
  91   int total()                                    { return total_size; }
  92   bool is_empty()                                { return count == 0; }
  93 
  94   void print(const char* title) {
  95     tty->print_cr(" #%d %s = %dK (hdr %d%%,  loc %d%%, code %d%%, stub %d%%, [oops %d%%, metadata %d%%, data %d%%, pcs %d%%])",
  96                   count,
  97                   title,
  98                   (int)(total() / K),
  99                   header_size             * 100 / total_size,
 100                   relocation_size         * 100 / total_size,
 101                   code_size               * 100 / total_size,
 102                   stub_size               * 100 / total_size,
 103                   scopes_oop_size         * 100 / total_size,
 104                   scopes_metadata_size    * 100 / total_size,
 105                   scopes_data_size        * 100 / total_size,
 106                   scopes_pcs_size         * 100 / total_size);
 107   }
 108 
 109   void add(CodeBlob* cb) {
 110     count++;
 111     total_size       += cb->size();
 112     header_size      += cb->header_size();
 113     relocation_size  += cb->relocation_size();
 114     if (cb->is_nmethod()) {
 115       nmethod* nm = cb->as_nmethod_or_null();
 116       code_size        += nm->insts_size();
 117       stub_size        += nm->stub_size();
 118 
 119       scopes_oop_size  += nm->oops_size();
 120       scopes_metadata_size  += nm->metadata_size();
 121       scopes_data_size += nm->scopes_data_size();
 122       scopes_pcs_size  += nm->scopes_pcs_size();
 123     } else {
 124       code_size        += cb->code_size();
 125     }
 126   }
 127 };
 128 
 129 // Iterate over all CodeHeaps
 130 #define FOR_ALL_HEAPS(heap) for (GrowableArrayIterator<CodeHeap*> heap = _heaps->begin(); heap != _heaps->end(); ++heap)
 131 // Iterate over all CodeBlobs (cb) on the given CodeHeap
 132 #define FOR_ALL_BLOBS(cb, heap) for (CodeBlob* cb = first_blob(heap); cb != NULL; cb = next_blob(heap, cb))
 133 
 134 address CodeCache::_low_bound = 0;
 135 address CodeCache::_high_bound = 0;
 136 int CodeCache::_number_of_blobs = 0;
 137 int CodeCache::_number_of_adapters = 0;
 138 int CodeCache::_number_of_nmethods = 0;
 139 int CodeCache::_number_of_nmethods_with_dependencies = 0;
 140 bool CodeCache::_needs_cache_clean = false;
 141 nmethod* CodeCache::_scavenge_root_nmethods = NULL;
 142 int CodeCache::_codemem_full_count = 0;
 143 
 144 // Initialize array of CodeHeaps
 145 GrowableArray<CodeHeap*>* CodeCache::_heaps = new(ResourceObj::C_HEAP, mtCode) GrowableArray<CodeHeap*> (CodeBlobType::All, true);
 146 
 147 void CodeCache::initialize_heaps() {
 148   // Determine size of compiler buffers
 149   size_t code_buffers_size = 0;
 150 #ifdef COMPILER1
 151   // C1 temporary code buffers (see Compiler::init_buffer_blob())
 152   const int c1_count = CompilationPolicy::policy()->compiler_count(CompLevel_simple);
 153   code_buffers_size += c1_count * Compiler::code_buffer_size();
 154 #endif
 155 #ifdef COMPILER2
 156   // C2 scratch buffers (see Compile::init_scratch_buffer_blob())
 157   const int c2_count = CompilationPolicy::policy()->compiler_count(CompLevel_full_optimization);
 158   // Initial size of constant table (this may be increased if a compiled method needs more space)
 159   code_buffers_size += c2_count * C2Compiler::initial_code_buffer_size();
 160 #endif
 161 
 162   // Calculate default CodeHeap sizes if not set by user
 163   if (!FLAG_IS_CMDLINE(NonNMethodCodeHeapSize) && !FLAG_IS_CMDLINE(ProfiledCodeHeapSize)
 164       && !FLAG_IS_CMDLINE(NonProfiledCodeHeapSize)) {
 165     // Increase default NonNMethodCodeHeapSize to account for compiler buffers
 166     FLAG_SET_ERGO(uintx, NonNMethodCodeHeapSize, NonNMethodCodeHeapSize + code_buffers_size);
 167 
 168     // Check if we have enough space for the non-nmethod code heap
 169     if (ReservedCodeCacheSize > NonNMethodCodeHeapSize) {
 170       // Use the default value for NonNMethodCodeHeapSize and one half of the
 171       // remaining size for non-profiled methods and one half for profiled methods
 172       size_t remaining_size = ReservedCodeCacheSize - NonNMethodCodeHeapSize;
 173       size_t profiled_size = remaining_size / 2;
 174       size_t non_profiled_size = remaining_size - profiled_size;
 175       FLAG_SET_ERGO(uintx, ProfiledCodeHeapSize, profiled_size);
 176       FLAG_SET_ERGO(uintx, NonProfiledCodeHeapSize, non_profiled_size);
 177     } else {
 178       // Use all space for the non-nmethod heap and set other heaps to minimal size
 179       FLAG_SET_ERGO(uintx, NonNMethodCodeHeapSize, ReservedCodeCacheSize - os::vm_page_size() * 2);
 180       FLAG_SET_ERGO(uintx, ProfiledCodeHeapSize, os::vm_page_size());
 181       FLAG_SET_ERGO(uintx, NonProfiledCodeHeapSize, os::vm_page_size());
 182     }
 183   }
 184 
 185   // We do not need the profiled CodeHeap, use all space for the non-profiled CodeHeap
 186   if(!heap_available(CodeBlobType::MethodProfiled)) {
 187     FLAG_SET_ERGO(uintx, NonProfiledCodeHeapSize, NonProfiledCodeHeapSize + ProfiledCodeHeapSize);
 188     FLAG_SET_ERGO(uintx, ProfiledCodeHeapSize, 0);
 189   }
 190   // We do not need the non-profiled CodeHeap, use all space for the non-nmethod CodeHeap
 191   if(!heap_available(CodeBlobType::MethodNonProfiled)) {
 192     FLAG_SET_ERGO(uintx, NonNMethodCodeHeapSize, NonNMethodCodeHeapSize + NonProfiledCodeHeapSize);
 193     FLAG_SET_ERGO(uintx, NonProfiledCodeHeapSize, 0);
 194   }
 195 
 196   // Make sure we have enough space for VM internal code
 197   uint min_code_cache_size = CodeCacheMinimumUseSpace DEBUG_ONLY(* 3);
 198   if (NonNMethodCodeHeapSize < (min_code_cache_size + code_buffers_size)) {
 199     vm_exit_during_initialization("Not enough space in non-nmethod code heap to run VM.");
 200   }
 201   guarantee(NonProfiledCodeHeapSize + ProfiledCodeHeapSize + NonNMethodCodeHeapSize <= ReservedCodeCacheSize, "Size check");
 202 
 203   // Align CodeHeaps
 204   size_t alignment = heap_alignment();
 205   size_t non_method_size = align_size_up(NonNMethodCodeHeapSize, alignment);
 206   size_t profiled_size   = align_size_down(ProfiledCodeHeapSize, alignment);
 207 
 208   // Reserve one continuous chunk of memory for CodeHeaps and split it into
 209   // parts for the individual heaps. The memory layout looks like this:
 210   // ---------- high -----------
 211   //    Non-profiled nmethods
 212   //      Profiled nmethods
 213   //         Non-nmethods
 214   // ---------- low ------------
 215   ReservedCodeSpace rs = reserve_heap_memory(ReservedCodeCacheSize);
 216   ReservedSpace non_method_space    = rs.first_part(non_method_size);
 217   ReservedSpace rest                = rs.last_part(non_method_size);
 218   ReservedSpace profiled_space      = rest.first_part(profiled_size);
 219   ReservedSpace non_profiled_space  = rest.last_part(profiled_size);
 220 
 221   // Non-nmethods (stubs, adapters, ...)
 222   add_heap(non_method_space, "CodeHeap 'non-nmethods'", CodeBlobType::NonNMethod);
 223   // Tier 2 and tier 3 (profiled) methods
 224   add_heap(profiled_space, "CodeHeap 'profiled nmethods'", CodeBlobType::MethodProfiled);
 225   // Tier 1 and tier 4 (non-profiled) methods and native methods
 226   add_heap(non_profiled_space, "CodeHeap 'non-profiled nmethods'", CodeBlobType::MethodNonProfiled);
 227 }
 228 
 229 size_t CodeCache::heap_alignment() {
 230   // If large page support is enabled, align code heaps according to large
 231   // page size to make sure that code cache is covered by large pages.
 232   const size_t page_size = os::can_execute_large_page_memory() ?
 233              os::page_size_for_region_unaligned(ReservedCodeCacheSize, 8) :
 234              os::vm_page_size();
 235   return MAX2(page_size, (size_t) os::vm_allocation_granularity());
 236 }
 237 
 238 ReservedCodeSpace CodeCache::reserve_heap_memory(size_t size) {
 239   // Determine alignment
 240   const size_t page_size = os::can_execute_large_page_memory() ?
 241           MIN2(os::page_size_for_region_aligned(InitialCodeCacheSize, 8),
 242                os::page_size_for_region_aligned(size, 8)) :
 243           os::vm_page_size();
 244   const size_t granularity = os::vm_allocation_granularity();
 245   const size_t r_align = MAX2(page_size, granularity);
 246   const size_t r_size = align_size_up(size, r_align);
 247   const size_t rs_align = page_size == (size_t) os::vm_page_size() ? 0 :
 248     MAX2(page_size, granularity);
 249 
 250   ReservedCodeSpace rs(r_size, rs_align, rs_align > 0);
 251 
 252   // Initialize bounds
 253   _low_bound = (address)rs.base();
 254   _high_bound = _low_bound + rs.size();
 255 
 256   return rs;
 257 }
 258 
 259 bool CodeCache::heap_available(int code_blob_type) {
 260   if (!SegmentedCodeCache) {
 261     // No segmentation: use a single code heap
 262     return (code_blob_type == CodeBlobType::All);
 263   } else if (Arguments::mode() == Arguments::_int) {
 264     // Interpreter only: we don't need any method code heaps
 265     return (code_blob_type == CodeBlobType::NonNMethod);
 266   } else if (TieredCompilation && (TieredStopAtLevel > CompLevel_simple)) {
 267     // Tiered compilation: use all code heaps
 268     return (code_blob_type < CodeBlobType::All);
 269   } else {
 270     // No TieredCompilation: we only need the non-nmethod and non-profiled code heap
 271     return (code_blob_type == CodeBlobType::NonNMethod) ||
 272            (code_blob_type == CodeBlobType::MethodNonProfiled);
 273   }
 274 }
 275 
 276 const char* CodeCache::get_code_heap_flag_name(int code_blob_type) {
 277   switch(code_blob_type) {
 278   case CodeBlobType::NonNMethod:
 279     return "NonNMethodCodeHeapSize";
 280     break;
 281   case CodeBlobType::MethodNonProfiled:
 282     return "NonProfiledCodeHeapSize";
 283     break;
 284   case CodeBlobType::MethodProfiled:
 285     return "ProfiledCodeHeapSize";
 286     break;
 287   }
 288   ShouldNotReachHere();
 289   return NULL;
 290 }
 291 
 292 void CodeCache::add_heap(ReservedSpace rs, const char* name, int code_blob_type) {
 293   // Check if heap is needed
 294   if (!heap_available(code_blob_type)) {
 295     return;
 296   }
 297 
 298   // Create CodeHeap
 299   CodeHeap* heap = new CodeHeap(name, code_blob_type);
 300   _heaps->append(heap);
 301 
 302   // Reserve Space
 303   size_t size_initial = MIN2(InitialCodeCacheSize, rs.size());
 304   size_initial = round_to(size_initial, os::vm_page_size());
 305   if (!heap->reserve(rs, size_initial, CodeCacheSegmentSize)) {
 306     vm_exit_during_initialization("Could not reserve enough space for code cache");
 307   }
 308 
 309   // Register the CodeHeap
 310   MemoryService::add_code_heap_memory_pool(heap, name);
 311 }
 312 
 313 CodeHeap* CodeCache::get_code_heap(const CodeBlob* cb) {
 314   assert(cb != NULL, "CodeBlob is null");
 315   FOR_ALL_HEAPS(heap) {
 316     if ((*heap)->contains(cb)) {
 317       return *heap;
 318     }
 319   }
 320   ShouldNotReachHere();
 321   return NULL;
 322 }
 323 
 324 CodeHeap* CodeCache::get_code_heap(int code_blob_type) {
 325   FOR_ALL_HEAPS(heap) {
 326     if ((*heap)->accepts(code_blob_type)) {
 327       return *heap;
 328     }
 329   }
 330   return NULL;
 331 }
 332 
 333 CodeBlob* CodeCache::first_blob(CodeHeap* heap) {
 334   assert_locked_or_safepoint(CodeCache_lock);
 335   assert(heap != NULL, "heap is null");
 336   return (CodeBlob*)heap->first();
 337 }
 338 
 339 CodeBlob* CodeCache::first_blob(int code_blob_type) {
 340   if (heap_available(code_blob_type)) {
 341     return first_blob(get_code_heap(code_blob_type));
 342   } else {
 343     return NULL;
 344   }
 345 }
 346 
 347 CodeBlob* CodeCache::next_blob(CodeHeap* heap, CodeBlob* cb) {
 348   assert_locked_or_safepoint(CodeCache_lock);
 349   assert(heap != NULL, "heap is null");
 350   return (CodeBlob*)heap->next(cb);
 351 }
 352 
 353 CodeBlob* CodeCache::next_blob(CodeBlob* cb) {
 354   return next_blob(get_code_heap(cb), cb);
 355 }
 356 
 357 /**
 358  * Do not seize the CodeCache lock here--if the caller has not
 359  * already done so, we are going to lose bigtime, since the code
 360  * cache will contain a garbage CodeBlob until the caller can
 361  * run the constructor for the CodeBlob subclass he is busy
 362  * instantiating.
 363  */
 364 CodeBlob* CodeCache::allocate(int size, int code_blob_type) {
 365   // Possibly wakes up the sweeper thread.
 366   NMethodSweeper::notify(code_blob_type);
 367   assert_locked_or_safepoint(CodeCache_lock);
 368   assert(size > 0, err_msg_res("Code cache allocation request must be > 0 but is %d", size));
 369   if (size <= 0) {
 370     return NULL;
 371   }
 372   CodeBlob* cb = NULL;
 373 
 374   // Get CodeHeap for the given CodeBlobType
 375   CodeHeap* heap = get_code_heap(code_blob_type);
 376   assert(heap != NULL, "heap is null");
 377 
 378   while (true) {
 379     cb = (CodeBlob*)heap->allocate(size);
 380     if (cb != NULL) break;
 381     if (!heap->expand_by(CodeCacheExpansionSize)) {
 382       // Expansion failed
 383       if (SegmentedCodeCache && (code_blob_type == CodeBlobType::NonNMethod)) {
 384         // Fallback solution: Store non-nmethod code in the non-profiled code heap.
 385         // Note that at in the sweeper, we check the reverse_free_ratio of the non-profiled
 386         // code heap and force stack scanning if less than 10% if the code heap are free.
 387         return allocate(size, CodeBlobType::MethodNonProfiled);
 388       }
 389       MutexUnlockerEx mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
 390       CompileBroker::handle_full_code_cache(code_blob_type);
 391       return NULL;
 392     }
 393     if (PrintCodeCacheExtension) {
 394       ResourceMark rm;
 395       if (SegmentedCodeCache) {
 396         tty->print("%s", heap->name());
 397       } else {
 398         tty->print("CodeCache");
 399       }
 400       tty->print_cr(" extended to [" INTPTR_FORMAT ", " INTPTR_FORMAT "] (" SSIZE_FORMAT " bytes)",
 401                     (intptr_t)heap->low_boundary(), (intptr_t)heap->high(),
 402                     (address)heap->high() - (address)heap->low_boundary());
 403     }
 404   }
 405   print_trace("allocation", cb, size);
 406   _number_of_blobs++;
 407   return cb;
 408 }
 409 
 410 void CodeCache::free(CodeBlob* cb) {
 411   assert_locked_or_safepoint(CodeCache_lock);
 412 
 413   print_trace("free", cb);
 414   if (cb->is_nmethod()) {
 415     _number_of_nmethods--;
 416     if (((nmethod *)cb)->has_dependencies()) {
 417       _number_of_nmethods_with_dependencies--;
 418     }
 419   }
 420   if (cb->is_adapter_blob()) {
 421     _number_of_adapters--;
 422   }
 423   _number_of_blobs--;
 424 
 425   // Get heap for given CodeBlob and deallocate
 426   get_code_heap(cb)->deallocate(cb);
 427 
 428   assert(_number_of_blobs >= 0, "sanity check");
 429 }
 430 
 431 void CodeCache::commit(CodeBlob* cb) {
 432   // this is called by nmethod::nmethod, which must already own CodeCache_lock
 433   assert_locked_or_safepoint(CodeCache_lock);
 434   if (cb->is_nmethod()) {
 435     _number_of_nmethods++;
 436     if (((nmethod *)cb)->has_dependencies()) {
 437       _number_of_nmethods_with_dependencies++;
 438     }
 439   }
 440   if (cb->is_adapter_blob()) {
 441     _number_of_adapters++;
 442   }
 443 
 444   // flush the hardware I-cache
 445   ICache::invalidate_range(cb->content_begin(), cb->content_size());
 446 }
 447 
 448 bool CodeCache::contains(void *p) {
 449   // It should be ok to call contains without holding a lock
 450   FOR_ALL_HEAPS(heap) {
 451     if ((*heap)->contains(p)) {
 452       return true;
 453     }
 454   }
 455   return false;
 456 }
 457 
 458 // This method is safe to call without holding the CodeCache_lock, as long as a dead CodeBlob is not
 459 // looked up (i.e., one that has been marked for deletion). It only depends on the _segmap to contain
 460 // valid indices, which it will always do, as long as the CodeBlob is not in the process of being recycled.
 461 CodeBlob* CodeCache::find_blob(void* start) {
 462   CodeBlob* result = find_blob_unsafe(start);
 463   // We could potentially look up non_entrant methods
 464   guarantee(result == NULL || !result->is_zombie() || result->is_locked_by_vm() || is_error_reported(), "unsafe access to zombie method");
 465   return result;
 466 }
 467 
 468 // Lookup that does not fail if you lookup a zombie method (if you call this, be sure to know
 469 // what you are doing)
 470 CodeBlob* CodeCache::find_blob_unsafe(void* start) {
 471   // NMT can walk the stack before code cache is created
 472   if (_heaps == NULL || _heaps->is_empty()) return NULL;
 473 
 474   FOR_ALL_HEAPS(heap) {
 475     CodeBlob* result = (CodeBlob*) (*heap)->find_start(start);
 476     if (result != NULL && result->blob_contains((address)start)) {
 477       return result;
 478     }
 479   }
 480   return NULL;
 481 }
 482 
 483 nmethod* CodeCache::find_nmethod(void* start) {
 484   CodeBlob* cb = find_blob(start);
 485   assert(cb->is_nmethod(), "did not find an nmethod");
 486   return (nmethod*)cb;
 487 }
 488 
 489 void CodeCache::blobs_do(void f(CodeBlob* nm)) {
 490   assert_locked_or_safepoint(CodeCache_lock);
 491   FOR_ALL_HEAPS(heap) {
 492     FOR_ALL_BLOBS(cb, *heap) {
 493       f(cb);
 494     }
 495   }
 496 }
 497 
 498 void CodeCache::nmethods_do(void f(nmethod* nm)) {
 499   assert_locked_or_safepoint(CodeCache_lock);
 500   NMethodIterator iter;
 501   while(iter.next()) {
 502     f(iter.method());
 503   }
 504 }
 505 
 506 void CodeCache::alive_nmethods_do(void f(nmethod* nm)) {
 507   assert_locked_or_safepoint(CodeCache_lock);
 508   NMethodIterator iter;
 509   while(iter.next_alive()) {
 510     f(iter.method());
 511   }
 512 }
 513 
 514 int CodeCache::alignment_unit() {
 515   return (int)_heaps->first()->alignment_unit();
 516 }
 517 
 518 int CodeCache::alignment_offset() {
 519   return (int)_heaps->first()->alignment_offset();
 520 }
 521 
 522 // Mark nmethods for unloading if they contain otherwise unreachable oops.
 523 void CodeCache::do_unloading(BoolObjectClosure* is_alive, bool unloading_occurred) {
 524   assert_locked_or_safepoint(CodeCache_lock);
 525   NMethodIterator iter;
 526   while(iter.next_alive()) {
 527     iter.method()->do_unloading(is_alive, unloading_occurred);
 528   }
 529 }
 530 
 531 void CodeCache::blobs_do(CodeBlobClosure* f) {
 532   assert_locked_or_safepoint(CodeCache_lock);
 533   FOR_ALL_HEAPS(heap) {
 534     FOR_ALL_BLOBS(cb, *heap) {
 535       if (cb->is_alive()) {
 536         f->do_code_blob(cb);
 537 
 538 #ifdef ASSERT
 539         if (cb->is_nmethod())
 540         ((nmethod*)cb)->verify_scavenge_root_oops();
 541 #endif //ASSERT
 542       }
 543     }
 544   }
 545 }
 546 
 547 // Walk the list of methods which might contain non-perm oops.
 548 void CodeCache::scavenge_root_nmethods_do(CodeBlobClosure* f) {
 549   assert_locked_or_safepoint(CodeCache_lock);
 550 
 551   if (UseG1GC) {
 552     return;
 553   }
 554 
 555   debug_only(mark_scavenge_root_nmethods());
 556 
 557   for (nmethod* cur = scavenge_root_nmethods(); cur != NULL; cur = cur->scavenge_root_link()) {
 558     debug_only(cur->clear_scavenge_root_marked());
 559     assert(cur->scavenge_root_not_marked(), "");
 560     assert(cur->on_scavenge_root_list(), "else shouldn't be on this list");
 561 
 562     bool is_live = (!cur->is_zombie() && !cur->is_unloaded());
 563 #ifndef PRODUCT
 564     if (TraceScavenge) {
 565       cur->print_on(tty, is_live ? "scavenge root" : "dead scavenge root"); tty->cr();
 566     }
 567 #endif //PRODUCT
 568     if (is_live) {
 569       // Perform cur->oops_do(f), maybe just once per nmethod.
 570       f->do_code_blob(cur);
 571     }
 572   }
 573 
 574   // Check for stray marks.
 575   debug_only(verify_perm_nmethods(NULL));
 576 }
 577 
 578 void CodeCache::add_scavenge_root_nmethod(nmethod* nm) {
 579   assert_locked_or_safepoint(CodeCache_lock);
 580 
 581   if (UseG1GC) {
 582     return;
 583   }
 584 
 585   nm->set_on_scavenge_root_list();
 586   nm->set_scavenge_root_link(_scavenge_root_nmethods);
 587   set_scavenge_root_nmethods(nm);
 588   print_trace("add_scavenge_root", nm);
 589 }
 590 
 591 void CodeCache::drop_scavenge_root_nmethod(nmethod* nm) {
 592   assert_locked_or_safepoint(CodeCache_lock);
 593 
 594   if (UseG1GC) {
 595     return;
 596   }
 597 
 598   print_trace("drop_scavenge_root", nm);
 599   nmethod* last = NULL;
 600   nmethod* cur = scavenge_root_nmethods();
 601   while (cur != NULL) {
 602     nmethod* next = cur->scavenge_root_link();
 603     if (cur == nm) {
 604       if (last != NULL)
 605             last->set_scavenge_root_link(next);
 606       else  set_scavenge_root_nmethods(next);
 607       nm->set_scavenge_root_link(NULL);
 608       nm->clear_on_scavenge_root_list();
 609       return;
 610     }
 611     last = cur;
 612     cur = next;
 613   }
 614   assert(false, "should have been on list");
 615 }
 616 
 617 void CodeCache::prune_scavenge_root_nmethods() {
 618   assert_locked_or_safepoint(CodeCache_lock);
 619 
 620   if (UseG1GC) {
 621     return;
 622   }
 623 
 624   debug_only(mark_scavenge_root_nmethods());
 625 
 626   nmethod* last = NULL;
 627   nmethod* cur = scavenge_root_nmethods();
 628   while (cur != NULL) {
 629     nmethod* next = cur->scavenge_root_link();
 630     debug_only(cur->clear_scavenge_root_marked());
 631     assert(cur->scavenge_root_not_marked(), "");
 632     assert(cur->on_scavenge_root_list(), "else shouldn't be on this list");
 633 
 634     if (!cur->is_zombie() && !cur->is_unloaded()
 635         && cur->detect_scavenge_root_oops()) {
 636       // Keep it.  Advance 'last' to prevent deletion.
 637       last = cur;
 638     } else {
 639       // Prune it from the list, so we don't have to look at it any more.
 640       print_trace("prune_scavenge_root", cur);
 641       cur->set_scavenge_root_link(NULL);
 642       cur->clear_on_scavenge_root_list();
 643       if (last != NULL)
 644             last->set_scavenge_root_link(next);
 645       else  set_scavenge_root_nmethods(next);
 646     }
 647     cur = next;
 648   }
 649 
 650   // Check for stray marks.
 651   debug_only(verify_perm_nmethods(NULL));
 652 }
 653 
 654 #ifndef PRODUCT
 655 void CodeCache::asserted_non_scavengable_nmethods_do(CodeBlobClosure* f) {
 656   if (UseG1GC) {
 657     return;
 658   }
 659 
 660   // While we are here, verify the integrity of the list.
 661   mark_scavenge_root_nmethods();
 662   for (nmethod* cur = scavenge_root_nmethods(); cur != NULL; cur = cur->scavenge_root_link()) {
 663     assert(cur->on_scavenge_root_list(), "else shouldn't be on this list");
 664     cur->clear_scavenge_root_marked();
 665   }
 666   verify_perm_nmethods(f);
 667 }
 668 
 669 // Temporarily mark nmethods that are claimed to be on the non-perm list.
 670 void CodeCache::mark_scavenge_root_nmethods() {
 671   NMethodIterator iter;
 672   while(iter.next_alive()) {
 673     nmethod* nm = iter.method();
 674     assert(nm->scavenge_root_not_marked(), "clean state");
 675     if (nm->on_scavenge_root_list())
 676       nm->set_scavenge_root_marked();
 677   }
 678 }
 679 
 680 // If the closure is given, run it on the unlisted nmethods.
 681 // Also make sure that the effects of mark_scavenge_root_nmethods is gone.
 682 void CodeCache::verify_perm_nmethods(CodeBlobClosure* f_or_null) {
 683   NMethodIterator iter;
 684   while(iter.next_alive()) {
 685     nmethod* nm = iter.method();
 686     bool call_f = (f_or_null != NULL);
 687     assert(nm->scavenge_root_not_marked(), "must be already processed");
 688     if (nm->on_scavenge_root_list())
 689       call_f = false;  // don't show this one to the client
 690     nm->verify_scavenge_root_oops();
 691     if (call_f)  f_or_null->do_code_blob(nm);
 692   }
 693 }
 694 #endif //PRODUCT
 695 
 696 void CodeCache::verify_clean_inline_caches() {
 697 #ifdef ASSERT
 698   NMethodIterator iter;
 699   while(iter.next_alive()) {
 700     nmethod* nm = iter.method();
 701     assert(!nm->is_unloaded(), "Tautology");
 702     nm->verify_clean_inline_caches();
 703     nm->verify();
 704   }
 705 #endif
 706 }
 707 
 708 void CodeCache::verify_icholder_relocations() {
 709 #ifdef ASSERT
 710   // make sure that we aren't leaking icholders
 711   int count = 0;
 712   FOR_ALL_HEAPS(heap) {
 713     FOR_ALL_BLOBS(cb, *heap) {
 714       if (cb->is_nmethod()) {
 715         nmethod* nm = (nmethod*)cb;
 716         count += nm->verify_icholder_relocations();
 717       }
 718     }
 719   }
 720 
 721   assert(count + InlineCacheBuffer::pending_icholder_count() + CompiledICHolder::live_not_claimed_count() ==
 722          CompiledICHolder::live_count(), "must agree");
 723 #endif
 724 }
 725 
 726 void CodeCache::gc_prologue() {
 727 }
 728 
 729 void CodeCache::gc_epilogue() {
 730   assert_locked_or_safepoint(CodeCache_lock);
 731   NMethodIterator iter;
 732   while(iter.next_alive()) {
 733     nmethod* nm = iter.method();
 734     assert(!nm->is_unloaded(), "Tautology");
 735     if (needs_cache_clean()) {
 736       nm->cleanup_inline_caches();
 737     }
 738     DEBUG_ONLY(nm->verify());
 739     DEBUG_ONLY(nm->verify_oop_relocations());
 740   }
 741   set_needs_cache_clean(false);
 742   prune_scavenge_root_nmethods();
 743 
 744   verify_icholder_relocations();
 745 }
 746 
 747 void CodeCache::verify_oops() {
 748   MutexLockerEx mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
 749   VerifyOopClosure voc;
 750   NMethodIterator iter;
 751   while(iter.next_alive()) {
 752     nmethod* nm = iter.method();
 753     nm->oops_do(&voc);
 754     nm->verify_oop_relocations();
 755   }
 756 }
 757 
 758 size_t CodeCache::capacity() {
 759   size_t cap = 0;
 760   FOR_ALL_HEAPS(heap) {
 761     cap += (*heap)->capacity();
 762   }
 763   return cap;
 764 }
 765 
 766 size_t CodeCache::unallocated_capacity(int code_blob_type) {
 767   CodeHeap* heap = get_code_heap(code_blob_type);
 768   return (heap != NULL) ? heap->unallocated_capacity() : 0;
 769 }
 770 
 771 size_t CodeCache::unallocated_capacity() {
 772   size_t unallocated_cap = 0;
 773   FOR_ALL_HEAPS(heap) {
 774     unallocated_cap += (*heap)->unallocated_capacity();
 775   }
 776   return unallocated_cap;
 777 }
 778 
 779 size_t CodeCache::max_capacity() {
 780   size_t max_cap = 0;
 781   FOR_ALL_HEAPS(heap) {
 782     max_cap += (*heap)->max_capacity();
 783   }
 784   return max_cap;
 785 }
 786 
 787 /**
 788  * Returns the reverse free ratio. E.g., if 25% (1/4) of the code heap
 789  * is free, reverse_free_ratio() returns 4.
 790  */
 791 double CodeCache::reverse_free_ratio(int code_blob_type) {
 792   CodeHeap* heap = get_code_heap(code_blob_type);
 793   if (heap == NULL) {
 794     return 0;
 795   }
 796 
 797   double unallocated_capacity = MAX2((double)heap->unallocated_capacity(), 1.0); // Avoid division by 0;
 798   double max_capacity = (double)heap->max_capacity();
 799   double result = max_capacity / unallocated_capacity;
 800   assert (max_capacity >= unallocated_capacity, "Must be");
 801   assert (result >= 1.0, err_msg_res("reverse_free_ratio must be at least 1. It is %f", result));
 802   return result;
 803 }
 804 
 805 size_t CodeCache::bytes_allocated_in_freelists() {
 806   size_t allocated_bytes = 0;
 807   FOR_ALL_HEAPS(heap) {
 808     allocated_bytes += (*heap)->allocated_in_freelist();
 809   }
 810   return allocated_bytes;
 811 }
 812 
 813 int CodeCache::allocated_segments() {
 814   int number_of_segments = 0;
 815   FOR_ALL_HEAPS(heap) {
 816     number_of_segments += (*heap)->allocated_segments();
 817   }
 818   return number_of_segments;
 819 }
 820 
 821 size_t CodeCache::freelists_length() {
 822   size_t length = 0;
 823   FOR_ALL_HEAPS(heap) {
 824     length += (*heap)->freelist_length();
 825   }
 826   return length;
 827 }
 828 
 829 void icache_init();
 830 
 831 void CodeCache::initialize() {
 832   assert(CodeCacheSegmentSize >= (uintx)CodeEntryAlignment, "CodeCacheSegmentSize must be large enough to align entry points");
 833 #ifdef COMPILER2
 834   assert(CodeCacheSegmentSize >= (uintx)OptoLoopAlignment,  "CodeCacheSegmentSize must be large enough to align inner loops");
 835 #endif
 836   assert(CodeCacheSegmentSize >= sizeof(jdouble),    "CodeCacheSegmentSize must be large enough to align constants");
 837   // This was originally just a check of the alignment, causing failure, instead, round
 838   // the code cache to the page size.  In particular, Solaris is moving to a larger
 839   // default page size.
 840   CodeCacheExpansionSize = round_to(CodeCacheExpansionSize, os::vm_page_size());
 841 
 842   if (SegmentedCodeCache) {
 843     // Use multiple code heaps
 844     initialize_heaps();
 845   } else {
 846     // Use a single code heap
 847     ReservedCodeSpace rs = reserve_heap_memory(ReservedCodeCacheSize);
 848     add_heap(rs, "CodeCache", CodeBlobType::All);
 849   }
 850 
 851   // Initialize ICache flush mechanism
 852   // This service is needed for os::register_code_area
 853   icache_init();
 854 
 855   // Give OS a chance to register generated code area.
 856   // This is used on Windows 64 bit platforms to register
 857   // Structured Exception Handlers for our generated code.
 858   os::register_code_area((char*)low_bound(), (char*)high_bound());
 859 }
 860 
 861 void codeCache_init() {
 862   CodeCache::initialize();
 863 }
 864 
 865 //------------------------------------------------------------------------------------------------
 866 
 867 int CodeCache::number_of_nmethods_with_dependencies() {
 868   return _number_of_nmethods_with_dependencies;
 869 }
 870 
 871 void CodeCache::clear_inline_caches() {
 872   assert_locked_or_safepoint(CodeCache_lock);
 873   NMethodIterator iter;
 874   while(iter.next_alive()) {
 875     iter.method()->clear_inline_caches();
 876   }
 877 }
 878 
 879 // Keeps track of time spent for checking dependencies
 880 NOT_PRODUCT(static elapsedTimer dependentCheckTime;)
 881 
 882 int CodeCache::mark_for_deoptimization(DepChange& changes) {
 883   MutexLockerEx mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
 884   int number_of_marked_CodeBlobs = 0;
 885 
 886   // search the hierarchy looking for nmethods which are affected by the loading of this class
 887 
 888   // then search the interfaces this class implements looking for nmethods
 889   // which might be dependent of the fact that an interface only had one
 890   // implementor.
 891   // nmethod::check_all_dependencies works only correctly, if no safepoint
 892   // can happen
 893   No_Safepoint_Verifier nsv;
 894   for (DepChange::ContextStream str(changes, nsv); str.next(); ) {
 895     Klass* d = str.klass();
 896     number_of_marked_CodeBlobs += InstanceKlass::cast(d)->mark_dependent_nmethods(changes);
 897   }
 898 
 899 #ifndef PRODUCT
 900   if (VerifyDependencies) {
 901     // Object pointers are used as unique identifiers for dependency arguments. This
 902     // is only possible if no safepoint, i.e., GC occurs during the verification code.
 903     dependentCheckTime.start();
 904     nmethod::check_all_dependencies(changes);
 905     dependentCheckTime.stop();
 906   }
 907 #endif
 908 
 909   return number_of_marked_CodeBlobs;
 910 }
 911 
 912 
 913 #ifdef HOTSWAP
 914 int CodeCache::mark_for_evol_deoptimization(instanceKlassHandle dependee) {
 915   MutexLockerEx mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
 916   int number_of_marked_CodeBlobs = 0;
 917 
 918   // Deoptimize all methods of the evolving class itself
 919   Array<Method*>* old_methods = dependee->methods();
 920   for (int i = 0; i < old_methods->length(); i++) {
 921     ResourceMark rm;
 922     Method* old_method = old_methods->at(i);
 923     nmethod *nm = old_method->code();
 924     if (nm != NULL) {
 925       nm->mark_for_deoptimization();
 926       number_of_marked_CodeBlobs++;
 927     }
 928   }
 929 
 930   NMethodIterator iter;
 931   while(iter.next_alive()) {
 932     nmethod* nm = iter.method();
 933     if (nm->is_marked_for_deoptimization()) {
 934       // ...Already marked in the previous pass; don't count it again.
 935     } else if (nm->is_evol_dependent_on(dependee())) {
 936       ResourceMark rm;
 937       nm->mark_for_deoptimization();
 938       number_of_marked_CodeBlobs++;
 939     } else  {
 940       // flush caches in case they refer to a redefined Method*
 941       nm->clear_inline_caches();
 942     }
 943   }
 944 
 945   return number_of_marked_CodeBlobs;
 946 }
 947 #endif // HOTSWAP
 948 
 949 
 950 // Deoptimize all methods
 951 void CodeCache::mark_all_nmethods_for_deoptimization() {
 952   MutexLockerEx mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
 953   NMethodIterator iter;
 954   while(iter.next_alive()) {
 955     nmethod* nm = iter.method();
 956     if (!nm->method()->is_method_handle_intrinsic()) {
 957       nm->mark_for_deoptimization();
 958     }
 959   }
 960 }
 961 
 962 int CodeCache::mark_for_deoptimization(Method* dependee) {
 963   MutexLockerEx mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
 964   int number_of_marked_CodeBlobs = 0;
 965 
 966   NMethodIterator iter;
 967   while(iter.next_alive()) {
 968     nmethod* nm = iter.method();
 969     if (nm->is_dependent_on_method(dependee)) {
 970       ResourceMark rm;
 971       nm->mark_for_deoptimization();
 972       number_of_marked_CodeBlobs++;
 973     }
 974   }
 975 
 976   return number_of_marked_CodeBlobs;
 977 }
 978 
 979 void CodeCache::make_marked_nmethods_zombies() {
 980   assert(SafepointSynchronize::is_at_safepoint(), "must be at a safepoint");
 981   NMethodIterator iter;
 982   while(iter.next_alive()) {
 983     nmethod* nm = iter.method();
 984     if (nm->is_marked_for_deoptimization()) {
 985 
 986       // If the nmethod has already been made non-entrant and it can be converted
 987       // then zombie it now. Otherwise make it non-entrant and it will eventually
 988       // be zombied when it is no longer seen on the stack. Note that the nmethod
 989       // might be "entrant" and not on the stack and so could be zombied immediately
 990       // but we can't tell because we don't track it on stack until it becomes
 991       // non-entrant.
 992 
 993       if (nm->is_not_entrant() && nm->can_not_entrant_be_converted()) {
 994         nm->make_zombie();
 995       } else {
 996         nm->make_not_entrant();
 997       }
 998     }
 999   }
1000 }
1001 
1002 void CodeCache::make_marked_nmethods_not_entrant() {
1003   assert_locked_or_safepoint(CodeCache_lock);
1004   NMethodIterator iter;
1005   while(iter.next_alive()) {
1006     nmethod* nm = iter.method();
1007     if (nm->is_marked_for_deoptimization()) {
1008       nm->make_not_entrant();
1009     }
1010   }
1011 }
1012 
1013 // Flushes compiled methods dependent on dependee.
1014 void CodeCache::flush_dependents_on(instanceKlassHandle dependee) {
1015   assert_lock_strong(Compile_lock);
1016 
1017   if (number_of_nmethods_with_dependencies() == 0) return;
1018 
1019   // CodeCache can only be updated by a thread_in_VM and they will all be
1020   // stopped during the safepoint so CodeCache will be safe to update without
1021   // holding the CodeCache_lock.
1022 
1023   KlassDepChange changes(dependee);
1024 
1025   // Compute the dependent nmethods
1026   if (mark_for_deoptimization(changes) > 0) {
1027     // At least one nmethod has been marked for deoptimization
1028     VM_Deoptimize op;
1029     VMThread::execute(&op);
1030   }
1031 }
1032 
1033 // Flushes compiled methods dependent on a particular CallSite
1034 // instance when its target is different than the given MethodHandle.
1035 void CodeCache::flush_dependents_on(Handle call_site, Handle method_handle) {
1036   assert_lock_strong(Compile_lock);
1037 
1038   if (number_of_nmethods_with_dependencies() == 0) return;
1039 
1040   // CodeCache can only be updated by a thread_in_VM and they will all be
1041   // stopped during the safepoint so CodeCache will be safe to update without
1042   // holding the CodeCache_lock.
1043 
1044   CallSiteDepChange changes(call_site(), method_handle());
1045 
1046   // Compute the dependent nmethods that have a reference to a
1047   // CallSite object.  We use InstanceKlass::mark_dependent_nmethod
1048   // directly instead of CodeCache::mark_for_deoptimization because we
1049   // want dependents on the call site class only not all classes in
1050   // the ContextStream.
1051   int marked = 0;
1052   {
1053     MutexLockerEx mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
1054     InstanceKlass* call_site_klass = InstanceKlass::cast(call_site->klass());
1055     marked = call_site_klass->mark_dependent_nmethods(changes);
1056   }
1057   if (marked > 0) {
1058     // At least one nmethod has been marked for deoptimization
1059     VM_Deoptimize op;
1060     VMThread::execute(&op);
1061   }
1062 }
1063 
1064 #ifdef HOTSWAP
1065 // Flushes compiled methods dependent on dependee in the evolutionary sense
1066 void CodeCache::flush_evol_dependents_on(instanceKlassHandle ev_k_h) {
1067   // --- Compile_lock is not held. However we are at a safepoint.
1068   assert_locked_or_safepoint(Compile_lock);
1069   if (number_of_nmethods_with_dependencies() == 0) return;
1070 
1071   // CodeCache can only be updated by a thread_in_VM and they will all be
1072   // stopped during the safepoint so CodeCache will be safe to update without
1073   // holding the CodeCache_lock.
1074 
1075   // Compute the dependent nmethods
1076   if (mark_for_evol_deoptimization(ev_k_h) > 0) {
1077     // At least one nmethod has been marked for deoptimization
1078 
1079     // All this already happens inside a VM_Operation, so we'll do all the work here.
1080     // Stuff copied from VM_Deoptimize and modified slightly.
1081 
1082     // We do not want any GCs to happen while we are in the middle of this VM operation
1083     ResourceMark rm;
1084     DeoptimizationMarker dm;
1085 
1086     // Deoptimize all activations depending on marked nmethods
1087     Deoptimization::deoptimize_dependents();
1088 
1089     // Make the dependent methods not entrant (in VM_Deoptimize they are made zombies)
1090     make_marked_nmethods_not_entrant();
1091   }
1092 }
1093 #endif // HOTSWAP
1094 
1095 
1096 // Flushes compiled methods dependent on dependee
1097 void CodeCache::flush_dependents_on_method(methodHandle m_h) {
1098   // --- Compile_lock is not held. However we are at a safepoint.
1099   assert_locked_or_safepoint(Compile_lock);
1100 
1101   // CodeCache can only be updated by a thread_in_VM and they will all be
1102   // stopped dring the safepoint so CodeCache will be safe to update without
1103   // holding the CodeCache_lock.
1104 
1105   // Compute the dependent nmethods
1106   if (mark_for_deoptimization(m_h()) > 0) {
1107     // At least one nmethod has been marked for deoptimization
1108 
1109     // All this already happens inside a VM_Operation, so we'll do all the work here.
1110     // Stuff copied from VM_Deoptimize and modified slightly.
1111 
1112     // We do not want any GCs to happen while we are in the middle of this VM operation
1113     ResourceMark rm;
1114     DeoptimizationMarker dm;
1115 
1116     // Deoptimize all activations depending on marked nmethods
1117     Deoptimization::deoptimize_dependents();
1118 
1119     // Make the dependent methods not entrant (in VM_Deoptimize they are made zombies)
1120     make_marked_nmethods_not_entrant();
1121   }
1122 }
1123 
1124 void CodeCache::verify() {
1125   assert_locked_or_safepoint(CodeCache_lock);
1126   FOR_ALL_HEAPS(heap) {
1127     (*heap)->verify();
1128     FOR_ALL_BLOBS(cb, *heap) {
1129       if (cb->is_alive()) {
1130         cb->verify();
1131       }
1132     }
1133   }
1134 }
1135 
1136 // A CodeHeap is full. Print out warning and report event.
1137 void CodeCache::report_codemem_full(int code_blob_type, bool print) {
1138   // Get nmethod heap for the given CodeBlobType and build CodeCacheFull event
1139   CodeHeap* heap = get_code_heap(code_blob_type);
1140   assert(heap != NULL, "heap is null");
1141 
1142   if (!heap->was_full() || print) {
1143     // Not yet reported for this heap, report
1144     heap->report_full();
1145     if (SegmentedCodeCache) {
1146       warning("%s is full. Compiler has been disabled.", get_code_heap_name(code_blob_type));
1147       warning("Try increasing the code heap size using -XX:%s=", get_code_heap_flag_name(code_blob_type));
1148     } else {
1149       warning("CodeCache is full. Compiler has been disabled.");
1150       warning("Try increasing the code cache size using -XX:ReservedCodeCacheSize=");
1151     }
1152     ResourceMark rm;
1153     stringStream s;
1154     // Dump code cache  into a buffer before locking the tty,
1155     {
1156       MutexLockerEx mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
1157       print_summary(&s);
1158     }
1159     ttyLocker ttyl;
1160     tty->print("%s", s.as_string());
1161   }
1162 
1163   _codemem_full_count++;
1164   EventCodeCacheFull event;
1165   if (event.should_commit()) {
1166     event.set_codeBlobType((u1)code_blob_type);
1167     event.set_startAddress((u8)heap->low_boundary());
1168     event.set_commitedTopAddress((u8)heap->high());
1169     event.set_reservedTopAddress((u8)heap->high_boundary());
1170     event.set_entryCount(nof_blobs());
1171     event.set_methodCount(nof_nmethods());
1172     event.set_adaptorCount(nof_adapters());
1173     event.set_unallocatedCapacity(heap->unallocated_capacity()/K);
1174     event.set_fullCount(_codemem_full_count);
1175     event.commit();
1176   }
1177 }
1178 
1179 void CodeCache::print_memory_overhead() {
1180   size_t wasted_bytes = 0;
1181   FOR_ALL_HEAPS(heap) {
1182       CodeHeap* curr_heap = *heap;
1183       for (CodeBlob* cb = (CodeBlob*)curr_heap->first(); cb != NULL; cb = (CodeBlob*)curr_heap->next(cb)) {
1184         HeapBlock* heap_block = ((HeapBlock*)cb) - 1;
1185         wasted_bytes += heap_block->length() * CodeCacheSegmentSize - cb->size();
1186       }
1187   }
1188   // Print bytes that are allocated in the freelist
1189   ttyLocker ttl;
1190   tty->print_cr("Number of elements in freelist: " SSIZE_FORMAT,       freelists_length());
1191   tty->print_cr("Allocated in freelist:          " SSIZE_FORMAT "kB",  bytes_allocated_in_freelists()/K);
1192   tty->print_cr("Unused bytes in CodeBlobs:      " SSIZE_FORMAT "kB",  (wasted_bytes/K));
1193   tty->print_cr("Segment map size:               " SSIZE_FORMAT "kB",  allocated_segments()/K); // 1 byte per segment
1194 }
1195 
1196 //------------------------------------------------------------------------------------------------
1197 // Non-product version
1198 
1199 #ifndef PRODUCT
1200 
1201 void CodeCache::print_trace(const char* event, CodeBlob* cb, int size) {
1202   if (PrintCodeCache2) {  // Need to add a new flag
1203     ResourceMark rm;
1204     if (size == 0)  size = cb->size();
1205     tty->print_cr("CodeCache %s:  addr: " INTPTR_FORMAT ", size: 0x%x", event, p2i(cb), size);
1206   }
1207 }
1208 
1209 void CodeCache::print_internals() {
1210   int nmethodCount = 0;
1211   int runtimeStubCount = 0;
1212   int adapterCount = 0;
1213   int deoptimizationStubCount = 0;
1214   int uncommonTrapStubCount = 0;
1215   int bufferBlobCount = 0;
1216   int total = 0;
1217   int nmethodAlive = 0;
1218   int nmethodNotEntrant = 0;
1219   int nmethodZombie = 0;
1220   int nmethodUnloaded = 0;
1221   int nmethodJava = 0;
1222   int nmethodNative = 0;
1223   int max_nm_size = 0;
1224   ResourceMark rm;
1225 
1226   int i = 0;
1227   FOR_ALL_HEAPS(heap) {
1228     if (SegmentedCodeCache && Verbose) {
1229       tty->print_cr("-- %s --", (*heap)->name());
1230     }
1231     FOR_ALL_BLOBS(cb, *heap) {
1232       total++;
1233       if (cb->is_nmethod()) {
1234         nmethod* nm = (nmethod*)cb;
1235 
1236         if (Verbose && nm->method() != NULL) {
1237           ResourceMark rm;
1238           char *method_name = nm->method()->name_and_sig_as_C_string();
1239           tty->print("%s", method_name);
1240           if(nm->is_alive()) { tty->print_cr(" alive"); }
1241           if(nm->is_not_entrant()) { tty->print_cr(" not-entrant"); }
1242           if(nm->is_zombie()) { tty->print_cr(" zombie"); }
1243         }
1244 
1245         nmethodCount++;
1246 
1247         if(nm->is_alive()) { nmethodAlive++; }
1248         if(nm->is_not_entrant()) { nmethodNotEntrant++; }
1249         if(nm->is_zombie()) { nmethodZombie++; }
1250         if(nm->is_unloaded()) { nmethodUnloaded++; }
1251         if(nm->method() != NULL && nm->is_native_method()) { nmethodNative++; }
1252 
1253         if(nm->method() != NULL && nm->is_java_method()) {
1254           nmethodJava++;
1255           max_nm_size = MAX2(max_nm_size, nm->size());
1256         }
1257       } else if (cb->is_runtime_stub()) {
1258         runtimeStubCount++;
1259       } else if (cb->is_deoptimization_stub()) {
1260         deoptimizationStubCount++;
1261       } else if (cb->is_uncommon_trap_stub()) {
1262         uncommonTrapStubCount++;
1263       } else if (cb->is_adapter_blob()) {
1264         adapterCount++;
1265       } else if (cb->is_buffer_blob()) {
1266         bufferBlobCount++;
1267       }
1268     }
1269   }
1270 
1271   int bucketSize = 512;
1272   int bucketLimit = max_nm_size / bucketSize + 1;
1273   int *buckets = NEW_C_HEAP_ARRAY(int, bucketLimit, mtCode);
1274   memset(buckets, 0, sizeof(int) * bucketLimit);
1275 
1276   NMethodIterator iter;
1277   while(iter.next()) {
1278     nmethod* nm = iter.method();
1279     if(nm->method() != NULL && nm->is_java_method()) {
1280       buckets[nm->size() / bucketSize]++;
1281     }
1282   }
1283 
1284   tty->print_cr("Code Cache Entries (total of %d)",total);
1285   tty->print_cr("-------------------------------------------------");
1286   tty->print_cr("nmethods: %d",nmethodCount);
1287   tty->print_cr("\talive: %d",nmethodAlive);
1288   tty->print_cr("\tnot_entrant: %d",nmethodNotEntrant);
1289   tty->print_cr("\tzombie: %d",nmethodZombie);
1290   tty->print_cr("\tunloaded: %d",nmethodUnloaded);
1291   tty->print_cr("\tjava: %d",nmethodJava);
1292   tty->print_cr("\tnative: %d",nmethodNative);
1293   tty->print_cr("runtime_stubs: %d",runtimeStubCount);
1294   tty->print_cr("adapters: %d",adapterCount);
1295   tty->print_cr("buffer blobs: %d",bufferBlobCount);
1296   tty->print_cr("deoptimization_stubs: %d",deoptimizationStubCount);
1297   tty->print_cr("uncommon_traps: %d",uncommonTrapStubCount);
1298   tty->print_cr("\nnmethod size distribution (non-zombie java)");
1299   tty->print_cr("-------------------------------------------------");
1300 
1301   for(int i=0; i<bucketLimit; i++) {
1302     if(buckets[i] != 0) {
1303       tty->print("%d - %d bytes",i*bucketSize,(i+1)*bucketSize);
1304       tty->fill_to(40);
1305       tty->print_cr("%d",buckets[i]);
1306     }
1307   }
1308 
1309   FREE_C_HEAP_ARRAY(int, buckets);
1310   print_memory_overhead();
1311 }
1312 
1313 #endif // !PRODUCT
1314 
1315 void CodeCache::print() {
1316   print_summary(tty);
1317 
1318 #ifndef PRODUCT
1319   if (!Verbose) return;
1320 
1321   CodeBlob_sizes live;
1322   CodeBlob_sizes dead;
1323 
1324   FOR_ALL_HEAPS(heap) {
1325     FOR_ALL_BLOBS(cb, *heap) {
1326       if (!cb->is_alive()) {
1327         dead.add(cb);
1328       } else {
1329         live.add(cb);
1330       }
1331     }
1332   }
1333 
1334   tty->print_cr("CodeCache:");
1335   tty->print_cr("nmethod dependency checking time %fs", dependentCheckTime.seconds());
1336 
1337   if (!live.is_empty()) {
1338     live.print("live");
1339   }
1340   if (!dead.is_empty()) {
1341     dead.print("dead");
1342   }
1343 
1344   if (WizardMode) {
1345      // print the oop_map usage
1346     int code_size = 0;
1347     int number_of_blobs = 0;
1348     int number_of_oop_maps = 0;
1349     int map_size = 0;
1350     FOR_ALL_HEAPS(heap) {
1351       FOR_ALL_BLOBS(cb, *heap) {
1352         if (cb->is_alive()) {
1353           number_of_blobs++;
1354           code_size += cb->code_size();
1355           OopMapSet* set = cb->oop_maps();
1356           if (set != NULL) {
1357             number_of_oop_maps += set->size();
1358             map_size           += set->heap_size();
1359           }
1360         }
1361       }
1362     }
1363     tty->print_cr("OopMaps");
1364     tty->print_cr("  #blobs    = %d", number_of_blobs);
1365     tty->print_cr("  code size = %d", code_size);
1366     tty->print_cr("  #oop_maps = %d", number_of_oop_maps);
1367     tty->print_cr("  map size  = %d", map_size);
1368   }
1369 
1370 #endif // !PRODUCT
1371 }
1372 
1373 void CodeCache::print_summary(outputStream* st, bool detailed) {
1374   FOR_ALL_HEAPS(heap_iterator) {
1375     CodeHeap* heap = (*heap_iterator);
1376     size_t total = (heap->high_boundary() - heap->low_boundary());
1377     if (SegmentedCodeCache) {
1378       st->print("%s:", heap->name());
1379     } else {
1380       st->print("CodeCache:");
1381     }
1382     st->print_cr(" size=" SIZE_FORMAT "Kb used=" SIZE_FORMAT
1383                  "Kb max_used=" SIZE_FORMAT "Kb free=" SIZE_FORMAT "Kb",
1384                  total/K, (total - heap->unallocated_capacity())/K,
1385                  heap->max_allocated_capacity()/K, heap->unallocated_capacity()/K);
1386 
1387     if (detailed) {
1388       st->print_cr(" bounds [" INTPTR_FORMAT ", " INTPTR_FORMAT ", " INTPTR_FORMAT "]",
1389                    p2i(heap->low_boundary()),
1390                    p2i(heap->high()),
1391                    p2i(heap->high_boundary()));
1392     }
1393   }
1394 
1395   if (detailed) {
1396     st->print_cr(" total_blobs=" UINT32_FORMAT " nmethods=" UINT32_FORMAT
1397                        " adapters=" UINT32_FORMAT,
1398                        nof_blobs(), nof_nmethods(), nof_adapters());
1399     st->print_cr(" compilation: %s", CompileBroker::should_compile_new_jobs() ?
1400                  "enabled" : Arguments::mode() == Arguments::_int ?
1401                  "disabled (interpreter mode)" :
1402                  "disabled (not enough contiguous free space left)");
1403   }
1404 }
1405 
1406 void CodeCache::print_codelist(outputStream* st) {
1407   assert_locked_or_safepoint(CodeCache_lock);
1408 
1409   NMethodIterator iter;
1410   while(iter.next_alive()) {
1411     nmethod* nm = iter.method();
1412     ResourceMark rm;
1413     char *method_name = nm->method()->name_and_sig_as_C_string();
1414     st->print_cr("%d %d %s ["INTPTR_FORMAT", "INTPTR_FORMAT" - "INTPTR_FORMAT"]",
1415                  nm->compile_id(), nm->comp_level(), method_name, (intptr_t)nm->header_begin(),
1416                  (intptr_t)nm->code_begin(), (intptr_t)nm->code_end());
1417   }
1418 }
1419 
1420 void CodeCache::print_layout(outputStream* st) {
1421   assert_locked_or_safepoint(CodeCache_lock);
1422   ResourceMark rm;
1423 
1424   print_summary(st, true);
1425 }
1426 
1427 void CodeCache::log_state(outputStream* st) {
1428   st->print(" total_blobs='" UINT32_FORMAT "' nmethods='" UINT32_FORMAT "'"
1429             " adapters='" UINT32_FORMAT "' free_code_cache='" SIZE_FORMAT "'",
1430             nof_blobs(), nof_nmethods(), nof_adapters(),
1431             unallocated_capacity());
1432 }