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