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