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