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/codeCache.hpp"
  27 #include "code/compiledIC.hpp"
  28 #include "code/dependencies.hpp"
  29 #include "code/nativeInst.hpp"
  30 #include "code/nmethod.hpp"
  31 #include "code/scopeDesc.hpp"
  32 #include "compiler/abstractCompiler.hpp"
  33 #include "compiler/compileBroker.hpp"
  34 #include "compiler/compileLog.hpp"
  35 #include "compiler/compilerOracle.hpp"
  36 #include "compiler/disassembler.hpp"
  37 #include "interpreter/bytecode.hpp"
  38 #include "oops/methodData.hpp"
  39 #include "oops/oop.inline.hpp"
  40 #include "prims/jvmtiRedefineClassesTrace.hpp"
  41 #include "prims/jvmtiImpl.hpp"
  42 #include "runtime/atomic.inline.hpp"
  43 #include "runtime/orderAccess.inline.hpp"
  44 #include "runtime/sharedRuntime.hpp"
  45 #include "runtime/sweeper.hpp"
  46 #include "utilities/resourceHash.hpp"
  47 #include "utilities/dtrace.hpp"
  48 #include "utilities/events.hpp"
  49 #include "utilities/xmlstream.hpp"
  50 #ifdef TARGET_ARCH_x86
  51 # include "nativeInst_x86.hpp"
  52 #endif
  53 #ifdef TARGET_ARCH_sparc
  54 # include "nativeInst_sparc.hpp"
  55 #endif
  56 #ifdef TARGET_ARCH_zero
  57 # include "nativeInst_zero.hpp"
  58 #endif
  59 #ifdef TARGET_ARCH_arm
  60 # include "nativeInst_arm.hpp"
  61 #endif
  62 #ifdef TARGET_ARCH_ppc
  63 # include "nativeInst_ppc.hpp"
  64 #endif
  65 #ifdef SHARK
  66 #include "shark/sharkCompiler.hpp"
  67 #endif
  68 #if INCLUDE_JVMCI
  69 #include "jvmci/jvmciJavaClasses.hpp"
  70 #endif
  71 
  72 PRAGMA_FORMAT_MUTE_WARNINGS_FOR_GCC
  73 
  74 unsigned char nmethod::_global_unloading_clock = 0;
  75 
  76 #ifdef DTRACE_ENABLED
  77 
  78 // Only bother with this argument setup if dtrace is available
  79 
  80 #define DTRACE_METHOD_UNLOAD_PROBE(method)                                \
  81   {                                                                       \
  82     Method* m = (method);                                                 \
  83     if (m != NULL) {                                                      \
  84       Symbol* klass_name = m->klass_name();                               \
  85       Symbol* name = m->name();                                           \
  86       Symbol* signature = m->signature();                                 \
  87       HOTSPOT_COMPILED_METHOD_UNLOAD(                                     \
  88         (char *) klass_name->bytes(), klass_name->utf8_length(),                   \
  89         (char *) name->bytes(), name->utf8_length(),                               \
  90         (char *) signature->bytes(), signature->utf8_length());                    \
  91     }                                                                     \
  92   }
  93 
  94 #else //  ndef DTRACE_ENABLED
  95 
  96 #define DTRACE_METHOD_UNLOAD_PROBE(method)
  97 
  98 #endif
  99 
 100 bool nmethod::is_compiled_by_c1() const {
 101   if (compiler() == NULL) {
 102     return false;
 103   }
 104   return compiler()->is_c1();
 105 }
 106 bool nmethod::is_compiled_by_jvmci() const {
 107   if (compiler() == NULL || method() == NULL)  return false;  // can happen during debug printing
 108   if (is_native_method()) return false;
 109   return compiler()->is_jvmci();
 110 }
 111 bool nmethod::is_compiled_by_c2() const {
 112   if (compiler() == NULL) {
 113     return false;
 114   }
 115   return compiler()->is_c2();
 116 }
 117 bool nmethod::is_compiled_by_shark() const {
 118   if (compiler() == NULL) {
 119     return false;
 120   }
 121   return compiler()->is_shark();
 122 }
 123 
 124 
 125 
 126 //---------------------------------------------------------------------------------
 127 // NMethod statistics
 128 // They are printed under various flags, including:
 129 //   PrintC1Statistics, PrintOptoStatistics, LogVMOutput, and LogCompilation.
 130 // (In the latter two cases, they like other stats are printed to the log only.)
 131 
 132 #ifndef PRODUCT
 133 // These variables are put into one block to reduce relocations
 134 // and make it simpler to print from the debugger.
 135 struct java_nmethod_stats_struct {
 136   int nmethod_count;
 137   int total_size;
 138   int relocation_size;
 139   int consts_size;
 140   int insts_size;
 141   int stub_size;
 142   int scopes_data_size;
 143   int scopes_pcs_size;
 144   int dependencies_size;
 145   int handler_table_size;
 146   int nul_chk_table_size;
 147   int oops_size;
 148   int metadata_size;
 149 
 150   void note_nmethod(nmethod* nm) {
 151     nmethod_count += 1;
 152     total_size          += nm->size();
 153     relocation_size     += nm->relocation_size();
 154     consts_size         += nm->consts_size();
 155     insts_size          += nm->insts_size();
 156     stub_size           += nm->stub_size();
 157     oops_size           += nm->oops_size();
 158     metadata_size       += nm->metadata_size();
 159     scopes_data_size    += nm->scopes_data_size();
 160     scopes_pcs_size     += nm->scopes_pcs_size();
 161     dependencies_size   += nm->dependencies_size();
 162     handler_table_size  += nm->handler_table_size();
 163     nul_chk_table_size  += nm->nul_chk_table_size();
 164   }
 165   void print_nmethod_stats(const char* name) {
 166     if (nmethod_count == 0)  return;
 167     tty->print_cr("Statistics for %d bytecoded nmethods for %s:", nmethod_count, name);
 168     if (total_size != 0)          tty->print_cr(" total in heap  = %d", total_size);
 169     if (nmethod_count != 0)       tty->print_cr(" header         = %d", nmethod_count * sizeof(nmethod));
 170     if (relocation_size != 0)     tty->print_cr(" relocation     = %d", relocation_size);
 171     if (consts_size != 0)         tty->print_cr(" constants      = %d", consts_size);
 172     if (insts_size != 0)          tty->print_cr(" main code      = %d", insts_size);
 173     if (stub_size != 0)           tty->print_cr(" stub code      = %d", stub_size);
 174     if (oops_size != 0)           tty->print_cr(" oops           = %d", oops_size);
 175     if (metadata_size != 0)       tty->print_cr(" metadata       = %d", metadata_size);
 176     if (scopes_data_size != 0)    tty->print_cr(" scopes data    = %d", scopes_data_size);
 177     if (scopes_pcs_size != 0)     tty->print_cr(" scopes pcs     = %d", scopes_pcs_size);
 178     if (dependencies_size != 0)   tty->print_cr(" dependencies   = %d", dependencies_size);
 179     if (handler_table_size != 0)  tty->print_cr(" handler table  = %d", handler_table_size);
 180     if (nul_chk_table_size != 0)  tty->print_cr(" nul chk table  = %d", nul_chk_table_size);
 181   }
 182 };
 183 
 184 struct native_nmethod_stats_struct {
 185   int native_nmethod_count;
 186   int native_total_size;
 187   int native_relocation_size;
 188   int native_insts_size;
 189   int native_oops_size;
 190   int native_metadata_size;
 191   void note_native_nmethod(nmethod* nm) {
 192     native_nmethod_count += 1;
 193     native_total_size       += nm->size();
 194     native_relocation_size  += nm->relocation_size();
 195     native_insts_size       += nm->insts_size();
 196     native_oops_size        += nm->oops_size();
 197     native_metadata_size    += nm->metadata_size();
 198   }
 199   void print_native_nmethod_stats() {
 200     if (native_nmethod_count == 0)  return;
 201     tty->print_cr("Statistics for %d native nmethods:", native_nmethod_count);
 202     if (native_total_size != 0)       tty->print_cr(" N. total size  = %d", native_total_size);
 203     if (native_relocation_size != 0)  tty->print_cr(" N. relocation  = %d", native_relocation_size);
 204     if (native_insts_size != 0)       tty->print_cr(" N. main code   = %d", native_insts_size);
 205     if (native_oops_size != 0)        tty->print_cr(" N. oops        = %d", native_oops_size);
 206     if (native_metadata_size != 0)    tty->print_cr(" N. metadata    = %d", native_metadata_size);
 207   }
 208 };
 209 
 210 struct pc_nmethod_stats_struct {
 211   int pc_desc_resets;   // number of resets (= number of caches)
 212   int pc_desc_queries;  // queries to nmethod::find_pc_desc
 213   int pc_desc_approx;   // number of those which have approximate true
 214   int pc_desc_repeats;  // number of _pc_descs[0] hits
 215   int pc_desc_hits;     // number of LRU cache hits
 216   int pc_desc_tests;    // total number of PcDesc examinations
 217   int pc_desc_searches; // total number of quasi-binary search steps
 218   int pc_desc_adds;     // number of LUR cache insertions
 219 
 220   void print_pc_stats() {
 221     tty->print_cr("PcDesc Statistics:  %d queries, %.2f comparisons per query",
 222                   pc_desc_queries,
 223                   (double)(pc_desc_tests + pc_desc_searches)
 224                   / pc_desc_queries);
 225     tty->print_cr("  caches=%d queries=%d/%d, hits=%d+%d, tests=%d+%d, adds=%d",
 226                   pc_desc_resets,
 227                   pc_desc_queries, pc_desc_approx,
 228                   pc_desc_repeats, pc_desc_hits,
 229                   pc_desc_tests, pc_desc_searches, pc_desc_adds);
 230   }
 231 };
 232 
 233 #ifdef COMPILER1
 234 static java_nmethod_stats_struct c1_java_nmethod_stats;
 235 #endif
 236 #ifdef COMPILER2
 237 static java_nmethod_stats_struct c2_java_nmethod_stats;
 238 #endif
 239 #if INCLUDE_JVMCI
 240 static java_nmethod_stats_struct jvmci_java_nmethod_stats;
 241 #endif
 242 #ifdef SHARK
 243 static java_nmethod_stats_struct shark_java_nmethod_stats;
 244 #endif
 245 static java_nmethod_stats_struct unknown_java_nmethod_stats;
 246 
 247 static native_nmethod_stats_struct native_nmethod_stats;
 248 static pc_nmethod_stats_struct pc_nmethod_stats;
 249 
 250 static void note_java_nmethod(nmethod* nm) {
 251 #ifdef COMPILER1
 252   if (nm->is_compiled_by_c1()) {
 253     c1_java_nmethod_stats.note_nmethod(nm);
 254   } else
 255 #endif
 256 #ifdef COMPILER2
 257   if (nm->is_compiled_by_c2()) {
 258     c2_java_nmethod_stats.note_nmethod(nm);
 259   } else
 260 #endif
 261 #if INCLUDE_JVMCI
 262   if (nm->is_compiled_by_jvmci()) {
 263     jvmci_java_nmethod_stats.note_nmethod(nm);
 264   } else
 265 #endif
 266 #ifdef SHARK
 267   if (nm->is_compiled_by_shark()) {
 268     shark_java_nmethod_stats.note_nmethod(nm);
 269   } else
 270 #endif
 271   {
 272     unknown_java_nmethod_stats.note_nmethod(nm);
 273   }
 274 }
 275 #endif // !PRODUCT
 276 
 277 //---------------------------------------------------------------------------------
 278 
 279 
 280 ExceptionCache::ExceptionCache(Handle exception, address pc, address handler) {
 281   assert(pc != NULL, "Must be non null");
 282   assert(exception.not_null(), "Must be non null");
 283   assert(handler != NULL, "Must be non null");
 284 
 285   _count = 0;
 286   _exception_type = exception->klass();
 287   _next = NULL;
 288 
 289   add_address_and_handler(pc,handler);
 290 }
 291 
 292 
 293 address ExceptionCache::match(Handle exception, address pc) {
 294   assert(pc != NULL,"Must be non null");
 295   assert(exception.not_null(),"Must be non null");
 296   if (exception->klass() == exception_type()) {
 297     return (test_address(pc));
 298   }
 299 
 300   return NULL;
 301 }
 302 
 303 
 304 bool ExceptionCache::match_exception_with_space(Handle exception) {
 305   assert(exception.not_null(),"Must be non null");
 306   if (exception->klass() == exception_type() && count() < cache_size) {
 307     return true;
 308   }
 309   return false;
 310 }
 311 
 312 
 313 address ExceptionCache::test_address(address addr) {
 314   for (int i=0; i<count(); i++) {
 315     if (pc_at(i) == addr) {
 316       return handler_at(i);
 317     }
 318   }
 319   return NULL;
 320 }
 321 
 322 
 323 bool ExceptionCache::add_address_and_handler(address addr, address handler) {
 324   if (test_address(addr) == handler) return true;
 325   if (count() < cache_size) {
 326     set_pc_at(count(),addr);
 327     set_handler_at(count(), handler);
 328     increment_count();
 329     return true;
 330   }
 331   return false;
 332 }
 333 
 334 
 335 // private method for handling exception cache
 336 // These methods are private, and used to manipulate the exception cache
 337 // directly.
 338 ExceptionCache* nmethod::exception_cache_entry_for_exception(Handle exception) {
 339   ExceptionCache* ec = exception_cache();
 340   while (ec != NULL) {
 341     if (ec->match_exception_with_space(exception)) {
 342       return ec;
 343     }
 344     ec = ec->next();
 345   }
 346   return NULL;
 347 }
 348 
 349 
 350 //-----------------------------------------------------------------------------
 351 
 352 
 353 // Helper used by both find_pc_desc methods.
 354 static inline bool match_desc(PcDesc* pc, int pc_offset, bool approximate) {
 355   NOT_PRODUCT(++pc_nmethod_stats.pc_desc_tests);
 356   if (!approximate)
 357     return pc->pc_offset() == pc_offset;
 358   else
 359     return (pc-1)->pc_offset() < pc_offset && pc_offset <= pc->pc_offset();
 360 }
 361 
 362 void PcDescCache::reset_to(PcDesc* initial_pc_desc) {
 363   if (initial_pc_desc == NULL) {
 364     _pc_descs[0] = NULL; // native method; no PcDescs at all
 365     return;
 366   }
 367   NOT_PRODUCT(++pc_nmethod_stats.pc_desc_resets);
 368   // reset the cache by filling it with benign (non-null) values
 369   assert(initial_pc_desc->pc_offset() < 0, "must be sentinel");
 370   for (int i = 0; i < cache_size; i++)
 371     _pc_descs[i] = initial_pc_desc;
 372 }
 373 
 374 PcDesc* PcDescCache::find_pc_desc(int pc_offset, bool approximate) {
 375   NOT_PRODUCT(++pc_nmethod_stats.pc_desc_queries);
 376   NOT_PRODUCT(if (approximate) ++pc_nmethod_stats.pc_desc_approx);
 377 
 378   // Note: one might think that caching the most recently
 379   // read value separately would be a win, but one would be
 380   // wrong.  When many threads are updating it, the cache
 381   // line it's in would bounce between caches, negating
 382   // any benefit.
 383 
 384   // In order to prevent race conditions do not load cache elements
 385   // repeatedly, but use a local copy:
 386   PcDesc* res;
 387 
 388   // Step one:  Check the most recently added value.
 389   res = _pc_descs[0];
 390   if (res == NULL) return NULL;  // native method; no PcDescs at all
 391   if (match_desc(res, pc_offset, approximate)) {
 392     NOT_PRODUCT(++pc_nmethod_stats.pc_desc_repeats);
 393     return res;
 394   }
 395 
 396   // Step two:  Check the rest of the LRU cache.
 397   for (int i = 1; i < cache_size; ++i) {
 398     res = _pc_descs[i];
 399     if (res->pc_offset() < 0) break;  // optimization: skip empty cache
 400     if (match_desc(res, pc_offset, approximate)) {
 401       NOT_PRODUCT(++pc_nmethod_stats.pc_desc_hits);
 402       return res;
 403     }
 404   }
 405 
 406   // Report failure.
 407   return NULL;
 408 }
 409 
 410 void PcDescCache::add_pc_desc(PcDesc* pc_desc) {
 411   NOT_PRODUCT(++pc_nmethod_stats.pc_desc_adds);
 412   // Update the LRU cache by shifting pc_desc forward.
 413   for (int i = 0; i < cache_size; i++)  {
 414     PcDesc* next = _pc_descs[i];
 415     _pc_descs[i] = pc_desc;
 416     pc_desc = next;
 417   }
 418 }
 419 
 420 // adjust pcs_size so that it is a multiple of both oopSize and
 421 // sizeof(PcDesc) (assumes that if sizeof(PcDesc) is not a multiple
 422 // of oopSize, then 2*sizeof(PcDesc) is)
 423 static int adjust_pcs_size(int pcs_size) {
 424   int nsize = round_to(pcs_size,   oopSize);
 425   if ((nsize % sizeof(PcDesc)) != 0) {
 426     nsize = pcs_size + sizeof(PcDesc);
 427   }
 428   assert((nsize % oopSize) == 0, "correct alignment");
 429   return nsize;
 430 }
 431 
 432 //-----------------------------------------------------------------------------
 433 
 434 
 435 void nmethod::add_exception_cache_entry(ExceptionCache* new_entry) {
 436   assert(ExceptionCache_lock->owned_by_self(),"Must hold the ExceptionCache_lock");
 437   assert(new_entry != NULL,"Must be non null");
 438   assert(new_entry->next() == NULL, "Must be null");
 439 
 440   if (exception_cache() != NULL) {
 441     new_entry->set_next(exception_cache());
 442   }
 443   set_exception_cache(new_entry);
 444 }
 445 
 446 void nmethod::clean_exception_cache(BoolObjectClosure* is_alive) {
 447   ExceptionCache* prev = NULL;
 448   ExceptionCache* curr = exception_cache();
 449 
 450   while (curr != NULL) {
 451     ExceptionCache* next = curr->next();
 452 
 453     Klass* ex_klass = curr->exception_type();
 454     if (ex_klass != NULL && !ex_klass->is_loader_alive(is_alive)) {
 455       if (prev == NULL) {
 456         set_exception_cache(next);
 457       } else {
 458         prev->set_next(next);
 459       }
 460       delete curr;
 461       // prev stays the same.
 462     } else {
 463       prev = curr;
 464     }
 465 
 466     curr = next;
 467   }
 468 }
 469 
 470 // public method for accessing the exception cache
 471 // These are the public access methods.
 472 address nmethod::handler_for_exception_and_pc(Handle exception, address pc) {
 473   // We never grab a lock to read the exception cache, so we may
 474   // have false negatives. This is okay, as it can only happen during
 475   // the first few exception lookups for a given nmethod.
 476   ExceptionCache* ec = exception_cache();
 477   while (ec != NULL) {
 478     address ret_val;
 479     if ((ret_val = ec->match(exception,pc)) != NULL) {
 480       return ret_val;
 481     }
 482     ec = ec->next();
 483   }
 484   return NULL;
 485 }
 486 
 487 
 488 void nmethod::add_handler_for_exception_and_pc(Handle exception, address pc, address handler) {
 489   // There are potential race conditions during exception cache updates, so we
 490   // must own the ExceptionCache_lock before doing ANY modifications. Because
 491   // we don't lock during reads, it is possible to have several threads attempt
 492   // to update the cache with the same data. We need to check for already inserted
 493   // copies of the current data before adding it.
 494 
 495   MutexLocker ml(ExceptionCache_lock);
 496   ExceptionCache* target_entry = exception_cache_entry_for_exception(exception);
 497 
 498   if (target_entry == NULL || !target_entry->add_address_and_handler(pc,handler)) {
 499     target_entry = new ExceptionCache(exception,pc,handler);
 500     add_exception_cache_entry(target_entry);
 501   }
 502 }
 503 
 504 
 505 //-------------end of code for ExceptionCache--------------
 506 
 507 
 508 int nmethod::total_size() const {
 509   return
 510     consts_size()        +
 511     insts_size()         +
 512     stub_size()          +
 513     scopes_data_size()   +
 514     scopes_pcs_size()    +
 515     handler_table_size() +
 516     nul_chk_table_size();
 517 }
 518 
 519 const char* nmethod::compile_kind() const {
 520   if (is_osr_method())     return "osr";
 521   if (method() != NULL && is_native_method())  return "c2n";
 522   return NULL;
 523 }
 524 
 525 // Fill in default values for various flag fields
 526 void nmethod::init_defaults() {
 527   _state                      = in_use;
 528   _unloading_clock            = 0;
 529   _marked_for_reclamation     = 0;
 530   _has_flushed_dependencies   = 0;
 531   _has_unsafe_access          = 0;
 532   _has_method_handle_invokes  = 0;
 533   _lazy_critical_native       = 0;
 534   _has_wide_vectors           = 0;
 535   _marked_for_deoptimization  = 0;
 536   _lock_count                 = 0;
 537   _stack_traversal_mark       = 0;
 538   _unload_reported            = false; // jvmti state
 539 
 540 #ifdef ASSERT
 541   _oops_are_stale             = false;
 542 #endif
 543 
 544   _oops_do_mark_link       = NULL;
 545   _jmethod_id              = NULL;
 546   _osr_link                = NULL;
 547   if (UseG1GC) {
 548     _unloading_next        = NULL;
 549   } else {
 550     _scavenge_root_link    = NULL;
 551   }
 552   _scavenge_root_state     = 0;
 553   _compiler                = NULL;
 554 #if INCLUDE_RTM_OPT
 555   _rtm_state               = NoRTM;
 556 #endif
 557 #if INCLUDE_JVMCI
 558   _jvmci_installed_code   = NULL;
 559   _speculation_log        = NULL;
 560 #endif
 561 }
 562 
 563 nmethod* nmethod::new_native_nmethod(methodHandle method,
 564   int compile_id,
 565   CodeBuffer *code_buffer,
 566   int vep_offset,
 567   int frame_complete,
 568   int frame_size,
 569   ByteSize basic_lock_owner_sp_offset,
 570   ByteSize basic_lock_sp_offset,
 571   OopMapSet* oop_maps) {
 572   code_buffer->finalize_oop_references(method);
 573   // create nmethod
 574   nmethod* nm = NULL;
 575   {
 576     MutexLockerEx mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
 577     int native_nmethod_size = allocation_size(code_buffer, sizeof(nmethod));
 578     CodeOffsets offsets;
 579     offsets.set_value(CodeOffsets::Verified_Entry, vep_offset);
 580     offsets.set_value(CodeOffsets::Frame_Complete, frame_complete);
 581     nm = new (native_nmethod_size, CompLevel_none) nmethod(method(), native_nmethod_size,
 582                                             compile_id, &offsets,
 583                                             code_buffer, frame_size,
 584                                             basic_lock_owner_sp_offset,
 585                                             basic_lock_sp_offset, oop_maps);
 586     NOT_PRODUCT(if (nm != NULL)  native_nmethod_stats.note_native_nmethod(nm));
 587     if ((PrintAssembly || CompilerOracle::should_print(method)) && nm != NULL) {
 588       Disassembler::decode(nm);
 589     }
 590   }
 591   // verify nmethod
 592   debug_only(if (nm) nm->verify();) // might block
 593 
 594   if (nm != NULL) {
 595     nm->log_new_nmethod();
 596   }
 597 
 598   return nm;
 599 }
 600 
 601 nmethod* nmethod::new_nmethod(methodHandle method,
 602   int compile_id,
 603   int entry_bci,
 604   CodeOffsets* offsets,
 605   int orig_pc_offset,
 606   DebugInformationRecorder* debug_info,
 607   Dependencies* dependencies,
 608   CodeBuffer* code_buffer, int frame_size,
 609   OopMapSet* oop_maps,
 610   ExceptionHandlerTable* handler_table,
 611   ImplicitExceptionTable* nul_chk_table,
 612   AbstractCompiler* compiler,
 613   int comp_level
 614 #if INCLUDE_JVMCI
 615   , Handle installed_code,
 616   Handle speculationLog
 617 #endif
 618 )
 619 {
 620   assert(debug_info->oop_recorder() == code_buffer->oop_recorder(), "shared OR");
 621   code_buffer->finalize_oop_references(method);
 622   // create nmethod
 623   nmethod* nm = NULL;
 624   { MutexLockerEx mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
 625     int nmethod_size =
 626       allocation_size(code_buffer, sizeof(nmethod))
 627       + adjust_pcs_size(debug_info->pcs_size())
 628       + round_to(dependencies->size_in_bytes() , oopSize)
 629       + round_to(handler_table->size_in_bytes(), oopSize)
 630       + round_to(nul_chk_table->size_in_bytes(), oopSize)
 631       + round_to(debug_info->data_size()       , oopSize);
 632 
 633     nm = new (nmethod_size, comp_level)
 634     nmethod(method(), nmethod_size, compile_id, entry_bci, offsets,
 635             orig_pc_offset, debug_info, dependencies, code_buffer, frame_size,
 636             oop_maps,
 637             handler_table,
 638             nul_chk_table,
 639             compiler,
 640             comp_level
 641 #if INCLUDE_JVMCI
 642             , installed_code,
 643             speculationLog
 644 #endif
 645             );
 646 
 647     if (nm != NULL) {
 648       // To make dependency checking during class loading fast, record
 649       // the nmethod dependencies in the classes it is dependent on.
 650       // This allows the dependency checking code to simply walk the
 651       // class hierarchy above the loaded class, checking only nmethods
 652       // which are dependent on those classes.  The slow way is to
 653       // check every nmethod for dependencies which makes it linear in
 654       // the number of methods compiled.  For applications with a lot
 655       // classes the slow way is too slow.
 656       for (Dependencies::DepStream deps(nm); deps.next(); ) {
 657         if (deps.type() == Dependencies::call_site_target_value) {
 658           // CallSite dependencies are managed on per-CallSite instance basis.
 659           oop call_site = deps.argument_oop(0);
 660           MethodHandles::add_dependent_nmethod(call_site, nm);
 661         } else {
 662           Klass* klass = deps.context_type();
 663           if (klass == NULL) {
 664             continue;  // ignore things like evol_method
 665           }
 666           // record this nmethod as dependent on this klass
 667           InstanceKlass::cast(klass)->add_dependent_nmethod(nm);
 668         }
 669       }
 670       NOT_PRODUCT(if (nm != NULL)  note_java_nmethod(nm));
 671       if (PrintAssembly || CompilerOracle::has_option_string(method, "PrintAssembly")) {
 672         Disassembler::decode(nm);
 673       }
 674     }
 675   }
 676   // Do verification and logging outside CodeCache_lock.
 677   if (nm != NULL) {
 678     // Safepoints in nmethod::verify aren't allowed because nm hasn't been installed yet.
 679     DEBUG_ONLY(nm->verify();)
 680     nm->log_new_nmethod();
 681   }
 682   return nm;
 683 }
 684 
 685 #ifdef _MSC_VER
 686 #pragma warning(push)
 687 #pragma warning(disable:4355) //  warning C4355: 'this' : used in base member initializer list
 688 #endif
 689 // For native wrappers
 690 nmethod::nmethod(
 691   Method* method,
 692   int nmethod_size,
 693   int compile_id,
 694   CodeOffsets* offsets,
 695   CodeBuffer* code_buffer,
 696   int frame_size,
 697   ByteSize basic_lock_owner_sp_offset,
 698   ByteSize basic_lock_sp_offset,
 699   OopMapSet* oop_maps )
 700   : CodeBlob("native nmethod", code_buffer, sizeof(nmethod),
 701              nmethod_size, offsets->value(CodeOffsets::Frame_Complete), frame_size, oop_maps),
 702   _native_receiver_sp_offset(basic_lock_owner_sp_offset),
 703   _native_basic_lock_sp_offset(basic_lock_sp_offset)
 704 {
 705   {
 706     debug_only(No_Safepoint_Verifier nsv;)
 707     assert_locked_or_safepoint(CodeCache_lock);
 708 
 709     init_defaults();
 710     _method                  = method;
 711     _entry_bci               = InvocationEntryBci;
 712     // We have no exception handler or deopt handler make the
 713     // values something that will never match a pc like the nmethod vtable entry
 714     _exception_offset        = 0;
 715     _deoptimize_offset       = 0;
 716     _deoptimize_mh_offset    = 0;
 717     _orig_pc_offset          = 0;
 718 
 719     _consts_offset           = data_offset();
 720     _stub_offset             = data_offset();
 721     _oops_offset             = data_offset();
 722     _metadata_offset         = _oops_offset         + round_to(code_buffer->total_oop_size(), oopSize);
 723     _scopes_data_offset      = _metadata_offset     + round_to(code_buffer->total_metadata_size(), wordSize);
 724     _scopes_pcs_offset       = _scopes_data_offset;
 725     _dependencies_offset     = _scopes_pcs_offset;
 726     _handler_table_offset    = _dependencies_offset;
 727     _nul_chk_table_offset    = _handler_table_offset;
 728     _nmethod_end_offset      = _nul_chk_table_offset;
 729     _compile_id              = compile_id;
 730     _comp_level              = CompLevel_none;
 731     _entry_point             = code_begin()          + offsets->value(CodeOffsets::Entry);
 732     _verified_entry_point    = code_begin()          + offsets->value(CodeOffsets::Verified_Entry);
 733     _osr_entry_point         = NULL;
 734     _exception_cache         = NULL;
 735     _pc_desc_cache.reset_to(NULL);
 736     _hotness_counter         = NMethodSweeper::hotness_counter_reset_val();
 737 
 738     code_buffer->copy_values_to(this);
 739     if (ScavengeRootsInCode) {
 740       if (detect_scavenge_root_oops()) {
 741         CodeCache::add_scavenge_root_nmethod(this);
 742       }
 743       Universe::heap()->register_nmethod(this);
 744     }
 745     debug_only(verify_scavenge_root_oops());
 746     CodeCache::commit(this);
 747   }
 748 
 749   if (PrintNativeNMethods || PrintDebugInfo || PrintRelocations || PrintDependencies) {
 750     ttyLocker ttyl;  // keep the following output all in one block
 751     // This output goes directly to the tty, not the compiler log.
 752     // To enable tools to match it up with the compilation activity,
 753     // be sure to tag this tty output with the compile ID.
 754     if (xtty != NULL) {
 755       xtty->begin_head("print_native_nmethod");
 756       xtty->method(_method);
 757       xtty->stamp();
 758       xtty->end_head(" address='" INTPTR_FORMAT "'", (intptr_t) this);
 759     }
 760     // print the header part first
 761     print();
 762     // then print the requested information
 763     if (PrintNativeNMethods) {
 764       print_code();
 765       if (oop_maps != NULL) {
 766         oop_maps->print();
 767       }
 768     }
 769     if (PrintRelocations) {
 770       print_relocations();
 771     }
 772     if (xtty != NULL) {
 773       xtty->tail("print_native_nmethod");
 774     }
 775   }
 776 }
 777 
 778 #ifdef _MSC_VER
 779 #pragma warning(pop)
 780 #endif
 781 
 782 void* nmethod::operator new(size_t size, int nmethod_size, int comp_level) throw () {
 783   return CodeCache::allocate(nmethod_size, CodeCache::get_code_blob_type(comp_level));
 784 }
 785 
 786 nmethod::nmethod(
 787   Method* method,
 788   int nmethod_size,
 789   int compile_id,
 790   int entry_bci,
 791   CodeOffsets* offsets,
 792   int orig_pc_offset,
 793   DebugInformationRecorder* debug_info,
 794   Dependencies* dependencies,
 795   CodeBuffer *code_buffer,
 796   int frame_size,
 797   OopMapSet* oop_maps,
 798   ExceptionHandlerTable* handler_table,
 799   ImplicitExceptionTable* nul_chk_table,
 800   AbstractCompiler* compiler,
 801   int comp_level
 802 #if INCLUDE_JVMCI
 803   , Handle installed_code,
 804   Handle speculation_log
 805 #endif
 806   )
 807   : CodeBlob("nmethod", code_buffer, sizeof(nmethod),
 808              nmethod_size, offsets->value(CodeOffsets::Frame_Complete), frame_size, oop_maps),
 809   _native_receiver_sp_offset(in_ByteSize(-1)),
 810   _native_basic_lock_sp_offset(in_ByteSize(-1))
 811 {
 812   assert(debug_info->oop_recorder() == code_buffer->oop_recorder(), "shared OR");
 813   {
 814     debug_only(No_Safepoint_Verifier nsv;)
 815     assert_locked_or_safepoint(CodeCache_lock);
 816 
 817     init_defaults();
 818     _method                  = method;
 819     _entry_bci               = entry_bci;
 820     _compile_id              = compile_id;
 821     _comp_level              = comp_level;
 822     _compiler                = compiler;
 823     _orig_pc_offset          = orig_pc_offset;
 824     _hotness_counter         = NMethodSweeper::hotness_counter_reset_val();
 825 
 826     // Section offsets
 827     _consts_offset           = content_offset()      + code_buffer->total_offset_of(code_buffer->consts());
 828     _stub_offset             = content_offset()      + code_buffer->total_offset_of(code_buffer->stubs());
 829 
 830 #if INCLUDE_JVMCI
 831     _jvmci_installed_code = installed_code();
 832     _speculation_log = (instanceOop)speculation_log();
 833 
 834     if (compiler->is_jvmci()) {
 835       // JVMCI might not produce any stub sections
 836       if (offsets->value(CodeOffsets::Exceptions) != -1) {
 837         _exception_offset        = code_offset()          + offsets->value(CodeOffsets::Exceptions);
 838       } else {
 839         _exception_offset = -1;
 840       }
 841       if (offsets->value(CodeOffsets::Deopt) != -1) {
 842         _deoptimize_offset       = code_offset()          + offsets->value(CodeOffsets::Deopt);
 843       } else {
 844         _deoptimize_offset = -1;
 845       }
 846       if (offsets->value(CodeOffsets::DeoptMH) != -1) {
 847         _deoptimize_mh_offset  = code_offset()          + offsets->value(CodeOffsets::DeoptMH);
 848       } else {
 849         _deoptimize_mh_offset  = -1;
 850       }
 851     } else {
 852 #endif
 853     // Exception handler and deopt handler are in the stub section
 854     assert(offsets->value(CodeOffsets::Exceptions) != -1, "must be set");
 855     assert(offsets->value(CodeOffsets::Deopt     ) != -1, "must be set");
 856 
 857     _exception_offset        = _stub_offset          + offsets->value(CodeOffsets::Exceptions);
 858     _deoptimize_offset       = _stub_offset          + offsets->value(CodeOffsets::Deopt);
 859     if (offsets->value(CodeOffsets::DeoptMH) != -1) {
 860       _deoptimize_mh_offset  = _stub_offset          + offsets->value(CodeOffsets::DeoptMH);
 861     } else {
 862       _deoptimize_mh_offset  = -1;
 863 #if INCLUDE_JVMCI
 864     }
 865 #endif
 866     }
 867     if (offsets->value(CodeOffsets::UnwindHandler) != -1) {
 868       _unwind_handler_offset = code_offset()         + offsets->value(CodeOffsets::UnwindHandler);
 869     } else {
 870       _unwind_handler_offset = -1;
 871     }
 872 
 873     _oops_offset             = data_offset();
 874     _metadata_offset         = _oops_offset          + round_to(code_buffer->total_oop_size(), oopSize);
 875     _scopes_data_offset      = _metadata_offset      + round_to(code_buffer->total_metadata_size(), wordSize);
 876 
 877     _scopes_pcs_offset       = _scopes_data_offset   + round_to(debug_info->data_size       (), oopSize);
 878     _dependencies_offset     = _scopes_pcs_offset    + adjust_pcs_size(debug_info->pcs_size());
 879     _handler_table_offset    = _dependencies_offset  + round_to(dependencies->size_in_bytes (), oopSize);
 880     _nul_chk_table_offset    = _handler_table_offset + round_to(handler_table->size_in_bytes(), oopSize);
 881     _nmethod_end_offset      = _nul_chk_table_offset + round_to(nul_chk_table->size_in_bytes(), oopSize);
 882 
 883     _entry_point             = code_begin()          + offsets->value(CodeOffsets::Entry);
 884     _verified_entry_point    = code_begin()          + offsets->value(CodeOffsets::Verified_Entry);
 885     _osr_entry_point         = code_begin()          + offsets->value(CodeOffsets::OSR_Entry);
 886     _exception_cache         = NULL;
 887     _pc_desc_cache.reset_to(scopes_pcs_begin());
 888 
 889     // Copy contents of ScopeDescRecorder to nmethod
 890     code_buffer->copy_values_to(this);
 891     debug_info->copy_to(this);
 892     dependencies->copy_to(this);
 893     if (ScavengeRootsInCode) {
 894       if (detect_scavenge_root_oops()) {
 895         CodeCache::add_scavenge_root_nmethod(this);
 896       }
 897       Universe::heap()->register_nmethod(this);
 898     }
 899     debug_only(verify_scavenge_root_oops());
 900 
 901     CodeCache::commit(this);
 902 
 903     // Copy contents of ExceptionHandlerTable to nmethod
 904     handler_table->copy_to(this);
 905     nul_chk_table->copy_to(this);
 906 
 907     // we use the information of entry points to find out if a method is
 908     // static or non static
 909     assert(compiler->is_c2() || compiler->is_jvmci() ||
 910            _method->is_static() == (entry_point() == _verified_entry_point),
 911            " entry points must be same for static methods and vice versa");
 912   }
 913 
 914   bool printnmethods = PrintNMethods || PrintNMethodsAtLevel == _comp_level
 915     || CompilerOracle::should_print(_method)
 916     || CompilerOracle::has_option_string(_method, "PrintNMethods");
 917   if (printnmethods || PrintDebugInfo || PrintRelocations || PrintDependencies || PrintExceptionHandlers) {
 918     print_nmethod(printnmethods);
 919   }
 920 }
 921 
 922 // Print a short set of xml attributes to identify this nmethod.  The
 923 // output should be embedded in some other element.
 924 void nmethod::log_identity(xmlStream* log) const {
 925   log->print(" compile_id='%d'", compile_id());
 926   const char* nm_kind = compile_kind();
 927   if (nm_kind != NULL)  log->print(" compile_kind='%s'", nm_kind);
 928   if (compiler() != NULL) {
 929     log->print(" compiler='%s'", compiler()->name());
 930   }
 931   if (TieredCompilation) {
 932     log->print(" level='%d'", comp_level());
 933   }
 934 }
 935 
 936 
 937 #define LOG_OFFSET(log, name)                    \
 938   if ((intptr_t)name##_end() - (intptr_t)name##_begin()) \
 939     log->print(" " XSTR(name) "_offset='%d'"    , \
 940                (intptr_t)name##_begin() - (intptr_t)this)
 941 
 942 
 943 void nmethod::log_new_nmethod() const {
 944   if (LogCompilation && xtty != NULL) {
 945     ttyLocker ttyl;
 946     HandleMark hm;
 947     xtty->begin_elem("nmethod");
 948     log_identity(xtty);
 949     xtty->print(" entry='" INTPTR_FORMAT "' size='%d'", code_begin(), size());
 950     xtty->print(" address='" INTPTR_FORMAT "'", (intptr_t) this);
 951 
 952     LOG_OFFSET(xtty, relocation);
 953     LOG_OFFSET(xtty, consts);
 954     LOG_OFFSET(xtty, insts);
 955     LOG_OFFSET(xtty, stub);
 956     LOG_OFFSET(xtty, scopes_data);
 957     LOG_OFFSET(xtty, scopes_pcs);
 958     LOG_OFFSET(xtty, dependencies);
 959     LOG_OFFSET(xtty, handler_table);
 960     LOG_OFFSET(xtty, nul_chk_table);
 961     LOG_OFFSET(xtty, oops);
 962     LOG_OFFSET(xtty, metadata);
 963 
 964     xtty->method(method());
 965     xtty->stamp();
 966     xtty->end_elem();
 967   }
 968 }
 969 
 970 #undef LOG_OFFSET
 971 
 972 
 973 // Print out more verbose output usually for a newly created nmethod.
 974 void nmethod::print_on(outputStream* st, const char* msg) const {
 975   if (st != NULL) {
 976     ttyLocker ttyl;
 977     if (WizardMode) {
 978       CompileTask::print_compilation(st, this, msg, /*short_form:*/ true);
 979       st->print_cr(" (" INTPTR_FORMAT ")", this);
 980     } else {
 981       CompileTask::print_compilation(st, this, msg, /*short_form:*/ false);
 982     }
 983   }
 984 }
 985 
 986 
 987 void nmethod::print_nmethod(bool printmethod) {
 988   ttyLocker ttyl;  // keep the following output all in one block
 989   if (xtty != NULL) {
 990     xtty->begin_head("print_nmethod");
 991     xtty->stamp();
 992     xtty->end_head();
 993   }
 994   // print the header part first
 995   print();
 996   // then print the requested information
 997   if (printmethod) {
 998     print_code();
 999     print_pcs();
1000     if (oop_maps()) {
1001       oop_maps()->print();
1002     }
1003   }
1004   if (PrintDebugInfo || CompilerOracle::has_option_string(_method, "PrintDebugInfo")) {
1005     print_scopes();
1006   }
1007   if (PrintRelocations || CompilerOracle::has_option_string(_method, "PrintRelocations")) {
1008     print_relocations();
1009   }
1010   if (PrintDependencies || CompilerOracle::has_option_string(_method, "PrintDependencies")) {
1011     print_dependencies();
1012   }
1013   if (PrintExceptionHandlers) {
1014     print_handler_table();
1015     print_nul_chk_table();
1016   }
1017   if (xtty != NULL) {
1018     xtty->tail("print_nmethod");
1019   }
1020 }
1021 
1022 
1023 // Promote one word from an assembly-time handle to a live embedded oop.
1024 inline void nmethod::initialize_immediate_oop(oop* dest, jobject handle) {
1025   if (handle == NULL ||
1026       // As a special case, IC oops are initialized to 1 or -1.
1027       handle == (jobject) Universe::non_oop_word()) {
1028     (*dest) = (oop) handle;
1029   } else {
1030     (*dest) = JNIHandles::resolve_non_null(handle);
1031   }
1032 }
1033 
1034 
1035 // Have to have the same name because it's called by a template
1036 void nmethod::copy_values(GrowableArray<jobject>* array) {
1037   int length = array->length();
1038   assert((address)(oops_begin() + length) <= (address)oops_end(), "oops big enough");
1039   oop* dest = oops_begin();
1040   for (int index = 0 ; index < length; index++) {
1041     initialize_immediate_oop(&dest[index], array->at(index));
1042   }
1043 
1044   // Now we can fix up all the oops in the code.  We need to do this
1045   // in the code because the assembler uses jobjects as placeholders.
1046   // The code and relocations have already been initialized by the
1047   // CodeBlob constructor, so it is valid even at this early point to
1048   // iterate over relocations and patch the code.
1049   fix_oop_relocations(NULL, NULL, /*initialize_immediates=*/ true);
1050 }
1051 
1052 void nmethod::copy_values(GrowableArray<Metadata*>* array) {
1053   int length = array->length();
1054   assert((address)(metadata_begin() + length) <= (address)metadata_end(), "big enough");
1055   Metadata** dest = metadata_begin();
1056   for (int index = 0 ; index < length; index++) {
1057     dest[index] = array->at(index);
1058   }
1059 }
1060 
1061 bool nmethod::is_at_poll_return(address pc) {
1062   RelocIterator iter(this, pc, pc+1);
1063   while (iter.next()) {
1064     if (iter.type() == relocInfo::poll_return_type)
1065       return true;
1066   }
1067   return false;
1068 }
1069 
1070 
1071 bool nmethod::is_at_poll_or_poll_return(address pc) {
1072   RelocIterator iter(this, pc, pc+1);
1073   while (iter.next()) {
1074     relocInfo::relocType t = iter.type();
1075     if (t == relocInfo::poll_return_type || t == relocInfo::poll_type)
1076       return true;
1077   }
1078   return false;
1079 }
1080 
1081 
1082 void nmethod::fix_oop_relocations(address begin, address end, bool initialize_immediates) {
1083   // re-patch all oop-bearing instructions, just in case some oops moved
1084   RelocIterator iter(this, begin, end);
1085   while (iter.next()) {
1086     if (iter.type() == relocInfo::oop_type) {
1087       oop_Relocation* reloc = iter.oop_reloc();
1088       if (initialize_immediates && reloc->oop_is_immediate()) {
1089         oop* dest = reloc->oop_addr();
1090         initialize_immediate_oop(dest, (jobject) *dest);
1091       }
1092       // Refresh the oop-related bits of this instruction.
1093       reloc->fix_oop_relocation();
1094     } else if (iter.type() == relocInfo::metadata_type) {
1095       metadata_Relocation* reloc = iter.metadata_reloc();
1096       reloc->fix_metadata_relocation();
1097     }
1098   }
1099 }
1100 
1101 
1102 void nmethod::verify_oop_relocations() {
1103   // Ensure sure that the code matches the current oop values
1104   RelocIterator iter(this, NULL, NULL);
1105   while (iter.next()) {
1106     if (iter.type() == relocInfo::oop_type) {
1107       oop_Relocation* reloc = iter.oop_reloc();
1108       if (!reloc->oop_is_immediate()) {
1109         reloc->verify_oop_relocation();
1110       }
1111     }
1112   }
1113 }
1114 
1115 
1116 ScopeDesc* nmethod::scope_desc_at(address pc) {
1117   PcDesc* pd = pc_desc_at(pc);
1118   guarantee(pd != NULL, "scope must be present");
1119   return new ScopeDesc(this, pd->scope_decode_offset(),
1120                        pd->obj_decode_offset(), pd->should_reexecute(), pd->rethrow_exception(),
1121                        pd->return_oop());
1122 }
1123 
1124 
1125 void nmethod::clear_inline_caches() {
1126   assert(SafepointSynchronize::is_at_safepoint(), "cleaning of IC's only allowed at safepoint");
1127   if (is_zombie()) {
1128     return;
1129   }
1130 
1131   RelocIterator iter(this);
1132   while (iter.next()) {
1133     iter.reloc()->clear_inline_cache();
1134   }
1135 }
1136 
1137 // Clear ICStubs of all compiled ICs
1138 void nmethod::clear_ic_stubs() {
1139   assert_locked_or_safepoint(CompiledIC_lock);
1140   RelocIterator iter(this);
1141   while(iter.next()) {
1142     if (iter.type() == relocInfo::virtual_call_type) {
1143       CompiledIC* ic = CompiledIC_at(&iter);
1144       ic->clear_ic_stub();
1145     }
1146   }
1147 }
1148 
1149 
1150 void nmethod::cleanup_inline_caches() {
1151   assert_locked_or_safepoint(CompiledIC_lock);
1152 
1153   // If the method is not entrant or zombie then a JMP is plastered over the
1154   // first few bytes.  If an oop in the old code was there, that oop
1155   // should not get GC'd.  Skip the first few bytes of oops on
1156   // not-entrant methods.
1157   address low_boundary = verified_entry_point();
1158   if (!is_in_use()) {
1159     low_boundary += NativeJump::instruction_size;
1160     // %%% Note:  On SPARC we patch only a 4-byte trap, not a full NativeJump.
1161     // This means that the low_boundary is going to be a little too high.
1162     // This shouldn't matter, since oops of non-entrant methods are never used.
1163     // In fact, why are we bothering to look at oops in a non-entrant method??
1164   }
1165 
1166   // Find all calls in an nmethod and clear the ones that point to non-entrant,
1167   // zombie and unloaded nmethods.
1168   ResourceMark rm;
1169   RelocIterator iter(this, low_boundary);
1170   while(iter.next()) {
1171     switch(iter.type()) {
1172       case relocInfo::virtual_call_type:
1173       case relocInfo::opt_virtual_call_type: {
1174         CompiledIC *ic = CompiledIC_at(&iter);
1175         // Ok, to lookup references to zombies here
1176         CodeBlob *cb = CodeCache::find_blob_unsafe(ic->ic_destination());
1177         if( cb != NULL && cb->is_nmethod() ) {
1178           nmethod* nm = (nmethod*)cb;
1179           // Clean inline caches pointing to zombie, non-entrant and unloaded methods
1180           if (!nm->is_in_use() || (nm->method()->code() != nm)) ic->set_to_clean();
1181         }
1182         break;
1183       }
1184       case relocInfo::static_call_type: {
1185         CompiledStaticCall *csc = compiledStaticCall_at(iter.reloc());
1186         CodeBlob *cb = CodeCache::find_blob_unsafe(csc->destination());
1187         if( cb != NULL && cb->is_nmethod() ) {
1188           nmethod* nm = (nmethod*)cb;
1189           // Clean inline caches pointing to zombie, non-entrant and unloaded methods
1190           if (!nm->is_in_use() || (nm->method()->code() != nm)) csc->set_to_clean();
1191         }
1192         break;
1193       }
1194     }
1195   }
1196 }
1197 
1198 void nmethod::verify_clean_inline_caches() {
1199   assert_locked_or_safepoint(CompiledIC_lock);
1200 
1201   // If the method is not entrant or zombie then a JMP is plastered over the
1202   // first few bytes.  If an oop in the old code was there, that oop
1203   // should not get GC'd.  Skip the first few bytes of oops on
1204   // not-entrant methods.
1205   address low_boundary = verified_entry_point();
1206   if (!is_in_use()) {
1207     low_boundary += NativeJump::instruction_size;
1208     // %%% Note:  On SPARC we patch only a 4-byte trap, not a full NativeJump.
1209     // This means that the low_boundary is going to be a little too high.
1210     // This shouldn't matter, since oops of non-entrant methods are never used.
1211     // In fact, why are we bothering to look at oops in a non-entrant method??
1212   }
1213 
1214   ResourceMark rm;
1215   RelocIterator iter(this, low_boundary);
1216   while(iter.next()) {
1217     switch(iter.type()) {
1218       case relocInfo::virtual_call_type:
1219       case relocInfo::opt_virtual_call_type: {
1220         CompiledIC *ic = CompiledIC_at(&iter);
1221         // Ok, to lookup references to zombies here
1222         CodeBlob *cb = CodeCache::find_blob_unsafe(ic->ic_destination());
1223         if( cb != NULL && cb->is_nmethod() ) {
1224           nmethod* nm = (nmethod*)cb;
1225           // Verify that inline caches pointing to both zombie and not_entrant methods are clean
1226           if (!nm->is_in_use() || (nm->method()->code() != nm)) {
1227             assert(ic->is_clean(), "IC should be clean");
1228           }
1229         }
1230         break;
1231       }
1232       case relocInfo::static_call_type: {
1233         CompiledStaticCall *csc = compiledStaticCall_at(iter.reloc());
1234         CodeBlob *cb = CodeCache::find_blob_unsafe(csc->destination());
1235         if( cb != NULL && cb->is_nmethod() ) {
1236           nmethod* nm = (nmethod*)cb;
1237           // Verify that inline caches pointing to both zombie and not_entrant methods are clean
1238           if (!nm->is_in_use() || (nm->method()->code() != nm)) {
1239             assert(csc->is_clean(), "IC should be clean");
1240           }
1241         }
1242         break;
1243       }
1244     }
1245   }
1246 }
1247 
1248 int nmethod::verify_icholder_relocations() {
1249   int count = 0;
1250 
1251   RelocIterator iter(this);
1252   while(iter.next()) {
1253     if (iter.type() == relocInfo::virtual_call_type) {
1254       if (CompiledIC::is_icholder_call_site(iter.virtual_call_reloc())) {
1255         CompiledIC *ic = CompiledIC_at(&iter);
1256         if (TraceCompiledIC) {
1257           tty->print("noticed icholder " INTPTR_FORMAT " ", p2i(ic->cached_icholder()));
1258           ic->print();
1259         }
1260         assert(ic->cached_icholder() != NULL, "must be non-NULL");
1261         count++;
1262       }
1263     }
1264   }
1265 
1266   return count;
1267 }
1268 
1269 // This is a private interface with the sweeper.
1270 void nmethod::mark_as_seen_on_stack() {
1271   assert(is_alive(), "Must be an alive method");
1272   // Set the traversal mark to ensure that the sweeper does 2
1273   // cleaning passes before moving to zombie.
1274   set_stack_traversal_mark(NMethodSweeper::traversal_count());
1275 }
1276 
1277 // Tell if a non-entrant method can be converted to a zombie (i.e.,
1278 // there are no activations on the stack, not in use by the VM,
1279 // and not in use by the ServiceThread)
1280 bool nmethod::can_not_entrant_be_converted() {
1281   assert(is_not_entrant(), "must be a non-entrant method");
1282 
1283   // Since the nmethod sweeper only does partial sweep the sweeper's traversal
1284   // count can be greater than the stack traversal count before it hits the
1285   // nmethod for the second time.
1286   return stack_traversal_mark()+1 < NMethodSweeper::traversal_count() &&
1287          !is_locked_by_vm();
1288 }
1289 
1290 void nmethod::inc_decompile_count() {
1291   if (!is_compiled_by_c2() && !is_compiled_by_jvmci()) return;
1292   // Could be gated by ProfileTraps, but do not bother...
1293   Method* m = method();
1294   if (m == NULL)  return;
1295   MethodData* mdo = m->method_data();
1296   if (mdo == NULL)  return;
1297   // There is a benign race here.  See comments in methodData.hpp.
1298   mdo->inc_decompile_count();
1299 }
1300 
1301 void nmethod::increase_unloading_clock() {
1302   _global_unloading_clock++;
1303   if (_global_unloading_clock == 0) {
1304     // _nmethods are allocated with _unloading_clock == 0,
1305     // so 0 is never used as a clock value.
1306     _global_unloading_clock = 1;
1307   }
1308 }
1309 
1310 void nmethod::set_unloading_clock(unsigned char unloading_clock) {
1311   OrderAccess::release_store((volatile jubyte*)&_unloading_clock, unloading_clock);
1312 }
1313 
1314 unsigned char nmethod::unloading_clock() {
1315   return (unsigned char)OrderAccess::load_acquire((volatile jubyte*)&_unloading_clock);
1316 }
1317 
1318 void nmethod::make_unloaded(BoolObjectClosure* is_alive, oop cause) {
1319 
1320   post_compiled_method_unload();
1321 
1322   // Since this nmethod is being unloaded, make sure that dependencies
1323   // recorded in instanceKlasses get flushed and pass non-NULL closure to
1324   // indicate that this work is being done during a GC.
1325   assert(Universe::heap()->is_gc_active(), "should only be called during gc");
1326   assert(is_alive != NULL, "Should be non-NULL");
1327   // A non-NULL is_alive closure indicates that this is being called during GC.
1328   flush_dependencies(is_alive);
1329 
1330   // Break cycle between nmethod & method
1331   if (TraceClassUnloading && WizardMode) {
1332     tty->print_cr("[Class unloading: Making nmethod " INTPTR_FORMAT
1333                   " unloadable], Method*(" INTPTR_FORMAT
1334                   "), cause(" INTPTR_FORMAT ")",
1335                   this, (address)_method, (address)cause);
1336     if (!Universe::heap()->is_gc_active())
1337       cause->klass()->print();
1338   }
1339   // Unlink the osr method, so we do not look this up again
1340   if (is_osr_method()) {
1341     invalidate_osr_method();
1342   }
1343   // If _method is already NULL the Method* is about to be unloaded,
1344   // so we don't have to break the cycle. Note that it is possible to
1345   // have the Method* live here, in case we unload the nmethod because
1346   // it is pointing to some oop (other than the Method*) being unloaded.
1347   if (_method != NULL) {
1348     // OSR methods point to the Method*, but the Method* does not
1349     // point back!
1350     if (_method->code() == this) {
1351       _method->clear_code(); // Break a cycle
1352     }
1353     _method = NULL;            // Clear the method of this dead nmethod
1354   }
1355 
1356   // Make the class unloaded - i.e., change state and notify sweeper
1357   assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint");
1358   if (is_in_use()) {
1359     // Transitioning directly from live to unloaded -- so
1360     // we need to force a cache clean-up; remember this
1361     // for later on.
1362     CodeCache::set_needs_cache_clean(true);
1363   }
1364 
1365   // Unregister must be done before the state change
1366   Universe::heap()->unregister_nmethod(this);
1367 
1368 #if INCLUDE_JVMCI
1369   // The method can only be unloaded after the pointer to the installed code
1370   // Java wrapper is no longer alive. Here we need to clear out this weak
1371   // reference to the dead object. Nulling out the reference has to happen
1372   // after the method is unregistered since the original value may be still
1373   // tracked by the rset.
1374   if (_jvmci_installed_code != NULL) {
1375     InstalledCode::set_address(_jvmci_installed_code, 0);
1376     _jvmci_installed_code = NULL;
1377   }
1378 #endif
1379 
1380   _state = unloaded;
1381 
1382   // Log the unloading.
1383   log_state_change();
1384 
1385   // The Method* is gone at this point
1386   assert(_method == NULL, "Tautology");
1387 
1388   set_osr_link(NULL);
1389   //set_scavenge_root_link(NULL); // done by prune_scavenge_root_nmethods
1390   NMethodSweeper::report_state_change(this);
1391 }
1392 
1393 void nmethod::invalidate_osr_method() {
1394   assert(_entry_bci != InvocationEntryBci, "wrong kind of nmethod");
1395   // Remove from list of active nmethods
1396   if (method() != NULL)
1397     method()->method_holder()->remove_osr_nmethod(this);
1398 }
1399 
1400 void nmethod::log_state_change() const {
1401   if (LogCompilation) {
1402     if (xtty != NULL) {
1403       ttyLocker ttyl;  // keep the following output all in one block
1404       if (_state == unloaded) {
1405         xtty->begin_elem("make_unloaded thread='" UINTX_FORMAT "'",
1406                          os::current_thread_id());
1407       } else {
1408         xtty->begin_elem("make_not_entrant thread='" UINTX_FORMAT "'%s",
1409                          os::current_thread_id(),
1410                          (_state == zombie ? " zombie='1'" : ""));
1411       }
1412       log_identity(xtty);
1413       xtty->stamp();
1414       xtty->end_elem();
1415     }
1416   }
1417   if (PrintCompilation && _state != unloaded) {
1418     print_on(tty, _state == zombie ? "made zombie" : "made not entrant");
1419   }
1420 }
1421 
1422 /**
1423  * Common functionality for both make_not_entrant and make_zombie
1424  */
1425 bool nmethod::make_not_entrant_or_zombie(unsigned int state) {
1426   assert(state == zombie || state == not_entrant, "must be zombie or not_entrant");
1427   assert(!is_zombie(), "should not already be a zombie");
1428 
1429   // Make sure neither the nmethod nor the method is flushed in case of a safepoint in code below.
1430   nmethodLocker nml(this);
1431   methodHandle the_method(method());
1432   No_Safepoint_Verifier nsv;
1433 
1434   // during patching, depending on the nmethod state we must notify the GC that
1435   // code has been unloaded, unregistering it. We cannot do this right while
1436   // holding the Patching_lock because we need to use the CodeCache_lock. This
1437   // would be prone to deadlocks.
1438   // This flag is used to remember whether we need to later lock and unregister.
1439   bool nmethod_needs_unregister = false;
1440 
1441   {
1442     // invalidate osr nmethod before acquiring the patching lock since
1443     // they both acquire leaf locks and we don't want a deadlock.
1444     // This logic is equivalent to the logic below for patching the
1445     // verified entry point of regular methods.
1446     if (is_osr_method()) {
1447       // this effectively makes the osr nmethod not entrant
1448       invalidate_osr_method();
1449     }
1450 
1451     // Enter critical section.  Does not block for safepoint.
1452     MutexLockerEx pl(Patching_lock, Mutex::_no_safepoint_check_flag);
1453 
1454     if (_state == state) {
1455       // another thread already performed this transition so nothing
1456       // to do, but return false to indicate this.
1457       return false;
1458     }
1459 
1460     // The caller can be calling the method statically or through an inline
1461     // cache call.
1462     if (!is_osr_method() && !is_not_entrant()) {
1463       NativeJump::patch_verified_entry(entry_point(), verified_entry_point(),
1464                   SharedRuntime::get_handle_wrong_method_stub());
1465     }
1466 
1467     if (is_in_use()) {
1468       // It's a true state change, so mark the method as decompiled.
1469       // Do it only for transition from alive.
1470       inc_decompile_count();
1471     }
1472 
1473     // If the state is becoming a zombie, signal to unregister the nmethod with
1474     // the heap.
1475     // This nmethod may have already been unloaded during a full GC.
1476     if ((state == zombie) && !is_unloaded()) {
1477       nmethod_needs_unregister = true;
1478     }
1479 
1480     // Must happen before state change. Otherwise we have a race condition in
1481     // nmethod::can_not_entrant_be_converted(). I.e., a method can immediately
1482     // transition its state from 'not_entrant' to 'zombie' without having to wait
1483     // for stack scanning.
1484     if (state == not_entrant) {
1485       mark_as_seen_on_stack();
1486       OrderAccess::storestore();
1487     }
1488 
1489     // Change state
1490     _state = state;
1491 
1492     // Log the transition once
1493     log_state_change();
1494 
1495     // Remove nmethod from method.
1496     // We need to check if both the _code and _from_compiled_code_entry_point
1497     // refer to this nmethod because there is a race in setting these two fields
1498     // in Method* as seen in bugid 4947125.
1499     // If the vep() points to the zombie nmethod, the memory for the nmethod
1500     // could be flushed and the compiler and vtable stubs could still call
1501     // through it.
1502     if (method() != NULL && (method()->code() == this ||
1503                              method()->from_compiled_entry() == verified_entry_point())) {
1504       HandleMark hm;
1505       method()->clear_code();
1506     }
1507   } // leave critical region under Patching_lock
1508 
1509   // When the nmethod becomes zombie it is no longer alive so the
1510   // dependencies must be flushed.  nmethods in the not_entrant
1511   // state will be flushed later when the transition to zombie
1512   // happens or they get unloaded.
1513   if (state == zombie) {
1514     {
1515       // Flushing dependecies must be done before any possible
1516       // safepoint can sneak in, otherwise the oops used by the
1517       // dependency logic could have become stale.
1518       MutexLockerEx mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
1519       if (nmethod_needs_unregister) {
1520         Universe::heap()->unregister_nmethod(this);
1521       }
1522       flush_dependencies(NULL);
1523     }
1524 
1525     // zombie only - if a JVMTI agent has enabled the CompiledMethodUnload
1526     // event and it hasn't already been reported for this nmethod then
1527     // report it now. The event may have been reported earilier if the GC
1528     // marked it for unloading). JvmtiDeferredEventQueue support means
1529     // we no longer go to a safepoint here.
1530     post_compiled_method_unload();
1531 
1532 #ifdef ASSERT
1533     // It's no longer safe to access the oops section since zombie
1534     // nmethods aren't scanned for GC.
1535     _oops_are_stale = true;
1536 #endif
1537      // the Method may be reclaimed by class unloading now that the
1538      // nmethod is in zombie state
1539     set_method(NULL);
1540   } else {
1541     assert(state == not_entrant, "other cases may need to be handled differently");
1542   }
1543 #if INCLUDE_JVMCI
1544   if (_jvmci_installed_code != NULL) {
1545     // Break the link between nmethod and InstalledCode such that the nmethod can subsequently be flushed safely.
1546     InstalledCode::set_address(_jvmci_installed_code, 0);
1547   }
1548 #endif
1549 
1550   if (TraceCreateZombies) {
1551     ResourceMark m;
1552     tty->print_cr("nmethod <" INTPTR_FORMAT "> %s code made %s", this, this->method() ? this->method()->name_and_sig_as_C_string() : "null", (state == not_entrant) ? "not entrant" : "zombie");
1553   }
1554 
1555   NMethodSweeper::report_state_change(this);
1556   return true;
1557 }
1558 
1559 void nmethod::flush() {
1560   // Note that there are no valid oops in the nmethod anymore.
1561   assert(is_zombie() || (is_osr_method() && is_unloaded()), "must be a zombie method");
1562   assert(is_marked_for_reclamation() || (is_osr_method() && is_unloaded()), "must be marked for reclamation");
1563 
1564   assert (!is_locked_by_vm(), "locked methods shouldn't be flushed");
1565   assert_locked_or_safepoint(CodeCache_lock);
1566 
1567   // completely deallocate this method
1568   Events::log(JavaThread::current(), "flushing nmethod " INTPTR_FORMAT, this);
1569   if (PrintMethodFlushing) {
1570     tty->print_cr("*flushing nmethod %3d/" INTPTR_FORMAT ". Live blobs:" UINT32_FORMAT "/Free CodeCache:" SIZE_FORMAT "Kb",
1571         _compile_id, this, CodeCache::nof_blobs(), CodeCache::unallocated_capacity(CodeCache::get_code_blob_type(this))/1024);
1572   }
1573 
1574   // We need to deallocate any ExceptionCache data.
1575   // Note that we do not need to grab the nmethod lock for this, it
1576   // better be thread safe if we're disposing of it!
1577   ExceptionCache* ec = exception_cache();
1578   set_exception_cache(NULL);
1579   while(ec != NULL) {
1580     ExceptionCache* next = ec->next();
1581     delete ec;
1582     ec = next;
1583   }
1584 
1585   if (on_scavenge_root_list()) {
1586     CodeCache::drop_scavenge_root_nmethod(this);
1587   }
1588 
1589 #ifdef SHARK
1590   ((SharkCompiler *) compiler())->free_compiled_method(insts_begin());
1591 #endif // SHARK
1592 
1593   ((CodeBlob*)(this))->flush();
1594 
1595   CodeCache::free(this);
1596 }
1597 
1598 //
1599 // Notify all classes this nmethod is dependent on that it is no
1600 // longer dependent. This should only be called in two situations.
1601 // First, when a nmethod transitions to a zombie all dependents need
1602 // to be clear.  Since zombification happens at a safepoint there's no
1603 // synchronization issues.  The second place is a little more tricky.
1604 // During phase 1 of mark sweep class unloading may happen and as a
1605 // result some nmethods may get unloaded.  In this case the flushing
1606 // of dependencies must happen during phase 1 since after GC any
1607 // dependencies in the unloaded nmethod won't be updated, so
1608 // traversing the dependency information in unsafe.  In that case this
1609 // function is called with a non-NULL argument and this function only
1610 // notifies instanceKlasses that are reachable
1611 
1612 void nmethod::flush_dependencies(BoolObjectClosure* is_alive) {
1613   assert_locked_or_safepoint(CodeCache_lock);
1614   assert(Universe::heap()->is_gc_active() == (is_alive != NULL),
1615   "is_alive is non-NULL if and only if we are called during GC");
1616   if (!has_flushed_dependencies()) {
1617     set_has_flushed_dependencies();
1618     for (Dependencies::DepStream deps(this); deps.next(); ) {
1619       if (deps.type() == Dependencies::call_site_target_value) {
1620         // CallSite dependencies are managed on per-CallSite instance basis.
1621         oop call_site = deps.argument_oop(0);
1622         MethodHandles::remove_dependent_nmethod(call_site, this);
1623       } else {
1624         Klass* klass = deps.context_type();
1625         if (klass == NULL) {
1626           continue;  // ignore things like evol_method
1627         }
1628         // During GC the is_alive closure is non-NULL, and is used to
1629         // determine liveness of dependees that need to be updated.
1630         if (is_alive == NULL || klass->is_loader_alive(is_alive)) {
1631           InstanceKlass::cast(klass)->remove_dependent_nmethod(this);
1632         }
1633       }
1634     }
1635   }
1636 }
1637 
1638 
1639 // If this oop is not live, the nmethod can be unloaded.
1640 bool nmethod::can_unload(BoolObjectClosure* is_alive, oop* root, bool unloading_occurred) {
1641   assert(root != NULL, "just checking");
1642   oop obj = *root;
1643   if (obj == NULL || is_alive->do_object_b(obj)) {
1644       return false;
1645   }
1646 
1647   // If ScavengeRootsInCode is true, an nmethod might be unloaded
1648   // simply because one of its constant oops has gone dead.
1649   // No actual classes need to be unloaded in order for this to occur.
1650   assert(unloading_occurred || ScavengeRootsInCode, "Inconsistency in unloading");
1651   make_unloaded(is_alive, obj);
1652   return true;
1653 }
1654 
1655 // ------------------------------------------------------------------
1656 // post_compiled_method_load_event
1657 // new method for install_code() path
1658 // Transfer information from compilation to jvmti
1659 void nmethod::post_compiled_method_load_event() {
1660 
1661   Method* moop = method();
1662   HOTSPOT_COMPILED_METHOD_LOAD(
1663       (char *) moop->klass_name()->bytes(),
1664       moop->klass_name()->utf8_length(),
1665       (char *) moop->name()->bytes(),
1666       moop->name()->utf8_length(),
1667       (char *) moop->signature()->bytes(),
1668       moop->signature()->utf8_length(),
1669       insts_begin(), insts_size());
1670 
1671   if (JvmtiExport::should_post_compiled_method_load() ||
1672       JvmtiExport::should_post_compiled_method_unload()) {
1673     get_and_cache_jmethod_id();
1674   }
1675 
1676   if (JvmtiExport::should_post_compiled_method_load()) {
1677     // Let the Service thread (which is a real Java thread) post the event
1678     MutexLockerEx ml(Service_lock, Mutex::_no_safepoint_check_flag);
1679     JvmtiDeferredEventQueue::enqueue(
1680       JvmtiDeferredEvent::compiled_method_load_event(this));
1681   }
1682 }
1683 
1684 jmethodID nmethod::get_and_cache_jmethod_id() {
1685   if (_jmethod_id == NULL) {
1686     // Cache the jmethod_id since it can no longer be looked up once the
1687     // method itself has been marked for unloading.
1688     _jmethod_id = method()->jmethod_id();
1689   }
1690   return _jmethod_id;
1691 }
1692 
1693 void nmethod::post_compiled_method_unload() {
1694   if (unload_reported()) {
1695     // During unloading we transition to unloaded and then to zombie
1696     // and the unloading is reported during the first transition.
1697     return;
1698   }
1699 
1700   assert(_method != NULL && !is_unloaded(), "just checking");
1701   DTRACE_METHOD_UNLOAD_PROBE(method());
1702 
1703   // If a JVMTI agent has enabled the CompiledMethodUnload event then
1704   // post the event. Sometime later this nmethod will be made a zombie
1705   // by the sweeper but the Method* will not be valid at that point.
1706   // If the _jmethod_id is null then no load event was ever requested
1707   // so don't bother posting the unload.  The main reason for this is
1708   // that the jmethodID is a weak reference to the Method* so if
1709   // it's being unloaded there's no way to look it up since the weak
1710   // ref will have been cleared.
1711   if (_jmethod_id != NULL && JvmtiExport::should_post_compiled_method_unload()) {
1712     assert(!unload_reported(), "already unloaded");
1713     JvmtiDeferredEvent event =
1714       JvmtiDeferredEvent::compiled_method_unload_event(this,
1715           _jmethod_id, insts_begin());
1716     if (SafepointSynchronize::is_at_safepoint()) {
1717       // Don't want to take the queueing lock. Add it as pending and
1718       // it will get enqueued later.
1719       JvmtiDeferredEventQueue::add_pending_event(event);
1720     } else {
1721       MutexLockerEx ml(Service_lock, Mutex::_no_safepoint_check_flag);
1722       JvmtiDeferredEventQueue::enqueue(event);
1723     }
1724   }
1725 
1726   // The JVMTI CompiledMethodUnload event can be enabled or disabled at
1727   // any time. As the nmethod is being unloaded now we mark it has
1728   // having the unload event reported - this will ensure that we don't
1729   // attempt to report the event in the unlikely scenario where the
1730   // event is enabled at the time the nmethod is made a zombie.
1731   set_unload_reported();
1732 }
1733 
1734 void static clean_ic_if_metadata_is_dead(CompiledIC *ic, BoolObjectClosure *is_alive) {
1735   if (ic->is_icholder_call()) {
1736     // The only exception is compiledICHolder oops which may
1737     // yet be marked below. (We check this further below).
1738     CompiledICHolder* cichk_oop = ic->cached_icholder();
1739 
1740     if (cichk_oop->holder_method()->method_holder()->is_loader_alive(is_alive) &&
1741         cichk_oop->holder_klass()->is_loader_alive(is_alive)) {
1742       return;
1743     }
1744   } else {
1745     Metadata* ic_oop = ic->cached_metadata();
1746     if (ic_oop != NULL) {
1747       if (ic_oop->is_klass()) {
1748         if (((Klass*)ic_oop)->is_loader_alive(is_alive)) {
1749           return;
1750         }
1751       } else if (ic_oop->is_method()) {
1752         if (((Method*)ic_oop)->method_holder()->is_loader_alive(is_alive)) {
1753           return;
1754         }
1755       } else {
1756         ShouldNotReachHere();
1757       }
1758     }
1759   }
1760 
1761   ic->set_to_clean();
1762 }
1763 
1764 // This is called at the end of the strong tracing/marking phase of a
1765 // GC to unload an nmethod if it contains otherwise unreachable
1766 // oops.
1767 
1768 void nmethod::do_unloading(BoolObjectClosure* is_alive, bool unloading_occurred) {
1769   // Make sure the oop's ready to receive visitors
1770   assert(!is_zombie() && !is_unloaded(),
1771          "should not call follow on zombie or unloaded nmethod");
1772 
1773   // If the method is not entrant then a JMP is plastered over the
1774   // first few bytes.  If an oop in the old code was there, that oop
1775   // should not get GC'd.  Skip the first few bytes of oops on
1776   // not-entrant methods.
1777   address low_boundary = verified_entry_point();
1778   if (is_not_entrant()) {
1779     low_boundary += NativeJump::instruction_size;
1780     // %%% Note:  On SPARC we patch only a 4-byte trap, not a full NativeJump.
1781     // (See comment above.)
1782   }
1783 
1784   // The RedefineClasses() API can cause the class unloading invariant
1785   // to no longer be true. See jvmtiExport.hpp for details.
1786   // Also, leave a debugging breadcrumb in local flag.
1787   if (JvmtiExport::has_redefined_a_class()) {
1788     // This set of the unloading_occurred flag is done before the
1789     // call to post_compiled_method_unload() so that the unloading
1790     // of this nmethod is reported.
1791     unloading_occurred = true;
1792   }
1793 
1794   // Exception cache
1795   clean_exception_cache(is_alive);
1796 
1797   // If class unloading occurred we first iterate over all inline caches and
1798   // clear ICs where the cached oop is referring to an unloaded klass or method.
1799   // The remaining live cached oops will be traversed in the relocInfo::oop_type
1800   // iteration below.
1801   if (unloading_occurred) {
1802     RelocIterator iter(this, low_boundary);
1803     while(iter.next()) {
1804       if (iter.type() == relocInfo::virtual_call_type) {
1805         CompiledIC *ic = CompiledIC_at(&iter);
1806         clean_ic_if_metadata_is_dead(ic, is_alive);
1807       }
1808     }
1809   }
1810 
1811   // Compiled code
1812   {
1813   RelocIterator iter(this, low_boundary);
1814   while (iter.next()) {
1815     if (iter.type() == relocInfo::oop_type) {
1816       oop_Relocation* r = iter.oop_reloc();
1817       // In this loop, we must only traverse those oops directly embedded in
1818       // the code.  Other oops (oop_index>0) are seen as part of scopes_oops.
1819       assert(1 == (r->oop_is_immediate()) +
1820                   (r->oop_addr() >= oops_begin() && r->oop_addr() < oops_end()),
1821              "oop must be found in exactly one place");
1822       if (r->oop_is_immediate() && r->oop_value() != NULL) {
1823         if (can_unload(is_alive, r->oop_addr(), unloading_occurred)) {
1824           return;
1825         }
1826       }
1827     }
1828   }
1829   }
1830 
1831 
1832   // Scopes
1833   for (oop* p = oops_begin(); p < oops_end(); p++) {
1834     if (*p == Universe::non_oop_word())  continue;  // skip non-oops
1835     if (can_unload(is_alive, p, unloading_occurred)) {
1836       return;
1837     }
1838   }
1839 
1840 #if INCLUDE_JVMCI
1841   // Follow JVMCI method
1842   BarrierSet* bs = Universe::heap()->barrier_set();
1843   if (_jvmci_installed_code != NULL) {
1844     if (_jvmci_installed_code->is_a(HotSpotNmethod::klass()) && HotSpotNmethod::isDefault(_jvmci_installed_code)) {
1845       if (!is_alive->do_object_b(_jvmci_installed_code)) {
1846         bs->write_ref_nmethod_pre(&_jvmci_installed_code, this);
1847         _jvmci_installed_code = NULL;
1848         bs->write_ref_nmethod_post(&_jvmci_installed_code, this);
1849       }
1850     } else {
1851       if (can_unload(is_alive, (oop*)&_jvmci_installed_code, unloading_occurred)) {
1852         return;
1853       }
1854     }
1855   }
1856 
1857   if (_speculation_log != NULL) {
1858     if (!is_alive->do_object_b(_speculation_log)) {
1859       bs->write_ref_nmethod_pre(&_speculation_log, this);
1860       _speculation_log = NULL;
1861       bs->write_ref_nmethod_post(&_speculation_log, this);
1862     }
1863   }
1864 #endif
1865 
1866 
1867   // Ensure that all metadata is still alive
1868   verify_metadata_loaders(low_boundary, is_alive);
1869 }
1870 
1871 template <class CompiledICorStaticCall>
1872 static bool clean_if_nmethod_is_unloaded(CompiledICorStaticCall *ic, address addr, BoolObjectClosure *is_alive, nmethod* from) {
1873   // Ok, to lookup references to zombies here
1874   CodeBlob *cb = CodeCache::find_blob_unsafe(addr);
1875   if (cb != NULL && cb->is_nmethod()) {
1876     nmethod* nm = (nmethod*)cb;
1877 
1878     if (nm->unloading_clock() != nmethod::global_unloading_clock()) {
1879       // The nmethod has not been processed yet.
1880       return true;
1881     }
1882 
1883     // Clean inline caches pointing to both zombie and not_entrant methods
1884     if (!nm->is_in_use() || (nm->method()->code() != nm)) {
1885       ic->set_to_clean();
1886       assert(ic->is_clean(), err_msg("nmethod " PTR_FORMAT "not clean %s", from, from->method()->name_and_sig_as_C_string()));
1887     }
1888   }
1889 
1890   return false;
1891 }
1892 
1893 static bool clean_if_nmethod_is_unloaded(CompiledIC *ic, BoolObjectClosure *is_alive, nmethod* from) {
1894   return clean_if_nmethod_is_unloaded(ic, ic->ic_destination(), is_alive, from);
1895 }
1896 
1897 static bool clean_if_nmethod_is_unloaded(CompiledStaticCall *csc, BoolObjectClosure *is_alive, nmethod* from) {
1898   return clean_if_nmethod_is_unloaded(csc, csc->destination(), is_alive, from);
1899 }
1900 
1901 bool nmethod::unload_if_dead_at(RelocIterator* iter_at_oop, BoolObjectClosure *is_alive, bool unloading_occurred) {
1902   assert(iter_at_oop->type() == relocInfo::oop_type, "Wrong relocation type");
1903 
1904   oop_Relocation* r = iter_at_oop->oop_reloc();
1905   // Traverse those oops directly embedded in the code.
1906   // Other oops (oop_index>0) are seen as part of scopes_oops.
1907   assert(1 == (r->oop_is_immediate()) +
1908          (r->oop_addr() >= oops_begin() && r->oop_addr() < oops_end()),
1909          "oop must be found in exactly one place");
1910   if (r->oop_is_immediate() && r->oop_value() != NULL) {
1911     // Unload this nmethod if the oop is dead.
1912     if (can_unload(is_alive, r->oop_addr(), unloading_occurred)) {
1913       return true;;
1914     }
1915   }
1916 
1917   return false;
1918 }
1919 
1920 
1921 bool nmethod::do_unloading_parallel(BoolObjectClosure* is_alive, bool unloading_occurred) {
1922   ResourceMark rm;
1923 
1924   // Make sure the oop's ready to receive visitors
1925   assert(!is_zombie() && !is_unloaded(),
1926          "should not call follow on zombie or unloaded nmethod");
1927 
1928   // If the method is not entrant then a JMP is plastered over the
1929   // first few bytes.  If an oop in the old code was there, that oop
1930   // should not get GC'd.  Skip the first few bytes of oops on
1931   // not-entrant methods.
1932   address low_boundary = verified_entry_point();
1933   if (is_not_entrant()) {
1934     low_boundary += NativeJump::instruction_size;
1935     // %%% Note:  On SPARC we patch only a 4-byte trap, not a full NativeJump.
1936     // (See comment above.)
1937   }
1938 
1939   // The RedefineClasses() API can cause the class unloading invariant
1940   // to no longer be true. See jvmtiExport.hpp for details.
1941   // Also, leave a debugging breadcrumb in local flag.
1942   if (JvmtiExport::has_redefined_a_class()) {
1943     // This set of the unloading_occurred flag is done before the
1944     // call to post_compiled_method_unload() so that the unloading
1945     // of this nmethod is reported.
1946     unloading_occurred = true;
1947   }
1948 
1949 #if INCLUDE_JVMCI
1950   // Follow JVMCI method
1951   if (_jvmci_installed_code != NULL) {
1952     if (_jvmci_installed_code->is_a(HotSpotNmethod::klass()) && HotSpotNmethod::isDefault(_jvmci_installed_code)) {
1953       if (!is_alive->do_object_b(_jvmci_installed_code)) {
1954         _jvmci_installed_code = NULL;
1955       }
1956     } else {
1957       if (can_unload(is_alive, (oop*)&_jvmci_installed_code, unloading_occurred)) {
1958         return false;
1959       }
1960     }
1961   }
1962 
1963   if (_speculation_log != NULL) {
1964     if (!is_alive->do_object_b(_speculation_log)) {
1965       _speculation_log = NULL;
1966     }
1967   }
1968 #endif
1969 
1970   // Exception cache
1971   clean_exception_cache(is_alive);
1972 
1973   bool is_unloaded = false;
1974   bool postponed = false;
1975 
1976   RelocIterator iter(this, low_boundary);
1977   while(iter.next()) {
1978 
1979     switch (iter.type()) {
1980 
1981     case relocInfo::virtual_call_type:
1982       if (unloading_occurred) {
1983         // If class unloading occurred we first iterate over all inline caches and
1984         // clear ICs where the cached oop is referring to an unloaded klass or method.
1985         clean_ic_if_metadata_is_dead(CompiledIC_at(&iter), is_alive);
1986       }
1987 
1988       postponed |= clean_if_nmethod_is_unloaded(CompiledIC_at(&iter), is_alive, this);
1989       break;
1990 
1991     case relocInfo::opt_virtual_call_type:
1992       postponed |= clean_if_nmethod_is_unloaded(CompiledIC_at(&iter), is_alive, this);
1993       break;
1994 
1995     case relocInfo::static_call_type:
1996       postponed |= clean_if_nmethod_is_unloaded(compiledStaticCall_at(iter.reloc()), is_alive, this);
1997       break;
1998 
1999     case relocInfo::oop_type:
2000       if (!is_unloaded) {
2001         is_unloaded = unload_if_dead_at(&iter, is_alive, unloading_occurred);
2002       }
2003       break;
2004 
2005     case relocInfo::metadata_type:
2006       break; // nothing to do.
2007     }
2008   }
2009 
2010   if (is_unloaded) {
2011     return postponed;
2012   }
2013 
2014   // Scopes
2015   for (oop* p = oops_begin(); p < oops_end(); p++) {
2016     if (*p == Universe::non_oop_word())  continue;  // skip non-oops
2017     if (can_unload(is_alive, p, unloading_occurred)) {
2018       is_unloaded = true;
2019       break;
2020     }
2021   }
2022 
2023   if (is_unloaded) {
2024     return postponed;
2025   }
2026 
2027 #if INCLUDE_JVMCI
2028   // Follow JVMCI method
2029   BarrierSet* bs = Universe::heap()->barrier_set();
2030   if (_jvmci_installed_code != NULL) {
2031     if (_jvmci_installed_code->is_a(HotSpotNmethod::klass()) && HotSpotNmethod::isDefault(_jvmci_installed_code)) {
2032       if (!is_alive->do_object_b(_jvmci_installed_code)) {
2033         bs->write_ref_nmethod_pre(&_jvmci_installed_code, this);
2034         _jvmci_installed_code = NULL;
2035         bs->write_ref_nmethod_post(&_jvmci_installed_code, this);
2036       }
2037     } else {
2038       if (can_unload(is_alive, (oop*)&_jvmci_installed_code, unloading_occurred)) {
2039         is_unloaded = true;
2040       }
2041     }
2042   }
2043 
2044   if (_speculation_log != NULL) {
2045     if (!is_alive->do_object_b(_speculation_log)) {
2046       bs->write_ref_nmethod_pre(&_speculation_log, this);
2047       _speculation_log = NULL;
2048       bs->write_ref_nmethod_post(&_speculation_log, this);
2049     }
2050   }
2051 #endif
2052 
2053   // Ensure that all metadata is still alive
2054   verify_metadata_loaders(low_boundary, is_alive);
2055 
2056   return postponed;
2057 }
2058 
2059 void nmethod::do_unloading_parallel_postponed(BoolObjectClosure* is_alive, bool unloading_occurred) {
2060   ResourceMark rm;
2061 
2062   // Make sure the oop's ready to receive visitors
2063   assert(!is_zombie(),
2064          "should not call follow on zombie nmethod");
2065 
2066   // If the method is not entrant then a JMP is plastered over the
2067   // first few bytes.  If an oop in the old code was there, that oop
2068   // should not get GC'd.  Skip the first few bytes of oops on
2069   // not-entrant methods.
2070   address low_boundary = verified_entry_point();
2071   if (is_not_entrant()) {
2072     low_boundary += NativeJump::instruction_size;
2073     // %%% Note:  On SPARC we patch only a 4-byte trap, not a full NativeJump.
2074     // (See comment above.)
2075   }
2076 
2077   RelocIterator iter(this, low_boundary);
2078   while(iter.next()) {
2079 
2080     switch (iter.type()) {
2081 
2082     case relocInfo::virtual_call_type:
2083       clean_if_nmethod_is_unloaded(CompiledIC_at(&iter), is_alive, this);
2084       break;
2085 
2086     case relocInfo::opt_virtual_call_type:
2087       clean_if_nmethod_is_unloaded(CompiledIC_at(&iter), is_alive, this);
2088       break;
2089 
2090     case relocInfo::static_call_type:
2091       clean_if_nmethod_is_unloaded(compiledStaticCall_at(iter.reloc()), is_alive, this);
2092       break;
2093     }
2094   }
2095 }
2096 
2097 #ifdef ASSERT
2098 
2099 class CheckClass : AllStatic {
2100   static BoolObjectClosure* _is_alive;
2101 
2102   // Check class_loader is alive for this bit of metadata.
2103   static void check_class(Metadata* md) {
2104     Klass* klass = NULL;
2105     if (md->is_klass()) {
2106       klass = ((Klass*)md);
2107     } else if (md->is_method()) {
2108       klass = ((Method*)md)->method_holder();
2109     } else if (md->is_methodData()) {
2110       klass = ((MethodData*)md)->method()->method_holder();
2111     } else {
2112       md->print();
2113       ShouldNotReachHere();
2114     }
2115     assert(klass->is_loader_alive(_is_alive), "must be alive");
2116   }
2117  public:
2118   static void do_check_class(BoolObjectClosure* is_alive, nmethod* nm) {
2119     assert(SafepointSynchronize::is_at_safepoint(), "this is only ok at safepoint");
2120     _is_alive = is_alive;
2121     nm->metadata_do(check_class);
2122   }
2123 };
2124 
2125 // This is called during a safepoint so can use static data
2126 BoolObjectClosure* CheckClass::_is_alive = NULL;
2127 #endif // ASSERT
2128 
2129 
2130 // Processing of oop references should have been sufficient to keep
2131 // all strong references alive.  Any weak references should have been
2132 // cleared as well.  Visit all the metadata and ensure that it's
2133 // really alive.
2134 void nmethod::verify_metadata_loaders(address low_boundary, BoolObjectClosure* is_alive) {
2135 #ifdef ASSERT
2136     RelocIterator iter(this, low_boundary);
2137     while (iter.next()) {
2138     // static_stub_Relocations may have dangling references to
2139     // Method*s so trim them out here.  Otherwise it looks like
2140     // compiled code is maintaining a link to dead metadata.
2141     address static_call_addr = NULL;
2142     if (iter.type() == relocInfo::opt_virtual_call_type) {
2143       CompiledIC* cic = CompiledIC_at(&iter);
2144       if (!cic->is_call_to_interpreted()) {
2145         static_call_addr = iter.addr();
2146       }
2147     } else if (iter.type() == relocInfo::static_call_type) {
2148       CompiledStaticCall* csc = compiledStaticCall_at(iter.reloc());
2149       if (!csc->is_call_to_interpreted()) {
2150         static_call_addr = iter.addr();
2151       }
2152     }
2153     if (static_call_addr != NULL) {
2154       RelocIterator sciter(this, low_boundary);
2155       while (sciter.next()) {
2156         if (sciter.type() == relocInfo::static_stub_type &&
2157             sciter.static_stub_reloc()->static_call() == static_call_addr) {
2158           sciter.static_stub_reloc()->clear_inline_cache();
2159         }
2160       }
2161     }
2162   }
2163   // Check that the metadata embedded in the nmethod is alive
2164   CheckClass::do_check_class(is_alive, this);
2165 #endif
2166 }
2167 
2168 
2169 // Iterate over metadata calling this function.   Used by RedefineClasses
2170 void nmethod::metadata_do(void f(Metadata*)) {
2171   address low_boundary = verified_entry_point();
2172   if (is_not_entrant()) {
2173     low_boundary += NativeJump::instruction_size;
2174     // %%% Note:  On SPARC we patch only a 4-byte trap, not a full NativeJump.
2175     // (See comment above.)
2176   }
2177   {
2178     // Visit all immediate references that are embedded in the instruction stream.
2179     RelocIterator iter(this, low_boundary);
2180     while (iter.next()) {
2181       if (iter.type() == relocInfo::metadata_type ) {
2182         metadata_Relocation* r = iter.metadata_reloc();
2183         // In this metadata, we must only follow those metadatas directly embedded in
2184         // the code.  Other metadatas (oop_index>0) are seen as part of
2185         // the metadata section below.
2186         assert(1 == (r->metadata_is_immediate()) +
2187                (r->metadata_addr() >= metadata_begin() && r->metadata_addr() < metadata_end()),
2188                "metadata must be found in exactly one place");
2189         if (r->metadata_is_immediate() && r->metadata_value() != NULL) {
2190           Metadata* md = r->metadata_value();
2191           if (md != _method) f(md);
2192         }
2193       } else if (iter.type() == relocInfo::virtual_call_type) {
2194         // Check compiledIC holders associated with this nmethod
2195         CompiledIC *ic = CompiledIC_at(&iter);
2196         if (ic->is_icholder_call()) {
2197           CompiledICHolder* cichk = ic->cached_icholder();
2198           f(cichk->holder_method());
2199           f(cichk->holder_klass());
2200         } else {
2201           Metadata* ic_oop = ic->cached_metadata();
2202           if (ic_oop != NULL) {
2203             f(ic_oop);
2204           }
2205         }
2206       }
2207     }
2208   }
2209 
2210   // Visit the metadata section
2211   for (Metadata** p = metadata_begin(); p < metadata_end(); p++) {
2212     if (*p == Universe::non_oop_word() || *p == NULL)  continue;  // skip non-oops
2213     Metadata* md = *p;
2214     f(md);
2215   }
2216 
2217   // Visit metadata not embedded in the other places.
2218   if (_method != NULL) f(_method);
2219 }
2220 
2221 void nmethod::oops_do(OopClosure* f, bool allow_zombie) {
2222   // make sure the oops ready to receive visitors
2223   assert(allow_zombie || !is_zombie(), "should not call follow on zombie nmethod");
2224   assert(!is_unloaded(), "should not call follow on unloaded nmethod");
2225 
2226   // If the method is not entrant or zombie then a JMP is plastered over the
2227   // first few bytes.  If an oop in the old code was there, that oop
2228   // should not get GC'd.  Skip the first few bytes of oops on
2229   // not-entrant methods.
2230   address low_boundary = verified_entry_point();
2231   if (is_not_entrant()) {
2232     low_boundary += NativeJump::instruction_size;
2233     // %%% Note:  On SPARC we patch only a 4-byte trap, not a full NativeJump.
2234     // (See comment above.)
2235   }
2236 
2237 #if INCLUDE_JVMCI
2238   if (_jvmci_installed_code != NULL) {
2239     f->do_oop((oop*) &_jvmci_installed_code);
2240   }
2241   if (_speculation_log != NULL) {
2242     f->do_oop((oop*) &_speculation_log);
2243   }
2244 #endif
2245 
2246   RelocIterator iter(this, low_boundary);
2247 
2248   while (iter.next()) {
2249     if (iter.type() == relocInfo::oop_type ) {
2250       oop_Relocation* r = iter.oop_reloc();
2251       // In this loop, we must only follow those oops directly embedded in
2252       // the code.  Other oops (oop_index>0) are seen as part of scopes_oops.
2253       assert(1 == (r->oop_is_immediate()) +
2254                    (r->oop_addr() >= oops_begin() && r->oop_addr() < oops_end()),
2255              "oop must be found in exactly one place");
2256       if (r->oop_is_immediate() && r->oop_value() != NULL) {
2257         f->do_oop(r->oop_addr());
2258       }
2259     }
2260   }
2261 
2262   // Scopes
2263   // This includes oop constants not inlined in the code stream.
2264   for (oop* p = oops_begin(); p < oops_end(); p++) {
2265     if (*p == Universe::non_oop_word())  continue;  // skip non-oops
2266     f->do_oop(p);
2267   }
2268 }
2269 
2270 #define NMETHOD_SENTINEL ((nmethod*)badAddress)
2271 
2272 nmethod* volatile nmethod::_oops_do_mark_nmethods;
2273 
2274 // An nmethod is "marked" if its _mark_link is set non-null.
2275 // Even if it is the end of the linked list, it will have a non-null link value,
2276 // as long as it is on the list.
2277 // This code must be MP safe, because it is used from parallel GC passes.
2278 bool nmethod::test_set_oops_do_mark() {
2279   assert(nmethod::oops_do_marking_is_active(), "oops_do_marking_prologue must be called");
2280   nmethod* observed_mark_link = _oops_do_mark_link;
2281   if (observed_mark_link == NULL) {
2282     // Claim this nmethod for this thread to mark.
2283     observed_mark_link = (nmethod*)
2284       Atomic::cmpxchg_ptr(NMETHOD_SENTINEL, &_oops_do_mark_link, NULL);
2285     if (observed_mark_link == NULL) {
2286 
2287       // Atomically append this nmethod (now claimed) to the head of the list:
2288       nmethod* observed_mark_nmethods = _oops_do_mark_nmethods;
2289       for (;;) {
2290         nmethod* required_mark_nmethods = observed_mark_nmethods;
2291         _oops_do_mark_link = required_mark_nmethods;
2292         observed_mark_nmethods = (nmethod*)
2293           Atomic::cmpxchg_ptr(this, &_oops_do_mark_nmethods, required_mark_nmethods);
2294         if (observed_mark_nmethods == required_mark_nmethods)
2295           break;
2296       }
2297       // Mark was clear when we first saw this guy.
2298       NOT_PRODUCT(if (TraceScavenge)  print_on(tty, "oops_do, mark"));
2299       return false;
2300     }
2301   }
2302   // On fall through, another racing thread marked this nmethod before we did.
2303   return true;
2304 }
2305 
2306 void nmethod::oops_do_marking_prologue() {
2307   NOT_PRODUCT(if (TraceScavenge)  tty->print_cr("[oops_do_marking_prologue"));
2308   assert(_oops_do_mark_nmethods == NULL, "must not call oops_do_marking_prologue twice in a row");
2309   // We use cmpxchg_ptr instead of regular assignment here because the user
2310   // may fork a bunch of threads, and we need them all to see the same state.
2311   void* observed = Atomic::cmpxchg_ptr(NMETHOD_SENTINEL, &_oops_do_mark_nmethods, NULL);
2312   guarantee(observed == NULL, "no races in this sequential code");
2313 }
2314 
2315 void nmethod::oops_do_marking_epilogue() {
2316   assert(_oops_do_mark_nmethods != NULL, "must not call oops_do_marking_epilogue twice in a row");
2317   nmethod* cur = _oops_do_mark_nmethods;
2318   while (cur != NMETHOD_SENTINEL) {
2319     assert(cur != NULL, "not NULL-terminated");
2320     nmethod* next = cur->_oops_do_mark_link;
2321     cur->_oops_do_mark_link = NULL;
2322     cur->verify_oop_relocations();
2323     NOT_PRODUCT(if (TraceScavenge)  cur->print_on(tty, "oops_do, unmark"));
2324     cur = next;
2325   }
2326   void* required = _oops_do_mark_nmethods;
2327   void* observed = Atomic::cmpxchg_ptr(NULL, &_oops_do_mark_nmethods, required);
2328   guarantee(observed == required, "no races in this sequential code");
2329   NOT_PRODUCT(if (TraceScavenge)  tty->print_cr("oops_do_marking_epilogue]"));
2330 }
2331 
2332 class DetectScavengeRoot: public OopClosure {
2333   bool     _detected_scavenge_root;
2334 public:
2335   DetectScavengeRoot() : _detected_scavenge_root(false)
2336   { NOT_PRODUCT(_print_nm = NULL); }
2337   bool detected_scavenge_root() { return _detected_scavenge_root; }
2338   virtual void do_oop(oop* p) {
2339     if ((*p) != NULL && (*p)->is_scavengable()) {
2340       NOT_PRODUCT(maybe_print(p));
2341       _detected_scavenge_root = true;
2342     }
2343   }
2344   virtual void do_oop(narrowOop* p) { ShouldNotReachHere(); }
2345 
2346 #ifndef PRODUCT
2347   nmethod* _print_nm;
2348   void maybe_print(oop* p) {
2349     if (_print_nm == NULL)  return;
2350     if (!_detected_scavenge_root)  _print_nm->print_on(tty, "new scavenge root");
2351     tty->print_cr("" PTR_FORMAT "[offset=%d] detected scavengable oop " PTR_FORMAT " (found at " PTR_FORMAT ")",
2352                   _print_nm, (int)((intptr_t)p - (intptr_t)_print_nm),
2353                   (void *)(*p), (intptr_t)p);
2354     (*p)->print();
2355   }
2356 #endif //PRODUCT
2357 };
2358 
2359 bool nmethod::detect_scavenge_root_oops() {
2360   DetectScavengeRoot detect_scavenge_root;
2361   NOT_PRODUCT(if (TraceScavenge)  detect_scavenge_root._print_nm = this);
2362   oops_do(&detect_scavenge_root);
2363   return detect_scavenge_root.detected_scavenge_root();
2364 }
2365 
2366 // Method that knows how to preserve outgoing arguments at call. This method must be
2367 // called with a frame corresponding to a Java invoke
2368 void nmethod::preserve_callee_argument_oops(frame fr, const RegisterMap *reg_map, OopClosure* f) {
2369 #ifndef SHARK
2370   if (method() != NULL && !method()->is_native()) {
2371     SimpleScopeDesc ssd(this, fr.pc());
2372     Bytecode_invoke call(ssd.method(), ssd.bci());
2373     bool has_receiver = call.has_receiver();
2374     bool has_appendix = call.has_appendix();
2375     Symbol* signature = call.signature();
2376     fr.oops_compiled_arguments_do(signature, has_receiver, has_appendix, reg_map, f);
2377   }
2378 #endif // !SHARK
2379 }
2380 
2381 inline bool includes(void* p, void* from, void* to) {
2382   return from <= p && p < to;
2383 }
2384 
2385 
2386 void nmethod::copy_scopes_pcs(PcDesc* pcs, int count) {
2387   assert(count >= 2, "must be sentinel values, at least");
2388 
2389 #ifdef ASSERT
2390   // must be sorted and unique; we do a binary search in find_pc_desc()
2391   int prev_offset = pcs[0].pc_offset();
2392   assert(prev_offset == PcDesc::lower_offset_limit,
2393          "must start with a sentinel");
2394   for (int i = 1; i < count; i++) {
2395     int this_offset = pcs[i].pc_offset();
2396     assert(this_offset > prev_offset, "offsets must be sorted");
2397     prev_offset = this_offset;
2398   }
2399   assert(prev_offset == PcDesc::upper_offset_limit,
2400          "must end with a sentinel");
2401 #endif //ASSERT
2402 
2403   // Search for MethodHandle invokes and tag the nmethod.
2404   for (int i = 0; i < count; i++) {
2405     if (pcs[i].is_method_handle_invoke()) {
2406       set_has_method_handle_invokes(true);
2407       break;
2408     }
2409   }
2410   assert(has_method_handle_invokes() == (_deoptimize_mh_offset != -1), "must have deopt mh handler");
2411 
2412   int size = count * sizeof(PcDesc);
2413   assert(scopes_pcs_size() >= size, "oob");
2414   memcpy(scopes_pcs_begin(), pcs, size);
2415 
2416   // Adjust the final sentinel downward.
2417   PcDesc* last_pc = &scopes_pcs_begin()[count-1];
2418   assert(last_pc->pc_offset() == PcDesc::upper_offset_limit, "sanity");
2419   last_pc->set_pc_offset(content_size() + 1);
2420   for (; last_pc + 1 < scopes_pcs_end(); last_pc += 1) {
2421     // Fill any rounding gaps with copies of the last record.
2422     last_pc[1] = last_pc[0];
2423   }
2424   // The following assert could fail if sizeof(PcDesc) is not
2425   // an integral multiple of oopSize (the rounding term).
2426   // If it fails, change the logic to always allocate a multiple
2427   // of sizeof(PcDesc), and fill unused words with copies of *last_pc.
2428   assert(last_pc + 1 == scopes_pcs_end(), "must match exactly");
2429 }
2430 
2431 void nmethod::copy_scopes_data(u_char* buffer, int size) {
2432   assert(scopes_data_size() >= size, "oob");
2433   memcpy(scopes_data_begin(), buffer, size);
2434 }
2435 
2436 // When using JVMCI the address might be off by the size of a call instruction.
2437 bool nmethod::is_deopt_entry(address pc) {
2438   return pc == deopt_handler_begin()
2439 #if INCLUDE_JVMCI
2440     || pc == (deopt_handler_begin() + NativeCall::instruction_size)
2441 #endif
2442     ;
2443 }
2444 
2445 #ifdef ASSERT
2446 static PcDesc* linear_search(nmethod* nm, int pc_offset, bool approximate) {
2447   PcDesc* lower = nm->scopes_pcs_begin();
2448   PcDesc* upper = nm->scopes_pcs_end();
2449   lower += 1; // exclude initial sentinel
2450   PcDesc* res = NULL;
2451   for (PcDesc* p = lower; p < upper; p++) {
2452     NOT_PRODUCT(--pc_nmethod_stats.pc_desc_tests);  // don't count this call to match_desc
2453     if (match_desc(p, pc_offset, approximate)) {
2454       if (res == NULL)
2455         res = p;
2456       else
2457         res = (PcDesc*) badAddress;
2458     }
2459   }
2460   return res;
2461 }
2462 #endif
2463 
2464 
2465 // Finds a PcDesc with real-pc equal to "pc"
2466 PcDesc* nmethod::find_pc_desc_internal(address pc, bool approximate) {
2467   address base_address = code_begin();
2468   if ((pc < base_address) ||
2469       (pc - base_address) >= (ptrdiff_t) PcDesc::upper_offset_limit) {
2470     return NULL;  // PC is wildly out of range
2471   }
2472   int pc_offset = (int) (pc - base_address);
2473 
2474   // Check the PcDesc cache if it contains the desired PcDesc
2475   // (This as an almost 100% hit rate.)
2476   PcDesc* res = _pc_desc_cache.find_pc_desc(pc_offset, approximate);
2477   if (res != NULL) {
2478     assert(res == linear_search(this, pc_offset, approximate), "cache ok");
2479     return res;
2480   }
2481 
2482   // Fallback algorithm: quasi-linear search for the PcDesc
2483   // Find the last pc_offset less than the given offset.
2484   // The successor must be the required match, if there is a match at all.
2485   // (Use a fixed radix to avoid expensive affine pointer arithmetic.)
2486   PcDesc* lower = scopes_pcs_begin();
2487   PcDesc* upper = scopes_pcs_end();
2488   upper -= 1; // exclude final sentinel
2489   if (lower >= upper)  return NULL;  // native method; no PcDescs at all
2490 
2491 #define assert_LU_OK \
2492   /* invariant on lower..upper during the following search: */ \
2493   assert(lower->pc_offset() <  pc_offset, "sanity"); \
2494   assert(upper->pc_offset() >= pc_offset, "sanity")
2495   assert_LU_OK;
2496 
2497   // Use the last successful return as a split point.
2498   PcDesc* mid = _pc_desc_cache.last_pc_desc();
2499   NOT_PRODUCT(++pc_nmethod_stats.pc_desc_searches);
2500   if (mid->pc_offset() < pc_offset) {
2501     lower = mid;
2502   } else {
2503     upper = mid;
2504   }
2505 
2506   // Take giant steps at first (4096, then 256, then 16, then 1)
2507   const int LOG2_RADIX = 4 /*smaller steps in debug mode:*/ debug_only(-1);
2508   const int RADIX = (1 << LOG2_RADIX);
2509   for (int step = (1 << (LOG2_RADIX*3)); step > 1; step >>= LOG2_RADIX) {
2510     while ((mid = lower + step) < upper) {
2511       assert_LU_OK;
2512       NOT_PRODUCT(++pc_nmethod_stats.pc_desc_searches);
2513       if (mid->pc_offset() < pc_offset) {
2514         lower = mid;
2515       } else {
2516         upper = mid;
2517         break;
2518       }
2519     }
2520     assert_LU_OK;
2521   }
2522 
2523   // Sneak up on the value with a linear search of length ~16.
2524   while (true) {
2525     assert_LU_OK;
2526     mid = lower + 1;
2527     NOT_PRODUCT(++pc_nmethod_stats.pc_desc_searches);
2528     if (mid->pc_offset() < pc_offset) {
2529       lower = mid;
2530     } else {
2531       upper = mid;
2532       break;
2533     }
2534   }
2535 #undef assert_LU_OK
2536 
2537   if (match_desc(upper, pc_offset, approximate)) {
2538     assert(upper == linear_search(this, pc_offset, approximate), "search ok");
2539     _pc_desc_cache.add_pc_desc(upper);
2540     return upper;
2541   } else {
2542     assert(NULL == linear_search(this, pc_offset, approximate), "search ok");
2543     return NULL;
2544   }
2545 }
2546 
2547 
2548 void nmethod::check_all_dependencies(DepChange& changes) {
2549   // Checked dependencies are allocated into this ResourceMark
2550   ResourceMark rm;
2551 
2552   // Turn off dependency tracing while actually testing dependencies.
2553   NOT_PRODUCT( FlagSetting fs(TraceDependencies, false) );
2554 
2555   typedef ResourceHashtable<DependencySignature, int, &DependencySignature::hash,
2556                             &DependencySignature::equals, 11027> DepTable;
2557 
2558   DepTable* table = new DepTable();
2559 
2560   // Iterate over live nmethods and check dependencies of all nmethods that are not
2561   // marked for deoptimization. A particular dependency is only checked once.
2562   NMethodIterator iter;
2563   while(iter.next()) {
2564     nmethod* nm = iter.method();
2565     // Only notify for live nmethods
2566     if (nm->is_alive() && !nm->is_marked_for_deoptimization()) {
2567       for (Dependencies::DepStream deps(nm); deps.next(); ) {
2568         // Construct abstraction of a dependency.
2569         DependencySignature* current_sig = new DependencySignature(deps);
2570 
2571         // Determine if dependency is already checked. table->put(...) returns
2572         // 'true' if the dependency is added (i.e., was not in the hashtable).
2573         if (table->put(*current_sig, 1)) {
2574           if (deps.check_dependency() != NULL) {
2575             // Dependency checking failed. Print out information about the failed
2576             // dependency and finally fail with an assert. We can fail here, since
2577             // dependency checking is never done in a product build.
2578             tty->print_cr("Failed dependency:");
2579             changes.print();
2580             nm->print();
2581             nm->print_dependencies();
2582             assert(false, "Should have been marked for deoptimization");
2583           }
2584         }
2585       }
2586     }
2587   }
2588 }
2589 
2590 bool nmethod::check_dependency_on(DepChange& changes) {
2591   // What has happened:
2592   // 1) a new class dependee has been added
2593   // 2) dependee and all its super classes have been marked
2594   bool found_check = false;  // set true if we are upset
2595   for (Dependencies::DepStream deps(this); deps.next(); ) {
2596     // Evaluate only relevant dependencies.
2597     if (deps.spot_check_dependency_at(changes) != NULL) {
2598       found_check = true;
2599       NOT_DEBUG(break);
2600     }
2601   }
2602   return found_check;
2603 }
2604 
2605 bool nmethod::is_evol_dependent_on(Klass* dependee) {
2606   InstanceKlass *dependee_ik = InstanceKlass::cast(dependee);
2607   Array<Method*>* dependee_methods = dependee_ik->methods();
2608   for (Dependencies::DepStream deps(this); deps.next(); ) {
2609     if (deps.type() == Dependencies::evol_method) {
2610       Method* method = deps.method_argument(0);
2611       for (int j = 0; j < dependee_methods->length(); j++) {
2612         if (dependee_methods->at(j) == method) {
2613           // RC_TRACE macro has an embedded ResourceMark
2614           RC_TRACE(0x01000000,
2615             ("Found evol dependency of nmethod %s.%s(%s) compile_id=%d on method %s.%s(%s)",
2616             _method->method_holder()->external_name(),
2617             _method->name()->as_C_string(),
2618             _method->signature()->as_C_string(), compile_id(),
2619             method->method_holder()->external_name(),
2620             method->name()->as_C_string(),
2621             method->signature()->as_C_string()));
2622           if (TraceDependencies || LogCompilation)
2623             deps.log_dependency(dependee);
2624           return true;
2625         }
2626       }
2627     }
2628   }
2629   return false;
2630 }
2631 
2632 // Called from mark_for_deoptimization, when dependee is invalidated.
2633 bool nmethod::is_dependent_on_method(Method* dependee) {
2634   for (Dependencies::DepStream deps(this); deps.next(); ) {
2635     if (deps.type() != Dependencies::evol_method)
2636       continue;
2637     Method* method = deps.method_argument(0);
2638     if (method == dependee) return true;
2639   }
2640   return false;
2641 }
2642 
2643 
2644 bool nmethod::is_patchable_at(address instr_addr) {
2645   assert(insts_contains(instr_addr), "wrong nmethod used");
2646   if (is_zombie()) {
2647     // a zombie may never be patched
2648     return false;
2649   }
2650   return true;
2651 }
2652 
2653 
2654 address nmethod::continuation_for_implicit_exception(address pc) {
2655   // Exception happened outside inline-cache check code => we are inside
2656   // an active nmethod => use cpc to determine a return address
2657   int exception_offset = pc - code_begin();
2658   int cont_offset = ImplicitExceptionTable(this).at( exception_offset );
2659 #ifdef ASSERT
2660   if (cont_offset == 0) {
2661     Thread* thread = ThreadLocalStorage::get_thread_slow();
2662     ResetNoHandleMark rnm; // Might be called from LEAF/QUICK ENTRY
2663     HandleMark hm(thread);
2664     ResourceMark rm(thread);
2665     CodeBlob* cb = CodeCache::find_blob(pc);
2666     assert(cb != NULL && cb == this, "");
2667     tty->print_cr("implicit exception happened at " INTPTR_FORMAT, pc);
2668     print();
2669     method()->print_codes();
2670     print_code();
2671     print_pcs();
2672   }
2673 #endif
2674   if (cont_offset == 0) {
2675     // Let the normal error handling report the exception
2676     return NULL;
2677   }
2678   return code_begin() + cont_offset;
2679 }
2680 
2681 
2682 
2683 void nmethod_init() {
2684   // make sure you didn't forget to adjust the filler fields
2685   assert(sizeof(nmethod) % oopSize == 0, "nmethod size must be multiple of a word");
2686 }
2687 
2688 
2689 //-------------------------------------------------------------------------------------------
2690 
2691 
2692 // QQQ might we make this work from a frame??
2693 nmethodLocker::nmethodLocker(address pc) {
2694   CodeBlob* cb = CodeCache::find_blob(pc);
2695   guarantee(cb != NULL && cb->is_nmethod(), "bad pc for a nmethod found");
2696   _nm = (nmethod*)cb;
2697   lock_nmethod(_nm);
2698 }
2699 
2700 // Only JvmtiDeferredEvent::compiled_method_unload_event()
2701 // should pass zombie_ok == true.
2702 void nmethodLocker::lock_nmethod(nmethod* nm, bool zombie_ok) {
2703   if (nm == NULL)  return;
2704   Atomic::inc(&nm->_lock_count);
2705   assert(zombie_ok || !nm->is_zombie(), "cannot lock a zombie method");
2706 }
2707 
2708 void nmethodLocker::unlock_nmethod(nmethod* nm) {
2709   if (nm == NULL)  return;
2710   Atomic::dec(&nm->_lock_count);
2711   assert(nm->_lock_count >= 0, "unmatched nmethod lock/unlock");
2712 }
2713 
2714 // -----------------------------------------------------------------------------
2715 // nmethod::get_deopt_original_pc
2716 //
2717 // Return the original PC for the given PC if:
2718 // (a) the given PC belongs to a nmethod and
2719 // (b) it is a deopt PC
2720 address nmethod::get_deopt_original_pc(const frame* fr) {
2721   if (fr->cb() == NULL)  return NULL;
2722 
2723   nmethod* nm = fr->cb()->as_nmethod_or_null();
2724   if (nm != NULL && nm->is_deopt_pc(fr->pc()))
2725     return nm->get_original_pc(fr);
2726 
2727   return NULL;
2728 }
2729 
2730 
2731 // -----------------------------------------------------------------------------
2732 // MethodHandle
2733 
2734 bool nmethod::is_method_handle_return(address return_pc) {
2735   if (!has_method_handle_invokes())  return false;
2736   PcDesc* pd = pc_desc_at(return_pc);
2737   if (pd == NULL)
2738     return false;
2739   return pd->is_method_handle_invoke();
2740 }
2741 
2742 
2743 // -----------------------------------------------------------------------------
2744 // Verification
2745 
2746 class VerifyOopsClosure: public OopClosure {
2747   nmethod* _nm;
2748   bool     _ok;
2749 public:
2750   VerifyOopsClosure(nmethod* nm) : _nm(nm), _ok(true) { }
2751   bool ok() { return _ok; }
2752   virtual void do_oop(oop* p) {
2753     if ((*p) == NULL || (*p)->is_oop())  return;
2754     if (_ok) {
2755       _nm->print_nmethod(true);
2756       _ok = false;
2757     }
2758     tty->print_cr("*** non-oop " PTR_FORMAT " found at " PTR_FORMAT " (offset %d)",
2759                   (void *)(*p), (intptr_t)p, (int)((intptr_t)p - (intptr_t)_nm));
2760   }
2761   virtual void do_oop(narrowOop* p) { ShouldNotReachHere(); }
2762 };
2763 
2764 void nmethod::verify() {
2765 
2766   // Hmm. OSR methods can be deopted but not marked as zombie or not_entrant
2767   // seems odd.
2768 
2769   if (is_zombie() || is_not_entrant() || is_unloaded())
2770     return;
2771 
2772   // Make sure all the entry points are correctly aligned for patching.
2773   NativeJump::check_verified_entry_alignment(entry_point(), verified_entry_point());
2774 
2775   // assert(method()->is_oop(), "must be valid");
2776 
2777   ResourceMark rm;
2778 
2779   if (!CodeCache::contains(this)) {
2780     fatal(err_msg("nmethod at " INTPTR_FORMAT " not in zone", this));
2781   }
2782 
2783   if(is_native_method() )
2784     return;
2785 
2786   nmethod* nm = CodeCache::find_nmethod(verified_entry_point());
2787   if (nm != this) {
2788     fatal(err_msg("findNMethod did not find this nmethod (" INTPTR_FORMAT ")",
2789                   this));
2790   }
2791 
2792   for (PcDesc* p = scopes_pcs_begin(); p < scopes_pcs_end(); p++) {
2793     if (! p->verify(this)) {
2794       tty->print_cr("\t\tin nmethod at " INTPTR_FORMAT " (pcs)", this);
2795     }
2796   }
2797 
2798   VerifyOopsClosure voc(this);
2799   oops_do(&voc);
2800   assert(voc.ok(), "embedded oops must be OK");
2801   verify_scavenge_root_oops();
2802 
2803   verify_scopes();
2804 }
2805 
2806 
2807 void nmethod::verify_interrupt_point(address call_site) {
2808   // Verify IC only when nmethod installation is finished.
2809   bool is_installed = (method()->code() == this) // nmethod is in state 'in_use' and installed
2810                       || !this->is_in_use();     // nmethod is installed, but not in 'in_use' state
2811   if (is_installed) {
2812     Thread *cur = Thread::current();
2813     if (CompiledIC_lock->owner() == cur ||
2814         ((cur->is_VM_thread() || cur->is_ConcurrentGC_thread()) &&
2815          SafepointSynchronize::is_at_safepoint())) {
2816       CompiledIC_at(this, call_site);
2817       CHECK_UNHANDLED_OOPS_ONLY(Thread::current()->clear_unhandled_oops());
2818     } else {
2819       MutexLocker ml_verify (CompiledIC_lock);
2820       CompiledIC_at(this, call_site);
2821     }
2822   }
2823 
2824   PcDesc* pd = pc_desc_at(nativeCall_at(call_site)->return_address());
2825   assert(pd != NULL, "PcDesc must exist");
2826   for (ScopeDesc* sd = new ScopeDesc(this, pd->scope_decode_offset(),
2827                                      pd->obj_decode_offset(), pd->should_reexecute(), pd->rethrow_exception(),
2828                                      pd->return_oop());
2829        !sd->is_top(); sd = sd->sender()) {
2830     sd->verify();
2831   }
2832 }
2833 
2834 void nmethod::verify_scopes() {
2835   if( !method() ) return;       // Runtime stubs have no scope
2836   if (method()->is_native()) return; // Ignore stub methods.
2837   // iterate through all interrupt point
2838   // and verify the debug information is valid.
2839   RelocIterator iter((nmethod*)this);
2840   while (iter.next()) {
2841     address stub = NULL;
2842     switch (iter.type()) {
2843       case relocInfo::virtual_call_type:
2844         verify_interrupt_point(iter.addr());
2845         break;
2846       case relocInfo::opt_virtual_call_type:
2847         stub = iter.opt_virtual_call_reloc()->static_stub();
2848         verify_interrupt_point(iter.addr());
2849         break;
2850       case relocInfo::static_call_type:
2851         stub = iter.static_call_reloc()->static_stub();
2852         //verify_interrupt_point(iter.addr());
2853         break;
2854       case relocInfo::runtime_call_type:
2855         address destination = iter.reloc()->value();
2856         // Right now there is no way to find out which entries support
2857         // an interrupt point.  It would be nice if we had this
2858         // information in a table.
2859         break;
2860     }
2861     assert(stub == NULL || stub_contains(stub), "static call stub outside stub section");
2862   }
2863 }
2864 
2865 
2866 // -----------------------------------------------------------------------------
2867 // Non-product code
2868 #ifndef PRODUCT
2869 
2870 class DebugScavengeRoot: public OopClosure {
2871   nmethod* _nm;
2872   bool     _ok;
2873 public:
2874   DebugScavengeRoot(nmethod* nm) : _nm(nm), _ok(true) { }
2875   bool ok() { return _ok; }
2876   virtual void do_oop(oop* p) {
2877     if ((*p) == NULL || !(*p)->is_scavengable())  return;
2878     if (_ok) {
2879       _nm->print_nmethod(true);
2880       _ok = false;
2881     }
2882     tty->print_cr("*** scavengable oop " PTR_FORMAT " found at " PTR_FORMAT " (offset %d)",
2883                   (void *)(*p), (intptr_t)p, (int)((intptr_t)p - (intptr_t)_nm));
2884     (*p)->print();
2885   }
2886   virtual void do_oop(narrowOop* p) { ShouldNotReachHere(); }
2887 };
2888 
2889 void nmethod::verify_scavenge_root_oops() {
2890   if (UseG1GC) {
2891     return;
2892   }
2893 
2894   if (!on_scavenge_root_list()) {
2895     // Actually look inside, to verify the claim that it's clean.
2896     DebugScavengeRoot debug_scavenge_root(this);
2897     oops_do(&debug_scavenge_root);
2898     if (!debug_scavenge_root.ok())
2899       fatal("found an unadvertised bad scavengable oop in the code cache");
2900   }
2901   assert(scavenge_root_not_marked(), "");
2902 }
2903 
2904 #endif // PRODUCT
2905 
2906 // Printing operations
2907 
2908 void nmethod::print() const {
2909   ResourceMark rm;
2910   ttyLocker ttyl;   // keep the following output all in one block
2911 
2912   tty->print("Compiled method ");
2913 
2914   if (is_compiled_by_c1()) {
2915     tty->print("(c1) ");
2916   } else if (is_compiled_by_c2()) {
2917     tty->print("(c2) ");
2918   } else if (is_compiled_by_shark()) {
2919     tty->print("(shark) ");
2920   } else if (is_compiled_by_jvmci()) {
2921     tty->print("(JVMCI) ");
2922   } else {
2923     tty->print("(nm) ");
2924   }
2925 
2926   print_on(tty, NULL);
2927 
2928   if (WizardMode) {
2929     tty->print("((nmethod*) " INTPTR_FORMAT ") ", this);
2930     tty->print(" for method " INTPTR_FORMAT , (address)method());
2931     tty->print(" { ");
2932     if (is_in_use())      tty->print("in_use ");
2933     if (is_not_entrant()) tty->print("not_entrant ");
2934     if (is_zombie())      tty->print("zombie ");
2935     if (is_unloaded())    tty->print("unloaded ");
2936     if (on_scavenge_root_list())  tty->print("scavenge_root ");
2937     tty->print_cr("}:");
2938   }
2939   if (size              () > 0) tty->print_cr(" total in heap  [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
2940                                               (address)this,
2941                                               (address)this + size(),
2942                                               size());
2943   if (relocation_size   () > 0) tty->print_cr(" relocation     [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
2944                                               relocation_begin(),
2945                                               relocation_end(),
2946                                               relocation_size());
2947   if (consts_size       () > 0) tty->print_cr(" constants      [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
2948                                               consts_begin(),
2949                                               consts_end(),
2950                                               consts_size());
2951   if (insts_size        () > 0) tty->print_cr(" main code      [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
2952                                               insts_begin(),
2953                                               insts_end(),
2954                                               insts_size());
2955   if (stub_size         () > 0) tty->print_cr(" stub code      [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
2956                                               stub_begin(),
2957                                               stub_end(),
2958                                               stub_size());
2959   if (oops_size         () > 0) tty->print_cr(" oops           [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
2960                                               oops_begin(),
2961                                               oops_end(),
2962                                               oops_size());
2963   if (metadata_size      () > 0) tty->print_cr(" metadata       [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
2964                                               metadata_begin(),
2965                                               metadata_end(),
2966                                               metadata_size());
2967   if (scopes_data_size  () > 0) tty->print_cr(" scopes data    [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
2968                                               scopes_data_begin(),
2969                                               scopes_data_end(),
2970                                               scopes_data_size());
2971   if (scopes_pcs_size   () > 0) tty->print_cr(" scopes pcs     [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
2972                                               scopes_pcs_begin(),
2973                                               scopes_pcs_end(),
2974                                               scopes_pcs_size());
2975   if (dependencies_size () > 0) tty->print_cr(" dependencies   [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
2976                                               dependencies_begin(),
2977                                               dependencies_end(),
2978                                               dependencies_size());
2979   if (handler_table_size() > 0) tty->print_cr(" handler table  [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
2980                                               handler_table_begin(),
2981                                               handler_table_end(),
2982                                               handler_table_size());
2983   if (nul_chk_table_size() > 0) tty->print_cr(" nul chk table  [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
2984                                               nul_chk_table_begin(),
2985                                               nul_chk_table_end(),
2986                                               nul_chk_table_size());
2987 }
2988 
2989 void nmethod::print_code() {
2990   HandleMark hm;
2991   ResourceMark m;
2992   Disassembler::decode(this);
2993 }
2994 
2995 
2996 #ifndef PRODUCT
2997 
2998 void nmethod::print_scopes() {
2999   // Find the first pc desc for all scopes in the code and print it.
3000   ResourceMark rm;
3001   for (PcDesc* p = scopes_pcs_begin(); p < scopes_pcs_end(); p++) {
3002     if (p->scope_decode_offset() == DebugInformationRecorder::serialized_null)
3003       continue;
3004 
3005     ScopeDesc* sd = scope_desc_at(p->real_pc(this));
3006     while (sd != NULL) {
3007       sd->print_on(tty, p);
3008       sd = sd->sender();
3009     }
3010   }
3011 }
3012 
3013 void nmethod::print_dependencies() {
3014   ResourceMark rm;
3015   ttyLocker ttyl;   // keep the following output all in one block
3016   tty->print_cr("Dependencies:");
3017   for (Dependencies::DepStream deps(this); deps.next(); ) {
3018     deps.print_dependency();
3019     Klass* ctxk = deps.context_type();
3020     if (ctxk != NULL) {
3021       if (ctxk->oop_is_instance() && ((InstanceKlass*)ctxk)->is_dependent_nmethod(this)) {
3022         tty->print_cr("   [nmethod<=klass]%s", ctxk->external_name());
3023       }
3024     }
3025     deps.log_dependency();  // put it into the xml log also
3026   }
3027 }
3028 
3029 
3030 void nmethod::print_relocations() {
3031   ResourceMark m;       // in case methods get printed via the debugger
3032   tty->print_cr("relocations:");
3033   RelocIterator iter(this);
3034   iter.print();
3035   if (UseRelocIndex) {
3036     jint* index_end   = (jint*)relocation_end() - 1;
3037     jint  index_size  = *index_end;
3038     jint* index_start = (jint*)( (address)index_end - index_size );
3039     tty->print_cr("    index @" INTPTR_FORMAT ": index_size=%d", index_start, index_size);
3040     if (index_size > 0) {
3041       jint* ip;
3042       for (ip = index_start; ip+2 <= index_end; ip += 2)
3043         tty->print_cr("  (%d %d) addr=" INTPTR_FORMAT " @" INTPTR_FORMAT,
3044                       ip[0],
3045                       ip[1],
3046                       header_end()+ip[0],
3047                       relocation_begin()-1+ip[1]);
3048       for (; ip < index_end; ip++)
3049         tty->print_cr("  (%d ?)", ip[0]);
3050       tty->print_cr("          @" INTPTR_FORMAT ": index_size=%d", ip, *ip);
3051       ip++;
3052       tty->print_cr("reloc_end @" INTPTR_FORMAT ":", ip);
3053     }
3054   }
3055 }
3056 
3057 
3058 void nmethod::print_pcs() {
3059   ResourceMark m;       // in case methods get printed via debugger
3060   tty->print_cr("pc-bytecode offsets:");
3061   for (PcDesc* p = scopes_pcs_begin(); p < scopes_pcs_end(); p++) {
3062     p->print(this);
3063   }
3064 }
3065 
3066 #endif // PRODUCT
3067 
3068 const char* nmethod::reloc_string_for(u_char* begin, u_char* end) {
3069   RelocIterator iter(this, begin, end);
3070   bool have_one = false;
3071   while (iter.next()) {
3072     have_one = true;
3073     switch (iter.type()) {
3074         case relocInfo::none:                  return "no_reloc";
3075         case relocInfo::oop_type: {
3076           stringStream st;
3077           oop_Relocation* r = iter.oop_reloc();
3078           oop obj = r->oop_value();
3079           st.print("oop(");
3080           if (obj == NULL) st.print("NULL");
3081           else obj->print_value_on(&st);
3082           st.print(")");
3083           return st.as_string();
3084         }
3085         case relocInfo::metadata_type: {
3086           stringStream st;
3087           metadata_Relocation* r = iter.metadata_reloc();
3088           Metadata* obj = r->metadata_value();
3089           st.print("metadata(");
3090           if (obj == NULL) st.print("NULL");
3091           else obj->print_value_on(&st);
3092           st.print(")");
3093           return st.as_string();
3094         }
3095         case relocInfo::runtime_call_type: {
3096           stringStream st;
3097           st.print("runtime_call");
3098           runtime_call_Relocation* r = iter.runtime_call_reloc();
3099           address dest = r->destination();
3100           CodeBlob* cb = CodeCache::find_blob(dest);
3101           if (cb != NULL) {
3102             st.print(" %s", cb->name());
3103           }
3104           return st.as_string();
3105         }
3106         case relocInfo::virtual_call_type:     return "virtual_call";
3107         case relocInfo::opt_virtual_call_type: return "optimized virtual_call";
3108         case relocInfo::static_call_type:      return "static_call";
3109         case relocInfo::static_stub_type:      return "static_stub";
3110         case relocInfo::external_word_type:    return "external_word";
3111         case relocInfo::internal_word_type:    return "internal_word";
3112         case relocInfo::section_word_type:     return "section_word";
3113         case relocInfo::poll_type:             return "poll";
3114         case relocInfo::poll_return_type:      return "poll_return";
3115         case relocInfo::type_mask:             return "type_bit_mask";
3116     }
3117   }
3118   return have_one ? "other" : NULL;
3119 }
3120 
3121 // Return a the last scope in (begin..end]
3122 ScopeDesc* nmethod::scope_desc_in(address begin, address end) {
3123   PcDesc* p = pc_desc_near(begin+1);
3124   if (p != NULL && p->real_pc(this) <= end) {
3125     return new ScopeDesc(this, p->scope_decode_offset(),
3126                          p->obj_decode_offset(), p->should_reexecute(), p->rethrow_exception(),
3127                          p->return_oop());
3128   }
3129   return NULL;
3130 }
3131 
3132 void nmethod::print_nmethod_labels(outputStream* stream, address block_begin) const {
3133   if (block_begin == entry_point())             stream->print_cr("[Entry Point]");
3134   if (block_begin == verified_entry_point())    stream->print_cr("[Verified Entry Point]");
3135   if (JVMCI_ONLY(_exception_offset >= 0 &&) block_begin == exception_begin())         stream->print_cr("[Exception Handler]");
3136   if (block_begin == stub_begin())              stream->print_cr("[Stub Code]");
3137   if (JVMCI_ONLY(_deoptimize_offset >= 0 &&) block_begin == deopt_handler_begin())     stream->print_cr("[Deopt Handler Code]");
3138 
3139   if (has_method_handle_invokes())
3140     if (block_begin == deopt_mh_handler_begin())  stream->print_cr("[Deopt MH Handler Code]");
3141 
3142   if (block_begin == consts_begin())            stream->print_cr("[Constants]");
3143 
3144   if (block_begin == entry_point()) {
3145     methodHandle m = method();
3146     if (m.not_null()) {
3147       stream->print("  # ");
3148       m->print_value_on(stream);
3149       stream->cr();
3150     }
3151     if (m.not_null() && !is_osr_method()) {
3152       ResourceMark rm;
3153       int sizeargs = m->size_of_parameters();
3154       BasicType* sig_bt = NEW_RESOURCE_ARRAY(BasicType, sizeargs);
3155       VMRegPair* regs   = NEW_RESOURCE_ARRAY(VMRegPair, sizeargs);
3156       {
3157         int sig_index = 0;
3158         if (!m->is_static())
3159           sig_bt[sig_index++] = T_OBJECT; // 'this'
3160         for (SignatureStream ss(m->signature()); !ss.at_return_type(); ss.next()) {
3161           BasicType t = ss.type();
3162           sig_bt[sig_index++] = t;
3163           if (type2size[t] == 2) {
3164             sig_bt[sig_index++] = T_VOID;
3165           } else {
3166             assert(type2size[t] == 1, "size is 1 or 2");
3167           }
3168         }
3169         assert(sig_index == sizeargs, "");
3170       }
3171       const char* spname = "sp"; // make arch-specific?
3172       intptr_t out_preserve = SharedRuntime::java_calling_convention(sig_bt, regs, sizeargs, false);
3173       int stack_slot_offset = this->frame_size() * wordSize;
3174       int tab1 = 14, tab2 = 24;
3175       int sig_index = 0;
3176       int arg_index = (m->is_static() ? 0 : -1);
3177       bool did_old_sp = false;
3178       for (SignatureStream ss(m->signature()); !ss.at_return_type(); ) {
3179         bool at_this = (arg_index == -1);
3180         bool at_old_sp = false;
3181         BasicType t = (at_this ? T_OBJECT : ss.type());
3182         assert(t == sig_bt[sig_index], "sigs in sync");
3183         if (at_this)
3184           stream->print("  # this: ");
3185         else
3186           stream->print("  # parm%d: ", arg_index);
3187         stream->move_to(tab1);
3188         VMReg fst = regs[sig_index].first();
3189         VMReg snd = regs[sig_index].second();
3190         if (fst->is_reg()) {
3191           stream->print("%s", fst->name());
3192           if (snd->is_valid())  {
3193             stream->print(":%s", snd->name());
3194           }
3195         } else if (fst->is_stack()) {
3196           int offset = fst->reg2stack() * VMRegImpl::stack_slot_size + stack_slot_offset;
3197           if (offset == stack_slot_offset)  at_old_sp = true;
3198           stream->print("[%s+0x%x]", spname, offset);
3199         } else {
3200           stream->print("reg%d:%d??", (int)(intptr_t)fst, (int)(intptr_t)snd);
3201         }
3202         stream->print(" ");
3203         stream->move_to(tab2);
3204         stream->print("= ");
3205         if (at_this) {
3206           m->method_holder()->print_value_on(stream);
3207         } else {
3208           bool did_name = false;
3209           if (!at_this && ss.is_object()) {
3210             Symbol* name = ss.as_symbol_or_null();
3211             if (name != NULL) {
3212               name->print_value_on(stream);
3213               did_name = true;
3214             }
3215           }
3216           if (!did_name)
3217             stream->print("%s", type2name(t));
3218         }
3219         if (at_old_sp) {
3220           stream->print("  (%s of caller)", spname);
3221           did_old_sp = true;
3222         }
3223         stream->cr();
3224         sig_index += type2size[t];
3225         arg_index += 1;
3226         if (!at_this)  ss.next();
3227       }
3228       if (!did_old_sp) {
3229         stream->print("  # ");
3230         stream->move_to(tab1);
3231         stream->print("[%s+0x%x]", spname, stack_slot_offset);
3232         stream->print("  (%s of caller)", spname);
3233         stream->cr();
3234       }
3235     }
3236   }
3237 }
3238 
3239 void nmethod::print_code_comment_on(outputStream* st, int column, u_char* begin, u_char* end) {
3240   // First, find an oopmap in (begin, end].
3241   // We use the odd half-closed interval so that oop maps and scope descs
3242   // which are tied to the byte after a call are printed with the call itself.
3243   address base = code_begin();
3244   ImmutableOopMapSet* oms = oop_maps();
3245   if (oms != NULL) {
3246     for (int i = 0, imax = oms->count(); i < imax; i++) {
3247       const ImmutableOopMapPair* pair = oms->pair_at(i);
3248       const ImmutableOopMap* om = pair->get_from(oms);
3249       address pc = base + pair->pc_offset();
3250       if (pc > begin) {
3251         if (pc <= end) {
3252           st->move_to(column);
3253           st->print("; ");
3254           om->print_on(st);
3255         }
3256         break;
3257       }
3258     }
3259   }
3260 
3261   // Print any debug info present at this pc.
3262   ScopeDesc* sd  = scope_desc_in(begin, end);
3263   if (sd != NULL) {
3264     st->move_to(column);
3265     if (sd->bci() == SynchronizationEntryBCI) {
3266       st->print(";*synchronization entry");
3267     } else {
3268       if (sd->method() == NULL) {
3269         st->print("method is NULL");
3270       } else if (sd->method()->is_native()) {
3271         st->print("method is native");
3272       } else {
3273         Bytecodes::Code bc = sd->method()->java_code_at(sd->bci());
3274         st->print(";*%s", Bytecodes::name(bc));
3275         switch (bc) {
3276         case Bytecodes::_invokevirtual:
3277         case Bytecodes::_invokespecial:
3278         case Bytecodes::_invokestatic:
3279         case Bytecodes::_invokeinterface:
3280           {
3281             Bytecode_invoke invoke(sd->method(), sd->bci());
3282             st->print(" ");
3283             if (invoke.name() != NULL)
3284               invoke.name()->print_symbol_on(st);
3285             else
3286               st->print("<UNKNOWN>");
3287             break;
3288           }
3289         case Bytecodes::_getfield:
3290         case Bytecodes::_putfield:
3291         case Bytecodes::_getstatic:
3292         case Bytecodes::_putstatic:
3293           {
3294             Bytecode_field field(sd->method(), sd->bci());
3295             st->print(" ");
3296             if (field.name() != NULL)
3297               field.name()->print_symbol_on(st);
3298             else
3299               st->print("<UNKNOWN>");
3300           }
3301         }
3302       }
3303       st->print(" {reexecute=%d rethrow=%d return_oop=%d}", sd->should_reexecute(), sd->rethrow_exception(), sd->return_oop());
3304     }
3305 
3306     // Print all scopes
3307     for (;sd != NULL; sd = sd->sender()) {
3308       st->move_to(column);
3309       st->print("; -");
3310       if (sd->method() == NULL) {
3311         st->print("method is NULL");
3312       } else {
3313         sd->method()->print_short_name(st);
3314       }
3315       int lineno = sd->method()->line_number_from_bci(sd->bci());
3316       if (lineno != -1) {
3317         st->print("@%d (line %d)", sd->bci(), lineno);
3318       } else {
3319         st->print("@%d", sd->bci());
3320       }
3321       st->cr();
3322     }
3323   }
3324 
3325   // Print relocation information
3326   const char* str = reloc_string_for(begin, end);
3327   if (str != NULL) {
3328     if (sd != NULL) st->cr();
3329     st->move_to(column);
3330     st->print(";   {%s}", str);
3331   }
3332   int cont_offset = ImplicitExceptionTable(this).at(begin - code_begin());
3333   if (cont_offset != 0) {
3334     st->move_to(column);
3335     st->print("; implicit exception: dispatches to " INTPTR_FORMAT, code_begin() + cont_offset);
3336   }
3337 
3338 }
3339 
3340 #ifndef PRODUCT
3341 
3342 void nmethod::print_value_on(outputStream* st) const {
3343   st->print("nmethod");
3344   print_on(st, NULL);
3345 }
3346 
3347 void nmethod::print_calls(outputStream* st) {
3348   RelocIterator iter(this);
3349   while (iter.next()) {
3350     switch (iter.type()) {
3351     case relocInfo::virtual_call_type:
3352     case relocInfo::opt_virtual_call_type: {
3353       VerifyMutexLocker mc(CompiledIC_lock);
3354       CompiledIC_at(&iter)->print();
3355       break;
3356     }
3357     case relocInfo::static_call_type:
3358       st->print_cr("Static call at " INTPTR_FORMAT, iter.reloc()->addr());
3359       compiledStaticCall_at(iter.reloc())->print();
3360       break;
3361     }
3362   }
3363 }
3364 
3365 void nmethod::print_handler_table() {
3366   ExceptionHandlerTable(this).print();
3367 }
3368 
3369 void nmethod::print_nul_chk_table() {
3370   ImplicitExceptionTable(this).print(code_begin());
3371 }
3372 
3373 void nmethod::print_statistics() {
3374   ttyLocker ttyl;
3375   if (xtty != NULL)  xtty->head("statistics type='nmethod'");
3376   native_nmethod_stats.print_native_nmethod_stats();
3377 #ifdef COMPILER1
3378   c1_java_nmethod_stats.print_nmethod_stats("C1");
3379 #endif
3380 #ifdef COMPILER2
3381   c2_java_nmethod_stats.print_nmethod_stats("C2");
3382 #endif
3383 #if INCLUDE_JVMCI
3384   jvmci_java_nmethod_stats.print_nmethod_stats("JVMCI");
3385 #endif
3386 #ifdef SHARK
3387   shark_java_nmethod_stats.print_nmethod_stats("Shark");
3388 #endif
3389   unknown_java_nmethod_stats.print_nmethod_stats("Unknown");
3390   DebugInformationRecorder::print_statistics();
3391 #ifndef PRODUCT
3392   pc_nmethod_stats.print_pc_stats();
3393 #endif
3394   Dependencies::print_statistics();
3395   if (xtty != NULL)  xtty->tail("statistics");
3396 }
3397 
3398 #endif // !PRODUCT
3399 
3400 #if INCLUDE_JVMCI
3401 char* nmethod::jvmci_installed_code_name(char* buf, size_t buflen) {
3402   if (!this->is_compiled_by_jvmci()) {
3403     return NULL;
3404   }
3405   oop installedCode = this->jvmci_installed_code();
3406   if (installedCode != NULL) {
3407     oop installedCodeName = NULL;
3408     if (installedCode->is_a(InstalledCode::klass())) {
3409       installedCodeName = InstalledCode::name(installedCode);
3410     }
3411     if (installedCodeName != NULL) {
3412       return java_lang_String::as_utf8_string(installedCodeName, buf, (int)buflen);
3413     } else {
3414       jio_snprintf(buf, buflen, "null");
3415       return buf;
3416     }
3417   }
3418   jio_snprintf(buf, buflen, "noInstalledCode");
3419   return buf;
3420 }
3421 #endif