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 "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 "runtime/handles.inline.hpp"
  43 #include "runtime/arguments.hpp"
  44 #include "runtime/deoptimization.hpp"
  45 #include "runtime/icache.hpp"
  46 #include "runtime/java.hpp"
  47 #include "runtime/mutexLocker.hpp"
  48 #include "services/memoryService.hpp"
  49 #include "trace/tracing.hpp"
  50 #include "utilities/xmlstream.hpp"
  51 
  52 // Helper class for printing in CodeCache
  53 
  54 class CodeBlob_sizes {
  55  private:
  56   int count;
  57   int total_size;
  58   int header_size;
  59   int code_size;
  60   int stub_size;
  61   int relocation_size;
  62   int scopes_oop_size;
  63   int scopes_metadata_size;
  64   int scopes_data_size;
  65   int scopes_pcs_size;
  66 
  67  public:
  68   CodeBlob_sizes() {
  69     count            = 0;
  70     total_size       = 0;
  71     header_size      = 0;
  72     code_size        = 0;
  73     stub_size        = 0;
  74     relocation_size  = 0;
  75     scopes_oop_size  = 0;
  76     scopes_metadata_size  = 0;
  77     scopes_data_size = 0;
  78     scopes_pcs_size  = 0;
  79   }
  80 
  81   int total()                                    { return total_size; }
  82   bool is_empty()                                { return count == 0; }
  83 
  84   void print(const char* title) {
  85     tty->print_cr(" #%d %s = %dK (hdr %d%%,  loc %d%%, code %d%%, stub %d%%, [oops %d%%, metadata %d%%, data %d%%, pcs %d%%])",
  86                   count,
  87                   title,
  88                   (int)(total() / K),
  89                   header_size             * 100 / total_size,
  90                   relocation_size         * 100 / total_size,
  91                   code_size               * 100 / total_size,
  92                   stub_size               * 100 / total_size,
  93                   scopes_oop_size         * 100 / total_size,
  94                   scopes_metadata_size    * 100 / total_size,
  95                   scopes_data_size        * 100 / total_size,
  96                   scopes_pcs_size         * 100 / total_size);
  97   }
  98 
  99   void add(CodeBlob* cb) {
 100     count++;
 101     total_size       += cb->size();
 102     header_size      += cb->header_size();
 103     relocation_size  += cb->relocation_size();
 104     if (cb->is_nmethod()) {
 105       nmethod* nm = cb->as_nmethod_or_null();
 106       code_size        += nm->insts_size();
 107       stub_size        += nm->stub_size();
 108 
 109       scopes_oop_size  += nm->oops_size();
 110       scopes_metadata_size  += nm->metadata_size();
 111       scopes_data_size += nm->scopes_data_size();
 112       scopes_pcs_size  += nm->scopes_pcs_size();
 113     } else {
 114       code_size        += cb->code_size();
 115     }
 116   }
 117 };
 118 
 119 // CodeCache implementation
 120 
 121 CodeHeap * CodeCache::_heap = new CodeHeap();
 122 int CodeCache::_number_of_blobs = 0;
 123 int CodeCache::_number_of_adapters = 0;
 124 int CodeCache::_number_of_nmethods = 0;
 125 int CodeCache::_number_of_nmethods_with_dependencies = 0;
 126 bool CodeCache::_needs_cache_clean = false;
 127 nmethod* CodeCache::_scavenge_root_nmethods = NULL;
 128 
 129 int CodeCache::_codemem_full_count = 0;
 130 
 131 CodeBlob* CodeCache::first() {
 132   assert_locked_or_safepoint(CodeCache_lock);
 133   return (CodeBlob*)_heap->first();
 134 }
 135 
 136 
 137 CodeBlob* CodeCache::next(CodeBlob* cb) {
 138   assert_locked_or_safepoint(CodeCache_lock);
 139   return (CodeBlob*)_heap->next(cb);
 140 }
 141 
 142 
 143 CodeBlob* CodeCache::alive(CodeBlob *cb) {
 144   assert_locked_or_safepoint(CodeCache_lock);
 145   while (cb != NULL && !cb->is_alive()) cb = next(cb);
 146   return cb;
 147 }
 148 
 149 
 150 nmethod* CodeCache::alive_nmethod(CodeBlob* cb) {
 151   assert_locked_or_safepoint(CodeCache_lock);
 152   while (cb != NULL && (!cb->is_alive() || !cb->is_nmethod())) cb = next(cb);
 153   return (nmethod*)cb;
 154 }
 155 
 156 nmethod* CodeCache::first_nmethod() {
 157   assert_locked_or_safepoint(CodeCache_lock);
 158   CodeBlob* cb = first();
 159   while (cb != NULL && !cb->is_nmethod()) {
 160     cb = next(cb);
 161   }
 162   return (nmethod*)cb;
 163 }
 164 
 165 nmethod* CodeCache::next_nmethod (CodeBlob* cb) {
 166   assert_locked_or_safepoint(CodeCache_lock);
 167   cb = next(cb);
 168   while (cb != NULL && !cb->is_nmethod()) {
 169     cb = next(cb);
 170   }
 171   return (nmethod*)cb;
 172 }
 173 
 174 static size_t maxCodeCacheUsed = 0;
 175 
 176 CodeBlob* CodeCache::allocate(int size, bool is_critical) {
 177   // Do not seize the CodeCache lock here--if the caller has not
 178   // already done so, we are going to lose bigtime, since the code
 179   // cache will contain a garbage CodeBlob until the caller can
 180   // run the constructor for the CodeBlob subclass he is busy
 181   // instantiating.
 182   guarantee(size >= 0, "allocation request must be reasonable");
 183   assert_locked_or_safepoint(CodeCache_lock);
 184   CodeBlob* cb = NULL;
 185   _number_of_blobs++;
 186   while (true) {
 187     cb = (CodeBlob*)_heap->allocate(size, is_critical);
 188     if (cb != NULL) break;
 189     if (!_heap->expand_by(CodeCacheExpansionSize)) {
 190       // Expansion failed
 191       if (EnableJFR) {
 192         if (CodeCache_lock->owned_by_self()) {
 193           MutexUnlockerEx mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
 194           report_codemem_full();
 195         } else {
 196           report_codemem_full();
 197         }
 198       }
 199       return NULL;
 200     }
 201     if (PrintCodeCacheExtension) {
 202       ResourceMark rm;
 203       tty->print_cr("code cache extended to [" INTPTR_FORMAT ", " INTPTR_FORMAT "] (" SSIZE_FORMAT " bytes)",
 204                     (intptr_t)_heap->low_boundary(), (intptr_t)_heap->high(),
 205                     (address)_heap->high() - (address)_heap->low_boundary());
 206     }
 207   }
 208   maxCodeCacheUsed = MAX2(maxCodeCacheUsed, ((address)_heap->high_boundary() -
 209                           (address)_heap->low_boundary()) - unallocated_capacity());
 210   verify_if_often();
 211   print_trace("allocation", cb, size);
 212   return cb;
 213 }
 214 
 215 void CodeCache::free(CodeBlob* cb) {
 216   assert_locked_or_safepoint(CodeCache_lock);
 217   verify_if_often();
 218 
 219   print_trace("free", cb);
 220   if (cb->is_nmethod()) {
 221     _number_of_nmethods--;
 222     if (((nmethod *)cb)->has_dependencies()) {
 223       _number_of_nmethods_with_dependencies--;
 224     }
 225   }
 226   if (cb->is_adapter_blob()) {
 227     _number_of_adapters--;
 228   }
 229   _number_of_blobs--;
 230 
 231   _heap->deallocate(cb);
 232 
 233   verify_if_often();
 234   assert(_number_of_blobs >= 0, "sanity check");
 235 }
 236 
 237 
 238 void CodeCache::commit(CodeBlob* cb) {
 239   // this is called by nmethod::nmethod, which must already own CodeCache_lock
 240   assert_locked_or_safepoint(CodeCache_lock);
 241   if (cb->is_nmethod()) {
 242     _number_of_nmethods++;
 243     if (((nmethod *)cb)->has_dependencies()) {
 244       _number_of_nmethods_with_dependencies++;
 245     }
 246   }
 247   if (cb->is_adapter_blob()) {
 248     _number_of_adapters++;
 249   }
 250 
 251   // flush the hardware I-cache
 252   ICache::invalidate_range(cb->content_begin(), cb->content_size());
 253 }
 254 
 255 
 256 void CodeCache::flush() {
 257   assert_locked_or_safepoint(CodeCache_lock);
 258   Unimplemented();
 259 }
 260 
 261 
 262 // Iteration over CodeBlobs
 263 
 264 #define FOR_ALL_BLOBS(var)       for (CodeBlob *var =       first() ; var != NULL; var =       next(var) )
 265 #define FOR_ALL_ALIVE_BLOBS(var) for (CodeBlob *var = alive(first()); var != NULL; var = alive(next(var)))
 266 #define FOR_ALL_ALIVE_NMETHODS(var) for (nmethod *var = alive_nmethod(first()); var != NULL; var = alive_nmethod(next(var)))
 267 
 268 
 269 bool CodeCache::contains(void *p) {
 270   // It should be ok to call contains without holding a lock
 271   return _heap->contains(p);
 272 }
 273 
 274 
 275 // This method is safe to call without holding the CodeCache_lock, as long as a dead codeblob is not
 276 // looked up (i.e., one that has been marked for deletion). It only dependes on the _segmap to contain
 277 // valid indices, which it will always do, as long as the CodeBlob is not in the process of being recycled.
 278 CodeBlob* CodeCache::find_blob(void* start) {
 279   CodeBlob* result = find_blob_unsafe(start);
 280   if (result == NULL) return NULL;
 281   // We could potientially look up non_entrant methods
 282   guarantee(!result->is_zombie() || result->is_locked_by_vm() || is_error_reported(), "unsafe access to zombie method");
 283   return result;
 284 }
 285 
 286 nmethod* CodeCache::find_nmethod(void* start) {
 287   CodeBlob *cb = find_blob(start);
 288   assert(cb == NULL || cb->is_nmethod(), "did not find an nmethod");
 289   return (nmethod*)cb;
 290 }
 291 
 292 
 293 void CodeCache::blobs_do(void f(CodeBlob* nm)) {
 294   assert_locked_or_safepoint(CodeCache_lock);
 295   FOR_ALL_BLOBS(p) {
 296     f(p);
 297   }
 298 }
 299 
 300 
 301 void CodeCache::nmethods_do(void f(nmethod* nm)) {
 302   assert_locked_or_safepoint(CodeCache_lock);
 303   FOR_ALL_BLOBS(nm) {
 304     if (nm->is_nmethod()) f((nmethod*)nm);
 305   }
 306 }
 307 
 308 void CodeCache::alive_nmethods_do(void f(nmethod* nm)) {
 309   assert_locked_or_safepoint(CodeCache_lock);
 310   FOR_ALL_ALIVE_NMETHODS(nm) {
 311     f(nm);
 312   }
 313 }
 314 
 315 int CodeCache::alignment_unit() {
 316   return (int)_heap->alignment_unit();
 317 }
 318 
 319 
 320 int CodeCache::alignment_offset() {
 321   return (int)_heap->alignment_offset();
 322 }
 323 
 324 
 325 // Mark nmethods for unloading if they contain otherwise unreachable
 326 // oops.
 327 void CodeCache::do_unloading(BoolObjectClosure* is_alive, bool unloading_occurred) {
 328   assert_locked_or_safepoint(CodeCache_lock);
 329   FOR_ALL_ALIVE_NMETHODS(nm) {
 330     nm->do_unloading(is_alive, unloading_occurred);
 331   }
 332 }
 333 
 334 void CodeCache::blobs_do(CodeBlobClosure* f) {
 335   assert_locked_or_safepoint(CodeCache_lock);
 336   FOR_ALL_ALIVE_BLOBS(cb) {
 337     f->do_code_blob(cb);
 338 
 339 #ifdef ASSERT
 340     if (cb->is_nmethod())
 341       ((nmethod*)cb)->verify_scavenge_root_oops();
 342 #endif //ASSERT
 343   }
 344 }
 345 
 346 // Walk the list of methods which might contain non-perm oops.
 347 void CodeCache::scavenge_root_nmethods_do(CodeBlobClosure* f) {
 348   assert_locked_or_safepoint(CodeCache_lock);
 349 
 350   if (UseG1GC) {
 351     return;
 352   }
 353 
 354   debug_only(mark_scavenge_root_nmethods());
 355 
 356   for (nmethod* cur = scavenge_root_nmethods(); cur != NULL; cur = cur->scavenge_root_link()) {
 357     debug_only(cur->clear_scavenge_root_marked());
 358     assert(cur->scavenge_root_not_marked(), "");
 359     assert(cur->on_scavenge_root_list(), "else shouldn't be on this list");
 360 
 361     bool is_live = (!cur->is_zombie() && !cur->is_unloaded());
 362 #ifndef PRODUCT
 363     if (TraceScavenge) {
 364       cur->print_on(tty, is_live ? "scavenge root" : "dead scavenge root"); tty->cr();
 365     }
 366 #endif //PRODUCT
 367     if (is_live) {
 368       // Perform cur->oops_do(f), maybe just once per nmethod.
 369       f->do_code_blob(cur);
 370     }
 371   }
 372 
 373   // Check for stray marks.
 374   debug_only(verify_perm_nmethods(NULL));
 375 }
 376 
 377 void CodeCache::add_scavenge_root_nmethod(nmethod* nm) {
 378   assert_locked_or_safepoint(CodeCache_lock);
 379 
 380   if (UseG1GC) {
 381     return;
 382   }
 383 
 384   nm->set_on_scavenge_root_list();
 385   nm->set_scavenge_root_link(_scavenge_root_nmethods);
 386   set_scavenge_root_nmethods(nm);
 387   print_trace("add_scavenge_root", nm);
 388 }
 389 
 390 void CodeCache::drop_scavenge_root_nmethod(nmethod* nm) {
 391   assert_locked_or_safepoint(CodeCache_lock);
 392 
 393   if (UseG1GC) {
 394     return;
 395   }
 396 
 397   print_trace("drop_scavenge_root", nm);
 398   nmethod* last = NULL;
 399   nmethod* cur = scavenge_root_nmethods();
 400   while (cur != NULL) {
 401     nmethod* next = cur->scavenge_root_link();
 402     if (cur == nm) {
 403       if (last != NULL)
 404             last->set_scavenge_root_link(next);
 405       else  set_scavenge_root_nmethods(next);
 406       nm->set_scavenge_root_link(NULL);
 407       nm->clear_on_scavenge_root_list();
 408       return;
 409     }
 410     last = cur;
 411     cur = next;
 412   }
 413   assert(false, "should have been on list");
 414 }
 415 
 416 void CodeCache::prune_scavenge_root_nmethods() {
 417   assert_locked_or_safepoint(CodeCache_lock);
 418 
 419   if (UseG1GC) {
 420     return;
 421   }
 422 
 423   debug_only(mark_scavenge_root_nmethods());
 424 
 425   nmethod* last = NULL;
 426   nmethod* cur = scavenge_root_nmethods();
 427   while (cur != NULL) {
 428     nmethod* next = cur->scavenge_root_link();
 429     debug_only(cur->clear_scavenge_root_marked());
 430     assert(cur->scavenge_root_not_marked(), "");
 431     assert(cur->on_scavenge_root_list(), "else shouldn't be on this list");
 432 
 433     if (!cur->is_zombie() && !cur->is_unloaded()
 434         && cur->detect_scavenge_root_oops()) {
 435       // Keep it.  Advance 'last' to prevent deletion.
 436       last = cur;
 437     } else {
 438       // Prune it from the list, so we don't have to look at it any more.
 439       print_trace("prune_scavenge_root", cur);
 440       cur->set_scavenge_root_link(NULL);
 441       cur->clear_on_scavenge_root_list();
 442       if (last != NULL)
 443             last->set_scavenge_root_link(next);
 444       else  set_scavenge_root_nmethods(next);
 445     }
 446     cur = next;
 447   }
 448 
 449   // Check for stray marks.
 450   debug_only(verify_perm_nmethods(NULL));
 451 }
 452 
 453 #ifndef PRODUCT
 454 void CodeCache::asserted_non_scavengable_nmethods_do(CodeBlobClosure* f) {
 455   if (UseG1GC) {
 456     return;
 457   }
 458 
 459   // While we are here, verify the integrity of the list.
 460   mark_scavenge_root_nmethods();
 461   for (nmethod* cur = scavenge_root_nmethods(); cur != NULL; cur = cur->scavenge_root_link()) {
 462     assert(cur->on_scavenge_root_list(), "else shouldn't be on this list");
 463     cur->clear_scavenge_root_marked();
 464   }
 465   verify_perm_nmethods(f);
 466 }
 467 
 468 // Temporarily mark nmethods that are claimed to be on the non-perm list.
 469 void CodeCache::mark_scavenge_root_nmethods() {
 470   FOR_ALL_ALIVE_BLOBS(cb) {
 471     if (cb->is_nmethod()) {
 472       nmethod *nm = (nmethod*)cb;
 473       assert(nm->scavenge_root_not_marked(), "clean state");
 474       if (nm->on_scavenge_root_list())
 475         nm->set_scavenge_root_marked();
 476     }
 477   }
 478 }
 479 
 480 // If the closure is given, run it on the unlisted nmethods.
 481 // Also make sure that the effects of mark_scavenge_root_nmethods is gone.
 482 void CodeCache::verify_perm_nmethods(CodeBlobClosure* f_or_null) {
 483   FOR_ALL_ALIVE_BLOBS(cb) {
 484     bool call_f = (f_or_null != NULL);
 485     if (cb->is_nmethod()) {
 486       nmethod *nm = (nmethod*)cb;
 487       assert(nm->scavenge_root_not_marked(), "must be already processed");
 488       if (nm->on_scavenge_root_list())
 489         call_f = false;  // don't show this one to the client
 490       nm->verify_scavenge_root_oops();
 491     } else {
 492       call_f = false;   // not an nmethod
 493     }
 494     if (call_f)  f_or_null->do_code_blob(cb);
 495   }
 496 }
 497 #endif //PRODUCT
 498 
 499 void CodeCache::verify_clean_inline_caches() {
 500 #ifdef ASSERT
 501   FOR_ALL_ALIVE_BLOBS(cb) {
 502     if (cb->is_nmethod()) {
 503       nmethod* nm = (nmethod*)cb;
 504       assert(!nm->is_unloaded(), "Tautology");
 505       nm->verify_clean_inline_caches();
 506       nm->verify();
 507     }
 508   }
 509 #endif
 510 }
 511 
 512 void CodeCache::verify_icholder_relocations() {
 513 #ifdef ASSERT
 514   // make sure that we aren't leaking icholders
 515   int count = 0;
 516   FOR_ALL_BLOBS(cb) {
 517     if (cb->is_nmethod()) {
 518       nmethod* nm = (nmethod*)cb;
 519       count += nm->verify_icholder_relocations();
 520     }
 521   }
 522 
 523   assert(count + InlineCacheBuffer::pending_icholder_count() + CompiledICHolder::live_not_claimed_count() ==
 524          CompiledICHolder::live_count(), "must agree");
 525 #endif
 526 }
 527 
 528 void CodeCache::gc_prologue() {
 529 }
 530 
 531 void CodeCache::gc_epilogue() {
 532   assert_locked_or_safepoint(CodeCache_lock);
 533   NOT_DEBUG(if (needs_cache_clean())) {
 534     FOR_ALL_ALIVE_BLOBS(cb) {
 535       if (cb->is_nmethod()) {
 536         nmethod *nm = (nmethod*)cb;
 537         assert(!nm->is_unloaded(), "Tautology");
 538         DEBUG_ONLY(if (needs_cache_clean())) {
 539           nm->cleanup_inline_caches();
 540         }
 541         DEBUG_ONLY(nm->verify());
 542         DEBUG_ONLY(nm->verify_oop_relocations());
 543       }
 544     }
 545   }
 546   set_needs_cache_clean(false);
 547   prune_scavenge_root_nmethods();
 548 
 549   verify_icholder_relocations();
 550 }
 551 
 552 void CodeCache::verify_oops() {
 553   MutexLockerEx mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
 554   VerifyOopClosure voc;
 555   FOR_ALL_ALIVE_BLOBS(cb) {
 556     if (cb->is_nmethod()) {
 557       nmethod *nm = (nmethod*)cb;
 558       nm->oops_do(&voc);
 559       nm->verify_oop_relocations();
 560     }
 561   }
 562 }
 563 
 564 
 565 address CodeCache::first_address() {
 566   assert_locked_or_safepoint(CodeCache_lock);
 567   return (address)_heap->low_boundary();
 568 }
 569 
 570 
 571 address CodeCache::last_address() {
 572   assert_locked_or_safepoint(CodeCache_lock);
 573   return (address)_heap->high();
 574 }
 575 
 576 /**
 577  * Returns the reverse free ratio. E.g., if 25% (1/4) of the code cache
 578  * is free, reverse_free_ratio() returns 4.
 579  */
 580 double CodeCache::reverse_free_ratio() {
 581   double unallocated_capacity = (double)(CodeCache::unallocated_capacity() - CodeCacheMinimumFreeSpace);
 582   double max_capacity = (double)CodeCache::max_capacity();
 583   return max_capacity / unallocated_capacity;
 584 }
 585 
 586 void icache_init();
 587 
 588 void CodeCache::initialize() {
 589   assert(CodeCacheSegmentSize >= (uintx)CodeEntryAlignment, "CodeCacheSegmentSize must be large enough to align entry points");
 590 #ifdef COMPILER2
 591   assert(CodeCacheSegmentSize >= (uintx)OptoLoopAlignment,  "CodeCacheSegmentSize must be large enough to align inner loops");
 592 #endif
 593   assert(CodeCacheSegmentSize >= sizeof(jdouble),    "CodeCacheSegmentSize must be large enough to align constants");
 594   // This was originally just a check of the alignment, causing failure, instead, round
 595   // the code cache to the page size.  In particular, Solaris is moving to a larger
 596   // default page size.
 597   CodeCacheExpansionSize = round_to(CodeCacheExpansionSize, os::vm_page_size());
 598   InitialCodeCacheSize = round_to(InitialCodeCacheSize, os::vm_page_size());
 599   ReservedCodeCacheSize = round_to(ReservedCodeCacheSize, os::vm_page_size());
 600   if (!_heap->reserve(ReservedCodeCacheSize, InitialCodeCacheSize, CodeCacheSegmentSize)) {
 601     vm_exit_during_initialization("Could not reserve enough space for code cache");
 602   }
 603 
 604   MemoryService::add_code_heap_memory_pool(_heap);
 605 
 606   // Initialize ICache flush mechanism
 607   // This service is needed for os::register_code_area
 608   icache_init();
 609 
 610   // Give OS a chance to register generated code area.
 611   // This is used on Windows 64 bit platforms to register
 612   // Structured Exception Handlers for our generated code.
 613   os::register_code_area(_heap->low_boundary(), _heap->high_boundary());
 614 }
 615 
 616 
 617 void codeCache_init() {
 618   CodeCache::initialize();
 619 }
 620 
 621 //------------------------------------------------------------------------------------------------
 622 
 623 int CodeCache::number_of_nmethods_with_dependencies() {
 624   return _number_of_nmethods_with_dependencies;
 625 }
 626 
 627 void CodeCache::clear_inline_caches() {
 628   assert_locked_or_safepoint(CodeCache_lock);
 629   FOR_ALL_ALIVE_NMETHODS(nm) {
 630     nm->clear_inline_caches();
 631   }
 632 }
 633 
 634 #ifndef PRODUCT
 635 // used to keep track of how much time is spent in mark_for_deoptimization
 636 static elapsedTimer dependentCheckTime;
 637 static int dependentCheckCount = 0;
 638 #endif // PRODUCT
 639 
 640 
 641 int CodeCache::mark_for_deoptimization(DepChange& changes) {
 642   MutexLockerEx mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
 643 
 644 #ifndef PRODUCT
 645   dependentCheckTime.start();
 646   dependentCheckCount++;
 647 #endif // PRODUCT
 648 
 649   int number_of_marked_CodeBlobs = 0;
 650 
 651   // search the hierarchy looking for nmethods which are affected by the loading of this class
 652 
 653   // then search the interfaces this class implements looking for nmethods
 654   // which might be dependent of the fact that an interface only had one
 655   // implementor.
 656 
 657   { No_Safepoint_Verifier nsv;
 658     for (DepChange::ContextStream str(changes, nsv); str.next(); ) {
 659       Klass* d = str.klass();
 660       number_of_marked_CodeBlobs += InstanceKlass::cast(d)->mark_dependent_nmethods(changes);
 661     }
 662   }
 663 
 664   if (VerifyDependencies) {
 665     // Turn off dependency tracing while actually testing deps.
 666     NOT_PRODUCT( FlagSetting fs(TraceDependencies, false) );
 667     FOR_ALL_ALIVE_NMETHODS(nm) {
 668       if (!nm->is_marked_for_deoptimization() &&
 669           nm->check_all_dependencies()) {
 670         ResourceMark rm;
 671         tty->print_cr("Should have been marked for deoptimization:");
 672         changes.print();
 673         nm->print();
 674         nm->print_dependencies();
 675       }
 676     }
 677   }
 678 
 679 #ifndef PRODUCT
 680   dependentCheckTime.stop();
 681 #endif // PRODUCT
 682 
 683   return number_of_marked_CodeBlobs;
 684 }
 685 
 686 
 687 #ifdef HOTSWAP
 688 int CodeCache::mark_for_evol_deoptimization(instanceKlassHandle dependee) {
 689   MutexLockerEx mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
 690   int number_of_marked_CodeBlobs = 0;
 691 
 692   // Deoptimize all methods of the evolving class itself
 693   Array<Method*>* old_methods = dependee->methods();
 694   for (int i = 0; i < old_methods->length(); i++) {
 695     ResourceMark rm;
 696     Method* old_method = old_methods->at(i);
 697     nmethod *nm = old_method->code();
 698     if (nm != NULL) {
 699       nm->mark_for_deoptimization();
 700       number_of_marked_CodeBlobs++;
 701     }
 702   }
 703 
 704   FOR_ALL_ALIVE_NMETHODS(nm) {
 705     if (nm->is_marked_for_deoptimization()) {
 706       // ...Already marked in the previous pass; don't count it again.
 707     } else if (nm->is_evol_dependent_on(dependee())) {
 708       ResourceMark rm;
 709       nm->mark_for_deoptimization();
 710       number_of_marked_CodeBlobs++;
 711     } else  {
 712       // flush caches in case they refer to a redefined Method*
 713       nm->clear_inline_caches();
 714     }
 715   }
 716 
 717   return number_of_marked_CodeBlobs;
 718 }
 719 #endif // HOTSWAP
 720 
 721 
 722 // Deoptimize all methods
 723 void CodeCache::mark_all_nmethods_for_deoptimization() {
 724   MutexLockerEx mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
 725   FOR_ALL_ALIVE_NMETHODS(nm) {
 726     if (!nm->method()->is_method_handle_intrinsic()) {
 727       nm->mark_for_deoptimization();
 728     }
 729   }
 730 }
 731 
 732 
 733 int CodeCache::mark_for_deoptimization(Method* dependee) {
 734   MutexLockerEx mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
 735   int number_of_marked_CodeBlobs = 0;
 736 
 737   FOR_ALL_ALIVE_NMETHODS(nm) {
 738     if (nm->is_dependent_on_method(dependee)) {
 739       ResourceMark rm;
 740       nm->mark_for_deoptimization();
 741       number_of_marked_CodeBlobs++;
 742     }
 743   }
 744 
 745   return number_of_marked_CodeBlobs;
 746 }
 747 
 748 void CodeCache::make_marked_nmethods_not_entrant() {
 749   assert_locked_or_safepoint(CodeCache_lock);
 750   FOR_ALL_ALIVE_NMETHODS(nm) {
 751     if (nm->is_marked_for_deoptimization()) {
 752       nm->make_not_entrant();
 753     }
 754   }
 755 }
 756 
 757 void CodeCache::verify() {
 758   _heap->verify();
 759   FOR_ALL_ALIVE_BLOBS(p) {
 760     p->verify();
 761   }
 762 }
 763 
 764 void CodeCache::report_codemem_full() {
 765   _codemem_full_count++;
 766   EventCodeCacheFull event;
 767   if (event.should_commit()) {
 768     event.set_codeBlobType((u1)CodeBlobType::All);
 769     event.set_startAddress((u8)low_bound());
 770     event.set_commitedTopAddress((u8)high());
 771     event.set_reservedTopAddress((u8)high_bound());
 772     event.set_entryCount(nof_blobs());
 773     event.set_methodCount(nof_nmethods());
 774     event.set_adaptorCount(nof_adapters());
 775     event.set_unallocatedCapacity(unallocated_capacity()/K);
 776     event.set_fullCount(_codemem_full_count);
 777     event.commit();
 778   }
 779 }
 780 
 781 //------------------------------------------------------------------------------------------------
 782 // Non-product version
 783 
 784 #ifndef PRODUCT
 785 
 786 void CodeCache::verify_if_often() {
 787   if (VerifyCodeCacheOften) {
 788     _heap->verify();
 789   }
 790 }
 791 
 792 void CodeCache::print_trace(const char* event, CodeBlob* cb, int size) {
 793   if (PrintCodeCache2) {  // Need to add a new flag
 794     ResourceMark rm;
 795     if (size == 0)  size = cb->size();
 796     tty->print_cr("CodeCache %s:  addr: " INTPTR_FORMAT ", size: 0x%x", event, p2i(cb), size);
 797   }
 798 }
 799 
 800 void CodeCache::print_internals() {
 801   int nmethodCount = 0;
 802   int runtimeStubCount = 0;
 803   int adapterCount = 0;
 804   int deoptimizationStubCount = 0;
 805   int uncommonTrapStubCount = 0;
 806   int bufferBlobCount = 0;
 807   int total = 0;
 808   int nmethodAlive = 0;
 809   int nmethodNotEntrant = 0;
 810   int nmethodZombie = 0;
 811   int nmethodUnloaded = 0;
 812   int nmethodJava = 0;
 813   int nmethodNative = 0;
 814   int maxCodeSize = 0;
 815   ResourceMark rm;
 816 
 817   CodeBlob *cb;
 818   for (cb = first(); cb != NULL; cb = next(cb)) {
 819     total++;
 820     if (cb->is_nmethod()) {
 821       nmethod* nm = (nmethod*)cb;
 822 
 823       if (Verbose && nm->method() != NULL) {
 824         ResourceMark rm;
 825         char *method_name = nm->method()->name_and_sig_as_C_string();
 826         tty->print("%s", method_name);
 827         if(nm->is_alive()) { tty->print_cr(" alive"); }
 828         if(nm->is_not_entrant()) { tty->print_cr(" not-entrant"); }
 829         if(nm->is_zombie()) { tty->print_cr(" zombie"); }
 830       }
 831 
 832       nmethodCount++;
 833 
 834       if(nm->is_alive()) { nmethodAlive++; }
 835       if(nm->is_not_entrant()) { nmethodNotEntrant++; }
 836       if(nm->is_zombie()) { nmethodZombie++; }
 837       if(nm->is_unloaded()) { nmethodUnloaded++; }
 838       if(nm->is_native_method()) { nmethodNative++; }
 839 
 840       if(nm->method() != NULL && nm->is_java_method()) {
 841         nmethodJava++;
 842         if (nm->insts_size() > maxCodeSize) {
 843           maxCodeSize = nm->insts_size();
 844         }
 845       }
 846     } else if (cb->is_runtime_stub()) {
 847       runtimeStubCount++;
 848     } else if (cb->is_deoptimization_stub()) {
 849       deoptimizationStubCount++;
 850     } else if (cb->is_uncommon_trap_stub()) {
 851       uncommonTrapStubCount++;
 852     } else if (cb->is_adapter_blob()) {
 853       adapterCount++;
 854     } else if (cb->is_buffer_blob()) {
 855       bufferBlobCount++;
 856     }
 857   }
 858 
 859   int bucketSize = 512;
 860   int bucketLimit = maxCodeSize / bucketSize + 1;
 861   int *buckets = NEW_C_HEAP_ARRAY(int, bucketLimit, mtCode);
 862   memset(buckets,0,sizeof(int) * bucketLimit);
 863 
 864   for (cb = first(); cb != NULL; cb = next(cb)) {
 865     if (cb->is_nmethod()) {
 866       nmethod* nm = (nmethod*)cb;
 867       if(nm->is_java_method()) {
 868         buckets[nm->insts_size() / bucketSize]++;
 869       }
 870     }
 871   }
 872   tty->print_cr("Code Cache Entries (total of %d)",total);
 873   tty->print_cr("-------------------------------------------------");
 874   tty->print_cr("nmethods: %d",nmethodCount);
 875   tty->print_cr("\talive: %d",nmethodAlive);
 876   tty->print_cr("\tnot_entrant: %d",nmethodNotEntrant);
 877   tty->print_cr("\tzombie: %d",nmethodZombie);
 878   tty->print_cr("\tunloaded: %d",nmethodUnloaded);
 879   tty->print_cr("\tjava: %d",nmethodJava);
 880   tty->print_cr("\tnative: %d",nmethodNative);
 881   tty->print_cr("runtime_stubs: %d",runtimeStubCount);
 882   tty->print_cr("adapters: %d",adapterCount);
 883   tty->print_cr("buffer blobs: %d",bufferBlobCount);
 884   tty->print_cr("deoptimization_stubs: %d",deoptimizationStubCount);
 885   tty->print_cr("uncommon_traps: %d",uncommonTrapStubCount);
 886   tty->print_cr("\nnmethod size distribution (non-zombie java)");
 887   tty->print_cr("-------------------------------------------------");
 888 
 889   for(int i=0; i<bucketLimit; i++) {
 890     if(buckets[i] != 0) {
 891       tty->print("%d - %d bytes",i*bucketSize,(i+1)*bucketSize);
 892       tty->fill_to(40);
 893       tty->print_cr("%d",buckets[i]);
 894     }
 895   }
 896 
 897   FREE_C_HEAP_ARRAY(int, buckets, mtCode);
 898 }
 899 
 900 #endif // !PRODUCT
 901 
 902 void CodeCache::print() {
 903   print_summary(tty);
 904 
 905 #ifndef PRODUCT
 906   if (!Verbose) return;
 907 
 908   CodeBlob_sizes live;
 909   CodeBlob_sizes dead;
 910 
 911   FOR_ALL_BLOBS(p) {
 912     if (!p->is_alive()) {
 913       dead.add(p);
 914     } else {
 915       live.add(p);
 916     }
 917   }
 918 
 919   tty->print_cr("CodeCache:");
 920 
 921   tty->print_cr("nmethod dependency checking time %f, per dependent %f", dependentCheckTime.seconds(),
 922                 dependentCheckTime.seconds() / dependentCheckCount);
 923 
 924   if (!live.is_empty()) {
 925     live.print("live");
 926   }
 927   if (!dead.is_empty()) {
 928     dead.print("dead");
 929   }
 930 
 931 
 932   if (WizardMode) {
 933      // print the oop_map usage
 934     int code_size = 0;
 935     int number_of_blobs = 0;
 936     int number_of_oop_maps = 0;
 937     int map_size = 0;
 938     FOR_ALL_BLOBS(p) {
 939       if (p->is_alive()) {
 940         number_of_blobs++;
 941         code_size += p->code_size();
 942         OopMapSet* set = p->oop_maps();
 943         if (set != NULL) {
 944           number_of_oop_maps += set->size();
 945           map_size           += set->heap_size();
 946         }
 947       }
 948     }
 949     tty->print_cr("OopMaps");
 950     tty->print_cr("  #blobs    = %d", number_of_blobs);
 951     tty->print_cr("  code size = %d", code_size);
 952     tty->print_cr("  #oop_maps = %d", number_of_oop_maps);
 953     tty->print_cr("  map size  = %d", map_size);
 954   }
 955 
 956 #endif // !PRODUCT
 957 }
 958 
 959 void CodeCache::print_summary(outputStream* st, bool detailed) {
 960   size_t total = (_heap->high_boundary() - _heap->low_boundary());
 961   st->print_cr("CodeCache: size=" SIZE_FORMAT "Kb used=" SIZE_FORMAT
 962                "Kb max_used=" SIZE_FORMAT "Kb free=" SIZE_FORMAT "Kb",
 963                total/K, (total - unallocated_capacity())/K,
 964                maxCodeCacheUsed/K, unallocated_capacity()/K);
 965 
 966   if (detailed) {
 967     st->print_cr(" bounds [" INTPTR_FORMAT ", " INTPTR_FORMAT ", " INTPTR_FORMAT "]",
 968                  p2i(_heap->low_boundary()),
 969                  p2i(_heap->high()),
 970                  p2i(_heap->high_boundary()));
 971     st->print_cr(" total_blobs=" UINT32_FORMAT " nmethods=" UINT32_FORMAT
 972                  " adapters=" UINT32_FORMAT,
 973                  nof_blobs(), nof_nmethods(), nof_adapters());
 974     st->print_cr(" compilation: %s", CompileBroker::should_compile_new_jobs() ?
 975                  "enabled" : Arguments::mode() == Arguments::_int ?
 976                  "disabled (interpreter mode)" :
 977                  "disabled (not enough contiguous free space left)");
 978   }
 979 }
 980 
 981 void CodeCache::log_state(outputStream* st) {
 982   st->print(" total_blobs='" UINT32_FORMAT "' nmethods='" UINT32_FORMAT "'"
 983             " adapters='" UINT32_FORMAT "' free_code_cache='" SIZE_FORMAT "'",
 984             nof_blobs(), nof_nmethods(), nof_adapters(),
 985             unallocated_capacity());
 986 }
 987