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   NMethodSweeper::report_state_change(this);
1385 }
1386 
1387 void nmethod::invalidate_osr_method() {
1388   assert(_entry_bci != InvocationEntryBci, "wrong kind of nmethod");
1389   // Remove from list of active nmethods
1390   if (method() != NULL)
1391     method()->method_holder()->remove_osr_nmethod(this);
1392 }
1393 
1394 void nmethod::log_state_change() const {
1395   if (LogCompilation) {
1396     if (xtty != NULL) {
1397       ttyLocker ttyl;  // keep the following output all in one block
1398       if (_state == unloaded) {
1399         xtty->begin_elem("make_unloaded thread='" UINTX_FORMAT "'",
1400                          os::current_thread_id());
1401       } else {
1402         xtty->begin_elem("make_not_entrant thread='" UINTX_FORMAT "'%s",
1403                          os::current_thread_id(),
1404                          (_state == zombie ? " zombie='1'" : ""));
1405       }
1406       log_identity(xtty);
1407       xtty->stamp();
1408       xtty->end_elem();
1409     }
1410   }
1411   if (PrintCompilation && _state != unloaded) {
1412     print_on(tty, _state == zombie ? "made zombie" : "made not entrant");
1413   }
1414 }
1415 
1416 /**
1417  * Common functionality for both make_not_entrant and make_zombie
1418  */
1419 bool nmethod::make_not_entrant_or_zombie(unsigned int state) {
1420   assert(state == zombie || state == not_entrant, "must be zombie or not_entrant");
1421   assert(!is_zombie(), "should not already be a zombie");
1422 
1423   // Make sure neither the nmethod nor the method is flushed in case of a safepoint in code below.
1424   nmethodLocker nml(this);
1425   methodHandle the_method(method());
1426   NoSafepointVerifier nsv;
1427 
1428   // during patching, depending on the nmethod state we must notify the GC that
1429   // code has been unloaded, unregistering it. We cannot do this right while
1430   // holding the Patching_lock because we need to use the CodeCache_lock. This
1431   // would be prone to deadlocks.
1432   // This flag is used to remember whether we need to later lock and unregister.
1433   bool nmethod_needs_unregister = false;
1434 
1435   {
1436     // invalidate osr nmethod before acquiring the patching lock since
1437     // they both acquire leaf locks and we don't want a deadlock.
1438     // This logic is equivalent to the logic below for patching the
1439     // verified entry point of regular methods.
1440     if (is_osr_method()) {
1441       // this effectively makes the osr nmethod not entrant
1442       invalidate_osr_method();
1443     }
1444 
1445     // Enter critical section.  Does not block for safepoint.
1446     MutexLockerEx pl(Patching_lock, Mutex::_no_safepoint_check_flag);
1447 
1448     if (_state == state) {
1449       // another thread already performed this transition so nothing
1450       // to do, but return false to indicate this.
1451       return false;
1452     }
1453 
1454     // The caller can be calling the method statically or through an inline
1455     // cache call.
1456     if (!is_osr_method() && !is_not_entrant()) {
1457       NativeJump::patch_verified_entry(entry_point(), verified_entry_point(),
1458                   SharedRuntime::get_handle_wrong_method_stub());
1459     }
1460 
1461     if (is_in_use() && update_recompile_counts()) {
1462       // It's a true state change, so mark the method as decompiled.
1463       // Do it only for transition from alive.
1464       inc_decompile_count();
1465     }
1466 
1467     // If the state is becoming a zombie, signal to unregister the nmethod with
1468     // the heap.
1469     // This nmethod may have already been unloaded during a full GC.
1470     if ((state == zombie) && !is_unloaded()) {
1471       nmethod_needs_unregister = true;
1472     }
1473 
1474     // Must happen before state change. Otherwise we have a race condition in
1475     // nmethod::can_not_entrant_be_converted(). I.e., a method can immediately
1476     // transition its state from 'not_entrant' to 'zombie' without having to wait
1477     // for stack scanning.
1478     if (state == not_entrant) {
1479       mark_as_seen_on_stack();
1480       OrderAccess::storestore();
1481     }
1482 
1483     // Change state
1484     _state = state;
1485 
1486     // Log the transition once
1487     log_state_change();
1488 
1489     // Invalidate while holding the patching lock
1490     JVMCI_ONLY(maybe_invalidate_installed_code());
1491 
1492     // Remove nmethod from method.
1493     // We need to check if both the _code and _from_compiled_code_entry_point
1494     // refer to this nmethod because there is a race in setting these two fields
1495     // in Method* as seen in bugid 4947125.
1496     // If the vep() points to the zombie nmethod, the memory for the nmethod
1497     // could be flushed and the compiler and vtable stubs could still call
1498     // through it.
1499     if (method() != NULL && (method()->code() == this ||
1500                              method()->from_compiled_entry() == verified_entry_point())) {
1501       HandleMark hm;
1502       method()->clear_code();
1503     }
1504   } // leave critical region under Patching_lock
1505 
1506   // When the nmethod becomes zombie it is no longer alive so the
1507   // dependencies must be flushed.  nmethods in the not_entrant
1508   // state will be flushed later when the transition to zombie
1509   // happens or they get unloaded.
1510   if (state == zombie) {
1511     {
1512       // Flushing dependecies must be done before any possible
1513       // safepoint can sneak in, otherwise the oops used by the
1514       // dependency logic could have become stale.
1515       MutexLockerEx mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
1516       if (nmethod_needs_unregister) {
1517         Universe::heap()->unregister_nmethod(this);
1518 #ifdef JVMCI
1519         _jvmci_installed_code = NULL;
1520         _speculation_log = NULL;
1521 #endif
1522       }
1523       flush_dependencies(NULL);
1524     }
1525 
1526     // zombie only - if a JVMTI agent has enabled the CompiledMethodUnload
1527     // event and it hasn't already been reported for this nmethod then
1528     // report it now. The event may have been reported earilier if the GC
1529     // marked it for unloading). JvmtiDeferredEventQueue support means
1530     // we no longer go to a safepoint here.
1531     post_compiled_method_unload();
1532 
1533 #ifdef ASSERT
1534     // It's no longer safe to access the oops section since zombie
1535     // nmethods aren't scanned for GC.
1536     _oops_are_stale = true;
1537 #endif
1538      // the Method may be reclaimed by class unloading now that the
1539      // nmethod is in zombie state
1540     set_method(NULL);
1541   } else {
1542     assert(state == not_entrant, "other cases may need to be handled differently");
1543   }
1544 
1545   if (TraceCreateZombies) {
1546     ResourceMark m;
1547     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");
1548   }
1549 
1550   NMethodSweeper::report_state_change(this);
1551   return true;
1552 }
1553 
1554 void nmethod::flush() {
1555   // Note that there are no valid oops in the nmethod anymore.
1556   assert(is_zombie() || (is_osr_method() && is_unloaded()), "must be a zombie method");
1557   assert(is_marked_for_reclamation() || (is_osr_method() && is_unloaded()), "must be marked for reclamation");
1558 
1559   assert (!is_locked_by_vm(), "locked methods shouldn't be flushed");
1560   assert_locked_or_safepoint(CodeCache_lock);
1561 
1562   // completely deallocate this method
1563   Events::log(JavaThread::current(), "flushing nmethod " INTPTR_FORMAT, p2i(this));
1564   if (PrintMethodFlushing) {
1565     tty->print_cr("*flushing nmethod %3d/" INTPTR_FORMAT ". Live blobs:" UINT32_FORMAT
1566                   "/Free CodeCache:" SIZE_FORMAT "Kb",
1567                   _compile_id, p2i(this), CodeCache::blob_count(),
1568                   CodeCache::unallocated_capacity(CodeCache::get_code_blob_type(this))/1024);
1569   }
1570 
1571   // We need to deallocate any ExceptionCache data.
1572   // Note that we do not need to grab the nmethod lock for this, it
1573   // better be thread safe if we're disposing of it!
1574   ExceptionCache* ec = exception_cache();
1575   set_exception_cache(NULL);
1576   while(ec != NULL) {
1577     ExceptionCache* next = ec->next();
1578     delete ec;
1579     ec = next;
1580   }
1581 
1582   if (on_scavenge_root_list()) {
1583     CodeCache::drop_scavenge_root_nmethod(this);
1584   }
1585 
1586 #ifdef SHARK
1587   ((SharkCompiler *) compiler())->free_compiled_method(insts_begin());
1588 #endif // SHARK
1589 
1590   ((CodeBlob*)(this))->flush();
1591 
1592   CodeCache::free(this);
1593 }
1594 
1595 //
1596 // Notify all classes this nmethod is dependent on that it is no
1597 // longer dependent. This should only be called in two situations.
1598 // First, when a nmethod transitions to a zombie all dependents need
1599 // to be clear.  Since zombification happens at a safepoint there's no
1600 // synchronization issues.  The second place is a little more tricky.
1601 // During phase 1 of mark sweep class unloading may happen and as a
1602 // result some nmethods may get unloaded.  In this case the flushing
1603 // of dependencies must happen during phase 1 since after GC any
1604 // dependencies in the unloaded nmethod won't be updated, so
1605 // traversing the dependency information in unsafe.  In that case this
1606 // function is called with a non-NULL argument and this function only
1607 // notifies instanceKlasses that are reachable
1608 
1609 void nmethod::flush_dependencies(BoolObjectClosure* is_alive) {
1610   assert_locked_or_safepoint(CodeCache_lock);
1611   assert(Universe::heap()->is_gc_active() == (is_alive != NULL),
1612   "is_alive is non-NULL if and only if we are called during GC");
1613   if (!has_flushed_dependencies()) {
1614     set_has_flushed_dependencies();
1615     for (Dependencies::DepStream deps(this); deps.next(); ) {
1616       if (deps.type() == Dependencies::call_site_target_value) {
1617         // CallSite dependencies are managed on per-CallSite instance basis.
1618         oop call_site = deps.argument_oop(0);
1619         MethodHandles::remove_dependent_nmethod(call_site, this);
1620       } else {
1621         Klass* klass = deps.context_type();
1622         if (klass == NULL) {
1623           continue;  // ignore things like evol_method
1624         }
1625         // During GC the is_alive closure is non-NULL, and is used to
1626         // determine liveness of dependees that need to be updated.
1627         if (is_alive == NULL || klass->is_loader_alive(is_alive)) {
1628           // The GC defers deletion of this entry, since there might be multiple threads
1629           // iterating over the _dependencies graph. Other call paths are single-threaded
1630           // and may delete it immediately.
1631           bool delete_immediately = is_alive == NULL;
1632           InstanceKlass::cast(klass)->remove_dependent_nmethod(this, delete_immediately);
1633         }
1634       }
1635     }
1636   }
1637 }
1638 
1639 
1640 // If this oop is not live, the nmethod can be unloaded.
1641 bool nmethod::can_unload(BoolObjectClosure* is_alive, oop* root, bool unloading_occurred) {
1642   assert(root != NULL, "just checking");
1643   oop obj = *root;
1644   if (obj == NULL || is_alive->do_object_b(obj)) {
1645       return false;
1646   }
1647 
1648   // If ScavengeRootsInCode is true, an nmethod might be unloaded
1649   // simply because one of its constant oops has gone dead.
1650   // No actual classes need to be unloaded in order for this to occur.
1651   assert(unloading_occurred || ScavengeRootsInCode, "Inconsistency in unloading");
1652   make_unloaded(is_alive, obj);
1653   return true;
1654 }
1655 
1656 // ------------------------------------------------------------------
1657 // post_compiled_method_load_event
1658 // new method for install_code() path
1659 // Transfer information from compilation to jvmti
1660 void nmethod::post_compiled_method_load_event() {
1661 
1662   Method* moop = method();
1663   HOTSPOT_COMPILED_METHOD_LOAD(
1664       (char *) moop->klass_name()->bytes(),
1665       moop->klass_name()->utf8_length(),
1666       (char *) moop->name()->bytes(),
1667       moop->name()->utf8_length(),
1668       (char *) moop->signature()->bytes(),
1669       moop->signature()->utf8_length(),
1670       insts_begin(), insts_size());
1671 
1672   if (JvmtiExport::should_post_compiled_method_load() ||
1673       JvmtiExport::should_post_compiled_method_unload()) {
1674     get_and_cache_jmethod_id();
1675   }
1676 
1677   if (JvmtiExport::should_post_compiled_method_load()) {
1678     // Let the Service thread (which is a real Java thread) post the event
1679     MutexLockerEx ml(Service_lock, Mutex::_no_safepoint_check_flag);
1680     JvmtiDeferredEventQueue::enqueue(
1681       JvmtiDeferredEvent::compiled_method_load_event(this));
1682   }
1683 }
1684 
1685 jmethodID nmethod::get_and_cache_jmethod_id() {
1686   if (_jmethod_id == NULL) {
1687     // Cache the jmethod_id since it can no longer be looked up once the
1688     // method itself has been marked for unloading.
1689     _jmethod_id = method()->jmethod_id();
1690   }
1691   return _jmethod_id;
1692 }
1693 
1694 void nmethod::post_compiled_method_unload() {
1695   if (unload_reported()) {
1696     // During unloading we transition to unloaded and then to zombie
1697     // and the unloading is reported during the first transition.
1698     return;
1699   }
1700 
1701   assert(_method != NULL && !is_unloaded(), "just checking");
1702   DTRACE_METHOD_UNLOAD_PROBE(method());
1703 
1704   // If a JVMTI agent has enabled the CompiledMethodUnload event then
1705   // post the event. Sometime later this nmethod will be made a zombie
1706   // by the sweeper but the Method* will not be valid at that point.
1707   // If the _jmethod_id is null then no load event was ever requested
1708   // so don't bother posting the unload.  The main reason for this is
1709   // that the jmethodID is a weak reference to the Method* so if
1710   // it's being unloaded there's no way to look it up since the weak
1711   // ref will have been cleared.
1712   if (_jmethod_id != NULL && JvmtiExport::should_post_compiled_method_unload()) {
1713     assert(!unload_reported(), "already unloaded");
1714     JvmtiDeferredEvent event =
1715       JvmtiDeferredEvent::compiled_method_unload_event(this,
1716           _jmethod_id, insts_begin());
1717     if (SafepointSynchronize::is_at_safepoint()) {
1718       // Don't want to take the queueing lock. Add it as pending and
1719       // it will get enqueued later.
1720       JvmtiDeferredEventQueue::add_pending_event(event);
1721     } else {
1722       MutexLockerEx ml(Service_lock, Mutex::_no_safepoint_check_flag);
1723       JvmtiDeferredEventQueue::enqueue(event);
1724     }
1725   }
1726 
1727   // The JVMTI CompiledMethodUnload event can be enabled or disabled at
1728   // any time. As the nmethod is being unloaded now we mark it has
1729   // having the unload event reported - this will ensure that we don't
1730   // attempt to report the event in the unlikely scenario where the
1731   // event is enabled at the time the nmethod is made a zombie.
1732   set_unload_reported();
1733 }
1734 
1735 void static clean_ic_if_metadata_is_dead(CompiledIC *ic, BoolObjectClosure *is_alive) {
1736   if (ic->is_icholder_call()) {
1737     // The only exception is compiledICHolder oops which may
1738     // yet be marked below. (We check this further below).
1739     CompiledICHolder* cichk_oop = ic->cached_icholder();
1740 
1741     if (cichk_oop->holder_method()->method_holder()->is_loader_alive(is_alive) &&
1742         cichk_oop->holder_klass()->is_loader_alive(is_alive)) {
1743       return;
1744     }
1745   } else {
1746     Metadata* ic_oop = ic->cached_metadata();
1747     if (ic_oop != NULL) {
1748       if (ic_oop->is_klass()) {
1749         if (((Klass*)ic_oop)->is_loader_alive(is_alive)) {
1750           return;
1751         }
1752       } else if (ic_oop->is_method()) {
1753         if (((Method*)ic_oop)->method_holder()->is_loader_alive(is_alive)) {
1754           return;
1755         }
1756       } else {
1757         ShouldNotReachHere();
1758       }
1759     }
1760   }
1761 
1762   ic->set_to_clean();
1763 }
1764 
1765 // This is called at the end of the strong tracing/marking phase of a
1766 // GC to unload an nmethod if it contains otherwise unreachable
1767 // oops.
1768 
1769 void nmethod::do_unloading(BoolObjectClosure* is_alive, bool unloading_occurred) {
1770   // Make sure the oop's ready to receive visitors
1771   assert(!is_zombie() && !is_unloaded(),
1772          "should not call follow on zombie or unloaded nmethod");
1773 
1774   // If the method is not entrant then a JMP is plastered over the
1775   // first few bytes.  If an oop in the old code was there, that oop
1776   // should not get GC'd.  Skip the first few bytes of oops on
1777   // not-entrant methods.
1778   address low_boundary = verified_entry_point();
1779   if (is_not_entrant()) {
1780     low_boundary += NativeJump::instruction_size;
1781     // %%% Note:  On SPARC we patch only a 4-byte trap, not a full NativeJump.
1782     // (See comment above.)
1783   }
1784 
1785   // The RedefineClasses() API can cause the class unloading invariant
1786   // to no longer be true. See jvmtiExport.hpp for details.
1787   // Also, leave a debugging breadcrumb in local flag.
1788   if (JvmtiExport::has_redefined_a_class()) {
1789     // This set of the unloading_occurred flag is done before the
1790     // call to post_compiled_method_unload() so that the unloading
1791     // of this nmethod is reported.
1792     unloading_occurred = true;
1793   }
1794 
1795   // Exception cache
1796   clean_exception_cache(is_alive);
1797 
1798   // If class unloading occurred we first iterate over all inline caches and
1799   // clear ICs where the cached oop is referring to an unloaded klass or method.
1800   // The remaining live cached oops will be traversed in the relocInfo::oop_type
1801   // iteration below.
1802   if (unloading_occurred) {
1803     RelocIterator iter(this, low_boundary);
1804     while(iter.next()) {
1805       if (iter.type() == relocInfo::virtual_call_type) {
1806         CompiledIC *ic = CompiledIC_at(&iter);
1807         clean_ic_if_metadata_is_dead(ic, is_alive);
1808       }
1809     }
1810   }
1811 
1812   // Compiled code
1813   {
1814   RelocIterator iter(this, low_boundary);
1815   while (iter.next()) {
1816     if (iter.type() == relocInfo::oop_type) {
1817       oop_Relocation* r = iter.oop_reloc();
1818       // In this loop, we must only traverse those oops directly embedded in
1819       // the code.  Other oops (oop_index>0) are seen as part of scopes_oops.
1820       assert(1 == (r->oop_is_immediate()) +
1821                   (r->oop_addr() >= oops_begin() && r->oop_addr() < oops_end()),
1822              "oop must be found in exactly one place");
1823       if (r->oop_is_immediate() && r->oop_value() != NULL) {
1824         if (can_unload(is_alive, r->oop_addr(), unloading_occurred)) {
1825           return;
1826         }
1827       }
1828     }
1829   }
1830   }
1831 
1832 
1833   // Scopes
1834   for (oop* p = oops_begin(); p < oops_end(); p++) {
1835     if (*p == Universe::non_oop_word())  continue;  // skip non-oops
1836     if (can_unload(is_alive, p, unloading_occurred)) {
1837       return;
1838     }
1839   }
1840 
1841 #if INCLUDE_JVMCI
1842   // Follow JVMCI method
1843   BarrierSet* bs = Universe::heap()->barrier_set();
1844   if (_jvmci_installed_code != NULL) {
1845     if (_jvmci_installed_code->is_a(HotSpotNmethod::klass()) && HotSpotNmethod::isDefault(_jvmci_installed_code)) {
1846       if (!is_alive->do_object_b(_jvmci_installed_code)) {
1847         clear_jvmci_installed_code();
1848       }
1849     } else {
1850       if (can_unload(is_alive, (oop*)&_jvmci_installed_code, unloading_occurred)) {
1851         return;
1852       }
1853     }
1854   }
1855 
1856   if (_speculation_log != NULL) {
1857     if (!is_alive->do_object_b(_speculation_log)) {
1858       bs->write_ref_nmethod_pre(&_speculation_log, this);
1859       _speculation_log = NULL;
1860       bs->write_ref_nmethod_post(&_speculation_log, this);
1861     }
1862   }
1863 #endif
1864 
1865 
1866   // Ensure that all metadata is still alive
1867   verify_metadata_loaders(low_boundary, is_alive);
1868 }
1869 
1870 template <class CompiledICorStaticCall>
1871 static bool clean_if_nmethod_is_unloaded(CompiledICorStaticCall *ic, address addr, BoolObjectClosure *is_alive, nmethod* from) {
1872   // Ok, to lookup references to zombies here
1873   CodeBlob *cb = CodeCache::find_blob_unsafe(addr);
1874   if (cb != NULL && cb->is_nmethod()) {
1875     nmethod* nm = (nmethod*)cb;
1876 
1877     if (nm->unloading_clock() != nmethod::global_unloading_clock()) {
1878       // The nmethod has not been processed yet.
1879       return true;
1880     }
1881 
1882     // Clean inline caches pointing to both zombie and not_entrant methods
1883     if (!nm->is_in_use() || (nm->method()->code() != nm)) {
1884       ic->set_to_clean();
1885       assert(ic->is_clean(), "nmethod " PTR_FORMAT "not clean %s", p2i(from), from->method()->name_and_sig_as_C_string());
1886     }
1887   }
1888 
1889   return false;
1890 }
1891 
1892 static bool clean_if_nmethod_is_unloaded(CompiledIC *ic, BoolObjectClosure *is_alive, nmethod* from) {
1893   return clean_if_nmethod_is_unloaded(ic, ic->ic_destination(), is_alive, from);
1894 }
1895 
1896 static bool clean_if_nmethod_is_unloaded(CompiledStaticCall *csc, BoolObjectClosure *is_alive, nmethod* from) {
1897   return clean_if_nmethod_is_unloaded(csc, csc->destination(), is_alive, from);
1898 }
1899 
1900 bool nmethod::unload_if_dead_at(RelocIterator* iter_at_oop, BoolObjectClosure *is_alive, bool unloading_occurred) {
1901   assert(iter_at_oop->type() == relocInfo::oop_type, "Wrong relocation type");
1902 
1903   oop_Relocation* r = iter_at_oop->oop_reloc();
1904   // Traverse those oops directly embedded in the code.
1905   // Other oops (oop_index>0) are seen as part of scopes_oops.
1906   assert(1 == (r->oop_is_immediate()) +
1907          (r->oop_addr() >= oops_begin() && r->oop_addr() < oops_end()),
1908          "oop must be found in exactly one place");
1909   if (r->oop_is_immediate() && r->oop_value() != NULL) {
1910     // Unload this nmethod if the oop is dead.
1911     if (can_unload(is_alive, r->oop_addr(), unloading_occurred)) {
1912       return true;;
1913     }
1914   }
1915 
1916   return false;
1917 }
1918 
1919 
1920 bool nmethod::do_unloading_parallel(BoolObjectClosure* is_alive, bool unloading_occurred) {
1921   ResourceMark rm;
1922 
1923   // Make sure the oop's ready to receive visitors
1924   assert(!is_zombie() && !is_unloaded(),
1925          "should not call follow on zombie or unloaded nmethod");
1926 
1927   // If the method is not entrant then a JMP is plastered over the
1928   // first few bytes.  If an oop in the old code was there, that oop
1929   // should not get GC'd.  Skip the first few bytes of oops on
1930   // not-entrant methods.
1931   address low_boundary = verified_entry_point();
1932   if (is_not_entrant()) {
1933     low_boundary += NativeJump::instruction_size;
1934     // %%% Note:  On SPARC we patch only a 4-byte trap, not a full NativeJump.
1935     // (See comment above.)
1936   }
1937 
1938   // The RedefineClasses() API can cause the class unloading invariant
1939   // to no longer be true. See jvmtiExport.hpp for details.
1940   // Also, leave a debugging breadcrumb in local flag.
1941   if (JvmtiExport::has_redefined_a_class()) {
1942     // This set of the unloading_occurred flag is done before the
1943     // call to post_compiled_method_unload() so that the unloading
1944     // of this nmethod is reported.
1945     unloading_occurred = true;
1946   }
1947 
1948   // Exception cache
1949   clean_exception_cache(is_alive);
1950 
1951   bool is_unloaded = false;
1952   bool postponed = false;
1953 
1954   RelocIterator iter(this, low_boundary);
1955   while(iter.next()) {
1956 
1957     switch (iter.type()) {
1958 
1959     case relocInfo::virtual_call_type:
1960       if (unloading_occurred) {
1961         // If class unloading occurred we first iterate over all inline caches and
1962         // clear ICs where the cached oop is referring to an unloaded klass or method.
1963         clean_ic_if_metadata_is_dead(CompiledIC_at(&iter), is_alive);
1964       }
1965 
1966       postponed |= clean_if_nmethod_is_unloaded(CompiledIC_at(&iter), is_alive, this);
1967       break;
1968 
1969     case relocInfo::opt_virtual_call_type:
1970       postponed |= clean_if_nmethod_is_unloaded(CompiledIC_at(&iter), is_alive, this);
1971       break;
1972 
1973     case relocInfo::static_call_type:
1974       postponed |= clean_if_nmethod_is_unloaded(compiledStaticCall_at(iter.reloc()), is_alive, this);
1975       break;
1976 
1977     case relocInfo::oop_type:
1978       if (!is_unloaded) {
1979         is_unloaded = unload_if_dead_at(&iter, is_alive, unloading_occurred);
1980       }
1981       break;
1982 
1983     case relocInfo::metadata_type:
1984       break; // nothing to do.
1985     }
1986   }
1987 
1988   if (is_unloaded) {
1989     return postponed;
1990   }
1991 
1992   // Scopes
1993   for (oop* p = oops_begin(); p < oops_end(); p++) {
1994     if (*p == Universe::non_oop_word())  continue;  // skip non-oops
1995     if (can_unload(is_alive, p, unloading_occurred)) {
1996       is_unloaded = true;
1997       break;
1998     }
1999   }
2000 
2001   if (is_unloaded) {
2002     return postponed;
2003   }
2004 
2005 #if INCLUDE_JVMCI
2006   // Follow JVMCI method
2007   BarrierSet* bs = Universe::heap()->barrier_set();
2008   if (_jvmci_installed_code != NULL) {
2009     if (_jvmci_installed_code->is_a(HotSpotNmethod::klass()) && HotSpotNmethod::isDefault(_jvmci_installed_code)) {
2010       if (!is_alive->do_object_b(_jvmci_installed_code)) {
2011         clear_jvmci_installed_code();
2012       }
2013     } else {
2014       if (can_unload(is_alive, (oop*)&_jvmci_installed_code, unloading_occurred)) {
2015         is_unloaded = true;
2016       }
2017     }
2018   }
2019 
2020   if (_speculation_log != NULL) {
2021     if (!is_alive->do_object_b(_speculation_log)) {
2022       bs->write_ref_nmethod_pre(&_speculation_log, this);
2023       _speculation_log = NULL;
2024       bs->write_ref_nmethod_post(&_speculation_log, this);
2025     }
2026   }
2027 #endif
2028 
2029   // Ensure that all metadata is still alive
2030   verify_metadata_loaders(low_boundary, is_alive);
2031 
2032   return postponed;
2033 }
2034 
2035 void nmethod::do_unloading_parallel_postponed(BoolObjectClosure* is_alive, bool unloading_occurred) {
2036   ResourceMark rm;
2037 
2038   // Make sure the oop's ready to receive visitors
2039   assert(!is_zombie(),
2040          "should not call follow on zombie nmethod");
2041 
2042   // If the method is not entrant then a JMP is plastered over the
2043   // first few bytes.  If an oop in the old code was there, that oop
2044   // should not get GC'd.  Skip the first few bytes of oops on
2045   // not-entrant methods.
2046   address low_boundary = verified_entry_point();
2047   if (is_not_entrant()) {
2048     low_boundary += NativeJump::instruction_size;
2049     // %%% Note:  On SPARC we patch only a 4-byte trap, not a full NativeJump.
2050     // (See comment above.)
2051   }
2052 
2053   RelocIterator iter(this, low_boundary);
2054   while(iter.next()) {
2055 
2056     switch (iter.type()) {
2057 
2058     case relocInfo::virtual_call_type:
2059       clean_if_nmethod_is_unloaded(CompiledIC_at(&iter), is_alive, this);
2060       break;
2061 
2062     case relocInfo::opt_virtual_call_type:
2063       clean_if_nmethod_is_unloaded(CompiledIC_at(&iter), is_alive, this);
2064       break;
2065 
2066     case relocInfo::static_call_type:
2067       clean_if_nmethod_is_unloaded(compiledStaticCall_at(iter.reloc()), is_alive, this);
2068       break;
2069     }
2070   }
2071 }
2072 
2073 #ifdef ASSERT
2074 
2075 class CheckClass : AllStatic {
2076   static BoolObjectClosure* _is_alive;
2077 
2078   // Check class_loader is alive for this bit of metadata.
2079   static void check_class(Metadata* md) {
2080     Klass* klass = NULL;
2081     if (md->is_klass()) {
2082       klass = ((Klass*)md);
2083     } else if (md->is_method()) {
2084       klass = ((Method*)md)->method_holder();
2085     } else if (md->is_methodData()) {
2086       klass = ((MethodData*)md)->method()->method_holder();
2087     } else {
2088       md->print();
2089       ShouldNotReachHere();
2090     }
2091     assert(klass->is_loader_alive(_is_alive), "must be alive");
2092   }
2093  public:
2094   static void do_check_class(BoolObjectClosure* is_alive, nmethod* nm) {
2095     assert(SafepointSynchronize::is_at_safepoint(), "this is only ok at safepoint");
2096     _is_alive = is_alive;
2097     nm->metadata_do(check_class);
2098   }
2099 };
2100 
2101 // This is called during a safepoint so can use static data
2102 BoolObjectClosure* CheckClass::_is_alive = NULL;
2103 #endif // ASSERT
2104 
2105 
2106 // Processing of oop references should have been sufficient to keep
2107 // all strong references alive.  Any weak references should have been
2108 // cleared as well.  Visit all the metadata and ensure that it's
2109 // really alive.
2110 void nmethod::verify_metadata_loaders(address low_boundary, BoolObjectClosure* is_alive) {
2111 #ifdef ASSERT
2112     RelocIterator iter(this, low_boundary);
2113     while (iter.next()) {
2114     // static_stub_Relocations may have dangling references to
2115     // Method*s so trim them out here.  Otherwise it looks like
2116     // compiled code is maintaining a link to dead metadata.
2117     address static_call_addr = NULL;
2118     if (iter.type() == relocInfo::opt_virtual_call_type) {
2119       CompiledIC* cic = CompiledIC_at(&iter);
2120       if (!cic->is_call_to_interpreted()) {
2121         static_call_addr = iter.addr();
2122       }
2123     } else if (iter.type() == relocInfo::static_call_type) {
2124       CompiledStaticCall* csc = compiledStaticCall_at(iter.reloc());
2125       if (!csc->is_call_to_interpreted()) {
2126         static_call_addr = iter.addr();
2127       }
2128     }
2129     if (static_call_addr != NULL) {
2130       RelocIterator sciter(this, low_boundary);
2131       while (sciter.next()) {
2132         if (sciter.type() == relocInfo::static_stub_type &&
2133             sciter.static_stub_reloc()->static_call() == static_call_addr) {
2134           sciter.static_stub_reloc()->clear_inline_cache();
2135         }
2136       }
2137     }
2138   }
2139   // Check that the metadata embedded in the nmethod is alive
2140   CheckClass::do_check_class(is_alive, this);
2141 #endif
2142 }
2143 
2144 
2145 // Iterate over metadata calling this function.   Used by RedefineClasses
2146 void nmethod::metadata_do(void f(Metadata*)) {
2147   address low_boundary = verified_entry_point();
2148   if (is_not_entrant()) {
2149     low_boundary += NativeJump::instruction_size;
2150     // %%% Note:  On SPARC we patch only a 4-byte trap, not a full NativeJump.
2151     // (See comment above.)
2152   }
2153   {
2154     // Visit all immediate references that are embedded in the instruction stream.
2155     RelocIterator iter(this, low_boundary);
2156     while (iter.next()) {
2157       if (iter.type() == relocInfo::metadata_type ) {
2158         metadata_Relocation* r = iter.metadata_reloc();
2159         // In this metadata, we must only follow those metadatas directly embedded in
2160         // the code.  Other metadatas (oop_index>0) are seen as part of
2161         // the metadata section below.
2162         assert(1 == (r->metadata_is_immediate()) +
2163                (r->metadata_addr() >= metadata_begin() && r->metadata_addr() < metadata_end()),
2164                "metadata must be found in exactly one place");
2165         if (r->metadata_is_immediate() && r->metadata_value() != NULL) {
2166           Metadata* md = r->metadata_value();
2167           if (md != _method) f(md);
2168         }
2169       } else if (iter.type() == relocInfo::virtual_call_type) {
2170         // Check compiledIC holders associated with this nmethod
2171         CompiledIC *ic = CompiledIC_at(&iter);
2172         if (ic->is_icholder_call()) {
2173           CompiledICHolder* cichk = ic->cached_icholder();
2174           f(cichk->holder_method());
2175           f(cichk->holder_klass());
2176         } else {
2177           Metadata* ic_oop = ic->cached_metadata();
2178           if (ic_oop != NULL) {
2179             f(ic_oop);
2180           }
2181         }
2182       }
2183     }
2184   }
2185 
2186   // Visit the metadata section
2187   for (Metadata** p = metadata_begin(); p < metadata_end(); p++) {
2188     if (*p == Universe::non_oop_word() || *p == NULL)  continue;  // skip non-oops
2189     Metadata* md = *p;
2190     f(md);
2191   }
2192 
2193   // Visit metadata not embedded in the other places.
2194   if (_method != NULL) f(_method);
2195 }
2196 
2197 void nmethod::oops_do(OopClosure* f, bool allow_zombie) {
2198   // make sure the oops ready to receive visitors
2199   assert(allow_zombie || !is_zombie(), "should not call follow on zombie nmethod");
2200   assert(!is_unloaded(), "should not call follow on unloaded nmethod");
2201 
2202   // If the method is not entrant or zombie then a JMP is plastered over the
2203   // first few bytes.  If an oop in the old code was there, that oop
2204   // should not get GC'd.  Skip the first few bytes of oops on
2205   // not-entrant methods.
2206   address low_boundary = verified_entry_point();
2207   if (is_not_entrant()) {
2208     low_boundary += NativeJump::instruction_size;
2209     // %%% Note:  On SPARC we patch only a 4-byte trap, not a full NativeJump.
2210     // (See comment above.)
2211   }
2212 
2213 #if INCLUDE_JVMCI
2214   if (_jvmci_installed_code != NULL) {
2215     f->do_oop((oop*) &_jvmci_installed_code);
2216   }
2217   if (_speculation_log != NULL) {
2218     f->do_oop((oop*) &_speculation_log);
2219   }
2220 #endif
2221 
2222   RelocIterator iter(this, low_boundary);
2223 
2224   while (iter.next()) {
2225     if (iter.type() == relocInfo::oop_type ) {
2226       oop_Relocation* r = iter.oop_reloc();
2227       // In this loop, we must only follow those oops directly embedded in
2228       // the code.  Other oops (oop_index>0) are seen as part of scopes_oops.
2229       assert(1 == (r->oop_is_immediate()) +
2230                    (r->oop_addr() >= oops_begin() && r->oop_addr() < oops_end()),
2231              "oop must be found in exactly one place");
2232       if (r->oop_is_immediate() && r->oop_value() != NULL) {
2233         f->do_oop(r->oop_addr());
2234       }
2235     }
2236   }
2237 
2238   // Scopes
2239   // This includes oop constants not inlined in the code stream.
2240   for (oop* p = oops_begin(); p < oops_end(); p++) {
2241     if (*p == Universe::non_oop_word())  continue;  // skip non-oops
2242     f->do_oop(p);
2243   }
2244 }
2245 
2246 #define NMETHOD_SENTINEL ((nmethod*)badAddress)
2247 
2248 nmethod* volatile nmethod::_oops_do_mark_nmethods;
2249 
2250 // An nmethod is "marked" if its _mark_link is set non-null.
2251 // Even if it is the end of the linked list, it will have a non-null link value,
2252 // as long as it is on the list.
2253 // This code must be MP safe, because it is used from parallel GC passes.
2254 bool nmethod::test_set_oops_do_mark() {
2255   assert(nmethod::oops_do_marking_is_active(), "oops_do_marking_prologue must be called");
2256   nmethod* observed_mark_link = _oops_do_mark_link;
2257   if (observed_mark_link == NULL) {
2258     // Claim this nmethod for this thread to mark.
2259     observed_mark_link = (nmethod*)
2260       Atomic::cmpxchg_ptr(NMETHOD_SENTINEL, &_oops_do_mark_link, NULL);
2261     if (observed_mark_link == NULL) {
2262 
2263       // Atomically append this nmethod (now claimed) to the head of the list:
2264       nmethod* observed_mark_nmethods = _oops_do_mark_nmethods;
2265       for (;;) {
2266         nmethod* required_mark_nmethods = observed_mark_nmethods;
2267         _oops_do_mark_link = required_mark_nmethods;
2268         observed_mark_nmethods = (nmethod*)
2269           Atomic::cmpxchg_ptr(this, &_oops_do_mark_nmethods, required_mark_nmethods);
2270         if (observed_mark_nmethods == required_mark_nmethods)
2271           break;
2272       }
2273       // Mark was clear when we first saw this guy.
2274       if (TraceScavenge) { print_on(tty, "oops_do, mark"); }
2275       return false;
2276     }
2277   }
2278   // On fall through, another racing thread marked this nmethod before we did.
2279   return true;
2280 }
2281 
2282 void nmethod::oops_do_marking_prologue() {
2283   if (TraceScavenge) { tty->print_cr("[oops_do_marking_prologue"); }
2284   assert(_oops_do_mark_nmethods == NULL, "must not call oops_do_marking_prologue twice in a row");
2285   // We use cmpxchg_ptr instead of regular assignment here because the user
2286   // may fork a bunch of threads, and we need them all to see the same state.
2287   void* observed = Atomic::cmpxchg_ptr(NMETHOD_SENTINEL, &_oops_do_mark_nmethods, NULL);
2288   guarantee(observed == NULL, "no races in this sequential code");
2289 }
2290 
2291 void nmethod::oops_do_marking_epilogue() {
2292   assert(_oops_do_mark_nmethods != NULL, "must not call oops_do_marking_epilogue twice in a row");
2293   nmethod* cur = _oops_do_mark_nmethods;
2294   while (cur != NMETHOD_SENTINEL) {
2295     assert(cur != NULL, "not NULL-terminated");
2296     nmethod* next = cur->_oops_do_mark_link;
2297     cur->_oops_do_mark_link = NULL;
2298     DEBUG_ONLY(cur->verify_oop_relocations());
2299     NOT_PRODUCT(if (TraceScavenge)  cur->print_on(tty, "oops_do, unmark"));
2300     cur = next;
2301   }
2302   void* required = _oops_do_mark_nmethods;
2303   void* observed = Atomic::cmpxchg_ptr(NULL, &_oops_do_mark_nmethods, required);
2304   guarantee(observed == required, "no races in this sequential code");
2305   if (TraceScavenge) { tty->print_cr("oops_do_marking_epilogue]"); }
2306 }
2307 
2308 class DetectScavengeRoot: public OopClosure {
2309   bool     _detected_scavenge_root;
2310 public:
2311   DetectScavengeRoot() : _detected_scavenge_root(false)
2312   { NOT_PRODUCT(_print_nm = NULL); }
2313   bool detected_scavenge_root() { return _detected_scavenge_root; }
2314   virtual void do_oop(oop* p) {
2315     if ((*p) != NULL && (*p)->is_scavengable()) {
2316       NOT_PRODUCT(maybe_print(p));
2317       _detected_scavenge_root = true;
2318     }
2319   }
2320   virtual void do_oop(narrowOop* p) { ShouldNotReachHere(); }
2321 
2322 #ifndef PRODUCT
2323   nmethod* _print_nm;
2324   void maybe_print(oop* p) {
2325     if (_print_nm == NULL)  return;
2326     if (!_detected_scavenge_root)  _print_nm->print_on(tty, "new scavenge root");
2327     tty->print_cr("" PTR_FORMAT "[offset=%d] detected scavengable oop " PTR_FORMAT " (found at " PTR_FORMAT ")",
2328                   p2i(_print_nm), (int)((intptr_t)p - (intptr_t)_print_nm),
2329                   p2i(*p), p2i(p));
2330     (*p)->print();
2331   }
2332 #endif //PRODUCT
2333 };
2334 
2335 bool nmethod::detect_scavenge_root_oops() {
2336   DetectScavengeRoot detect_scavenge_root;
2337   NOT_PRODUCT(if (TraceScavenge)  detect_scavenge_root._print_nm = this);
2338   oops_do(&detect_scavenge_root);
2339   return detect_scavenge_root.detected_scavenge_root();
2340 }
2341 
2342 // Method that knows how to preserve outgoing arguments at call. This method must be
2343 // called with a frame corresponding to a Java invoke
2344 void nmethod::preserve_callee_argument_oops(frame fr, const RegisterMap *reg_map, OopClosure* f) {
2345 #ifndef SHARK
2346   if (method() != NULL && !method()->is_native()) {
2347     address pc = fr.pc();
2348     SimpleScopeDesc ssd(this, pc);
2349     Bytecode_invoke call(ssd.method(), ssd.bci());
2350     bool has_receiver = call.has_receiver();
2351     bool has_appendix = call.has_appendix();
2352     Symbol* signature = call.signature();
2353 
2354     // The method attached by JIT-compilers should be used, if present.
2355     // Bytecode can be inaccurate in such case.
2356     Method* callee = attached_method_before_pc(pc);
2357     if (callee != NULL) {
2358       has_receiver = !(callee->access_flags().is_static());
2359       has_appendix = false;
2360       signature = callee->signature();
2361     }
2362 
2363     fr.oops_compiled_arguments_do(signature, has_receiver, has_appendix, reg_map, f);
2364   }
2365 #endif // !SHARK
2366 }
2367 
2368 inline bool includes(void* p, void* from, void* to) {
2369   return from <= p && p < to;
2370 }
2371 
2372 
2373 void nmethod::copy_scopes_pcs(PcDesc* pcs, int count) {
2374   assert(count >= 2, "must be sentinel values, at least");
2375 
2376 #ifdef ASSERT
2377   // must be sorted and unique; we do a binary search in find_pc_desc()
2378   int prev_offset = pcs[0].pc_offset();
2379   assert(prev_offset == PcDesc::lower_offset_limit,
2380          "must start with a sentinel");
2381   for (int i = 1; i < count; i++) {
2382     int this_offset = pcs[i].pc_offset();
2383     assert(this_offset > prev_offset, "offsets must be sorted");
2384     prev_offset = this_offset;
2385   }
2386   assert(prev_offset == PcDesc::upper_offset_limit,
2387          "must end with a sentinel");
2388 #endif //ASSERT
2389 
2390   // Search for MethodHandle invokes and tag the nmethod.
2391   for (int i = 0; i < count; i++) {
2392     if (pcs[i].is_method_handle_invoke()) {
2393       set_has_method_handle_invokes(true);
2394       break;
2395     }
2396   }
2397   assert(has_method_handle_invokes() == (_deoptimize_mh_offset != -1), "must have deopt mh handler");
2398 
2399   int size = count * sizeof(PcDesc);
2400   assert(scopes_pcs_size() >= size, "oob");
2401   memcpy(scopes_pcs_begin(), pcs, size);
2402 
2403   // Adjust the final sentinel downward.
2404   PcDesc* last_pc = &scopes_pcs_begin()[count-1];
2405   assert(last_pc->pc_offset() == PcDesc::upper_offset_limit, "sanity");
2406   last_pc->set_pc_offset(content_size() + 1);
2407   for (; last_pc + 1 < scopes_pcs_end(); last_pc += 1) {
2408     // Fill any rounding gaps with copies of the last record.
2409     last_pc[1] = last_pc[0];
2410   }
2411   // The following assert could fail if sizeof(PcDesc) is not
2412   // an integral multiple of oopSize (the rounding term).
2413   // If it fails, change the logic to always allocate a multiple
2414   // of sizeof(PcDesc), and fill unused words with copies of *last_pc.
2415   assert(last_pc + 1 == scopes_pcs_end(), "must match exactly");
2416 }
2417 
2418 void nmethod::copy_scopes_data(u_char* buffer, int size) {
2419   assert(scopes_data_size() >= size, "oob");
2420   memcpy(scopes_data_begin(), buffer, size);
2421 }
2422 
2423 // When using JVMCI the address might be off by the size of a call instruction.
2424 bool nmethod::is_deopt_entry(address pc) {
2425   return pc == deopt_handler_begin()
2426 #if INCLUDE_JVMCI
2427     || pc == (deopt_handler_begin() + NativeCall::instruction_size)
2428 #endif
2429     ;
2430 }
2431 
2432 #ifdef ASSERT
2433 static PcDesc* linear_search(nmethod* nm, int pc_offset, bool approximate) {
2434   PcDesc* lower = nm->scopes_pcs_begin();
2435   PcDesc* upper = nm->scopes_pcs_end();
2436   lower += 1; // exclude initial sentinel
2437   PcDesc* res = NULL;
2438   for (PcDesc* p = lower; p < upper; p++) {
2439     NOT_PRODUCT(--pc_nmethod_stats.pc_desc_tests);  // don't count this call to match_desc
2440     if (match_desc(p, pc_offset, approximate)) {
2441       if (res == NULL)
2442         res = p;
2443       else
2444         res = (PcDesc*) badAddress;
2445     }
2446   }
2447   return res;
2448 }
2449 #endif
2450 
2451 
2452 // Finds a PcDesc with real-pc equal to "pc"
2453 PcDesc* nmethod::find_pc_desc_internal(address pc, bool approximate) {
2454   address base_address = code_begin();
2455   if ((pc < base_address) ||
2456       (pc - base_address) >= (ptrdiff_t) PcDesc::upper_offset_limit) {
2457     return NULL;  // PC is wildly out of range
2458   }
2459   int pc_offset = (int) (pc - base_address);
2460 
2461   // Check the PcDesc cache if it contains the desired PcDesc
2462   // (This as an almost 100% hit rate.)
2463   PcDesc* res = _pc_desc_cache.find_pc_desc(pc_offset, approximate);
2464   if (res != NULL) {
2465     assert(res == linear_search(this, pc_offset, approximate), "cache ok");
2466     return res;
2467   }
2468 
2469   // Fallback algorithm: quasi-linear search for the PcDesc
2470   // Find the last pc_offset less than the given offset.
2471   // The successor must be the required match, if there is a match at all.
2472   // (Use a fixed radix to avoid expensive affine pointer arithmetic.)
2473   PcDesc* lower = scopes_pcs_begin();
2474   PcDesc* upper = scopes_pcs_end();
2475   upper -= 1; // exclude final sentinel
2476   if (lower >= upper)  return NULL;  // native method; no PcDescs at all
2477 
2478 #define assert_LU_OK \
2479   /* invariant on lower..upper during the following search: */ \
2480   assert(lower->pc_offset() <  pc_offset, "sanity"); \
2481   assert(upper->pc_offset() >= pc_offset, "sanity")
2482   assert_LU_OK;
2483 
2484   // Use the last successful return as a split point.
2485   PcDesc* mid = _pc_desc_cache.last_pc_desc();
2486   NOT_PRODUCT(++pc_nmethod_stats.pc_desc_searches);
2487   if (mid->pc_offset() < pc_offset) {
2488     lower = mid;
2489   } else {
2490     upper = mid;
2491   }
2492 
2493   // Take giant steps at first (4096, then 256, then 16, then 1)
2494   const int LOG2_RADIX = 4 /*smaller steps in debug mode:*/ debug_only(-1);
2495   const int RADIX = (1 << LOG2_RADIX);
2496   for (int step = (1 << (LOG2_RADIX*3)); step > 1; step >>= LOG2_RADIX) {
2497     while ((mid = lower + step) < upper) {
2498       assert_LU_OK;
2499       NOT_PRODUCT(++pc_nmethod_stats.pc_desc_searches);
2500       if (mid->pc_offset() < pc_offset) {
2501         lower = mid;
2502       } else {
2503         upper = mid;
2504         break;
2505       }
2506     }
2507     assert_LU_OK;
2508   }
2509 
2510   // Sneak up on the value with a linear search of length ~16.
2511   while (true) {
2512     assert_LU_OK;
2513     mid = lower + 1;
2514     NOT_PRODUCT(++pc_nmethod_stats.pc_desc_searches);
2515     if (mid->pc_offset() < pc_offset) {
2516       lower = mid;
2517     } else {
2518       upper = mid;
2519       break;
2520     }
2521   }
2522 #undef assert_LU_OK
2523 
2524   if (match_desc(upper, pc_offset, approximate)) {
2525     assert(upper == linear_search(this, pc_offset, approximate), "search ok");
2526     _pc_desc_cache.add_pc_desc(upper);
2527     return upper;
2528   } else {
2529     assert(NULL == linear_search(this, pc_offset, approximate), "search ok");
2530     return NULL;
2531   }
2532 }
2533 
2534 
2535 void nmethod::check_all_dependencies(DepChange& changes) {
2536   // Checked dependencies are allocated into this ResourceMark
2537   ResourceMark rm;
2538 
2539   // Turn off dependency tracing while actually testing dependencies.
2540   NOT_PRODUCT( FlagSetting fs(TraceDependencies, false) );
2541 
2542   typedef ResourceHashtable<DependencySignature, int, &DependencySignature::hash,
2543                             &DependencySignature::equals, 11027> DepTable;
2544 
2545   DepTable* table = new DepTable();
2546 
2547   // Iterate over live nmethods and check dependencies of all nmethods that are not
2548   // marked for deoptimization. A particular dependency is only checked once.
2549   NMethodIterator iter;
2550   while(iter.next()) {
2551     nmethod* nm = iter.method();
2552     // Only notify for live nmethods
2553     if (nm->is_alive() && !nm->is_marked_for_deoptimization()) {
2554       for (Dependencies::DepStream deps(nm); deps.next(); ) {
2555         // Construct abstraction of a dependency.
2556         DependencySignature* current_sig = new DependencySignature(deps);
2557 
2558         // Determine if dependency is already checked. table->put(...) returns
2559         // 'true' if the dependency is added (i.e., was not in the hashtable).
2560         if (table->put(*current_sig, 1)) {
2561           if (deps.check_dependency() != NULL) {
2562             // Dependency checking failed. Print out information about the failed
2563             // dependency and finally fail with an assert. We can fail here, since
2564             // dependency checking is never done in a product build.
2565             tty->print_cr("Failed dependency:");
2566             changes.print();
2567             nm->print();
2568             nm->print_dependencies();
2569             assert(false, "Should have been marked for deoptimization");
2570           }
2571         }
2572       }
2573     }
2574   }
2575 }
2576 
2577 bool nmethod::check_dependency_on(DepChange& changes) {
2578   // What has happened:
2579   // 1) a new class dependee has been added
2580   // 2) dependee and all its super classes have been marked
2581   bool found_check = false;  // set true if we are upset
2582   for (Dependencies::DepStream deps(this); deps.next(); ) {
2583     // Evaluate only relevant dependencies.
2584     if (deps.spot_check_dependency_at(changes) != NULL) {
2585       found_check = true;
2586       NOT_DEBUG(break);
2587     }
2588   }
2589   return found_check;
2590 }
2591 
2592 bool nmethod::is_evol_dependent_on(Klass* dependee) {
2593   InstanceKlass *dependee_ik = InstanceKlass::cast(dependee);
2594   Array<Method*>* dependee_methods = dependee_ik->methods();
2595   for (Dependencies::DepStream deps(this); deps.next(); ) {
2596     if (deps.type() == Dependencies::evol_method) {
2597       Method* method = deps.method_argument(0);
2598       for (int j = 0; j < dependee_methods->length(); j++) {
2599         if (dependee_methods->at(j) == method) {
2600           // RC_TRACE macro has an embedded ResourceMark
2601           RC_TRACE(0x01000000,
2602             ("Found evol dependency of nmethod %s.%s(%s) compile_id=%d on method %s.%s(%s)",
2603             _method->method_holder()->external_name(),
2604             _method->name()->as_C_string(),
2605             _method->signature()->as_C_string(), compile_id(),
2606             method->method_holder()->external_name(),
2607             method->name()->as_C_string(),
2608             method->signature()->as_C_string()));
2609           if (TraceDependencies || LogCompilation)
2610             deps.log_dependency(dependee);
2611           return true;
2612         }
2613       }
2614     }
2615   }
2616   return false;
2617 }
2618 
2619 // Called from mark_for_deoptimization, when dependee is invalidated.
2620 bool nmethod::is_dependent_on_method(Method* dependee) {
2621   for (Dependencies::DepStream deps(this); deps.next(); ) {
2622     if (deps.type() != Dependencies::evol_method)
2623       continue;
2624     Method* method = deps.method_argument(0);
2625     if (method == dependee) return true;
2626   }
2627   return false;
2628 }
2629 
2630 
2631 bool nmethod::is_patchable_at(address instr_addr) {
2632   assert(insts_contains(instr_addr), "wrong nmethod used");
2633   if (is_zombie()) {
2634     // a zombie may never be patched
2635     return false;
2636   }
2637   return true;
2638 }
2639 
2640 
2641 address nmethod::continuation_for_implicit_exception(address pc) {
2642   // Exception happened outside inline-cache check code => we are inside
2643   // an active nmethod => use cpc to determine a return address
2644   int exception_offset = pc - code_begin();
2645   int cont_offset = ImplicitExceptionTable(this).at( exception_offset );
2646 #ifdef ASSERT
2647   if (cont_offset == 0) {
2648     Thread* thread = Thread::current();
2649     ResetNoHandleMark rnm; // Might be called from LEAF/QUICK ENTRY
2650     HandleMark hm(thread);
2651     ResourceMark rm(thread);
2652     CodeBlob* cb = CodeCache::find_blob(pc);
2653     assert(cb != NULL && cb == this, "");
2654     ttyLocker ttyl;
2655     tty->print_cr("implicit exception happened at " INTPTR_FORMAT, p2i(pc));
2656     print();
2657     method()->print_codes();
2658     print_code();
2659     print_pcs();
2660   }
2661 #endif
2662   if (cont_offset == 0) {
2663     // Let the normal error handling report the exception
2664     return NULL;
2665   }
2666   return code_begin() + cont_offset;
2667 }
2668 
2669 
2670 
2671 void nmethod_init() {
2672   // make sure you didn't forget to adjust the filler fields
2673   assert(sizeof(nmethod) % oopSize == 0, "nmethod size must be multiple of a word");
2674 }
2675 
2676 
2677 //-------------------------------------------------------------------------------------------
2678 
2679 
2680 // QQQ might we make this work from a frame??
2681 nmethodLocker::nmethodLocker(address pc) {
2682   CodeBlob* cb = CodeCache::find_blob(pc);
2683   guarantee(cb != NULL && cb->is_nmethod(), "bad pc for a nmethod found");
2684   _nm = (nmethod*)cb;
2685   lock_nmethod(_nm);
2686 }
2687 
2688 // Only JvmtiDeferredEvent::compiled_method_unload_event()
2689 // should pass zombie_ok == true.
2690 void nmethodLocker::lock_nmethod(nmethod* nm, bool zombie_ok) {
2691   if (nm == NULL)  return;
2692   Atomic::inc(&nm->_lock_count);
2693   assert(zombie_ok || !nm->is_zombie(), "cannot lock a zombie method");
2694 }
2695 
2696 void nmethodLocker::unlock_nmethod(nmethod* nm) {
2697   if (nm == NULL)  return;
2698   Atomic::dec(&nm->_lock_count);
2699   assert(nm->_lock_count >= 0, "unmatched nmethod lock/unlock");
2700 }
2701 
2702 // -----------------------------------------------------------------------------
2703 // nmethod::get_deopt_original_pc
2704 //
2705 // Return the original PC for the given PC if:
2706 // (a) the given PC belongs to a nmethod and
2707 // (b) it is a deopt PC
2708 address nmethod::get_deopt_original_pc(const frame* fr) {
2709   if (fr->cb() == NULL)  return NULL;
2710 
2711   nmethod* nm = fr->cb()->as_nmethod_or_null();
2712   if (nm != NULL && nm->is_deopt_pc(fr->pc()))
2713     return nm->get_original_pc(fr);
2714 
2715   return NULL;
2716 }
2717 
2718 
2719 // -----------------------------------------------------------------------------
2720 // MethodHandle
2721 
2722 bool nmethod::is_method_handle_return(address return_pc) {
2723   if (!has_method_handle_invokes())  return false;
2724   PcDesc* pd = pc_desc_at(return_pc);
2725   if (pd == NULL)
2726     return false;
2727   return pd->is_method_handle_invoke();
2728 }
2729 
2730 
2731 // -----------------------------------------------------------------------------
2732 // Verification
2733 
2734 class VerifyOopsClosure: public OopClosure {
2735   nmethod* _nm;
2736   bool     _ok;
2737 public:
2738   VerifyOopsClosure(nmethod* nm) : _nm(nm), _ok(true) { }
2739   bool ok() { return _ok; }
2740   virtual void do_oop(oop* p) {
2741     if ((*p) == NULL || (*p)->is_oop())  return;
2742     if (_ok) {
2743       _nm->print_nmethod(true);
2744       _ok = false;
2745     }
2746     tty->print_cr("*** non-oop " PTR_FORMAT " found at " PTR_FORMAT " (offset %d)",
2747                   p2i(*p), p2i(p), (int)((intptr_t)p - (intptr_t)_nm));
2748   }
2749   virtual void do_oop(narrowOop* p) { ShouldNotReachHere(); }
2750 };
2751 
2752 void nmethod::verify() {
2753 
2754   // Hmm. OSR methods can be deopted but not marked as zombie or not_entrant
2755   // seems odd.
2756 
2757   if (is_zombie() || is_not_entrant() || is_unloaded())
2758     return;
2759 
2760   // Make sure all the entry points are correctly aligned for patching.
2761   NativeJump::check_verified_entry_alignment(entry_point(), verified_entry_point());
2762 
2763   // assert(method()->is_oop(), "must be valid");
2764 
2765   ResourceMark rm;
2766 
2767   if (!CodeCache::contains(this)) {
2768     fatal("nmethod at " INTPTR_FORMAT " not in zone", p2i(this));
2769   }
2770 
2771   if(is_native_method() )
2772     return;
2773 
2774   nmethod* nm = CodeCache::find_nmethod(verified_entry_point());
2775   if (nm != this) {
2776     fatal("findNMethod did not find this nmethod (" INTPTR_FORMAT ")", p2i(this));
2777   }
2778 
2779   for (PcDesc* p = scopes_pcs_begin(); p < scopes_pcs_end(); p++) {
2780     if (! p->verify(this)) {
2781       tty->print_cr("\t\tin nmethod at " INTPTR_FORMAT " (pcs)", p2i(this));
2782     }
2783   }
2784 
2785   VerifyOopsClosure voc(this);
2786   oops_do(&voc);
2787   assert(voc.ok(), "embedded oops must be OK");
2788   verify_scavenge_root_oops();
2789 
2790   verify_scopes();
2791 }
2792 
2793 
2794 void nmethod::verify_interrupt_point(address call_site) {
2795   // Verify IC only when nmethod installation is finished.
2796   bool is_installed = (method()->code() == this) // nmethod is in state 'in_use' and installed
2797                       || !this->is_in_use();     // nmethod is installed, but not in 'in_use' state
2798   if (is_installed) {
2799     Thread *cur = Thread::current();
2800     if (CompiledIC_lock->owner() == cur ||
2801         ((cur->is_VM_thread() || cur->is_ConcurrentGC_thread()) &&
2802          SafepointSynchronize::is_at_safepoint())) {
2803       CompiledIC_at(this, call_site);
2804       CHECK_UNHANDLED_OOPS_ONLY(Thread::current()->clear_unhandled_oops());
2805     } else {
2806       MutexLocker ml_verify (CompiledIC_lock);
2807       CompiledIC_at(this, call_site);
2808     }
2809   }
2810 
2811   PcDesc* pd = pc_desc_at(nativeCall_at(call_site)->return_address());
2812   assert(pd != NULL, "PcDesc must exist");
2813   for (ScopeDesc* sd = new ScopeDesc(this, pd->scope_decode_offset(),
2814                                      pd->obj_decode_offset(), pd->should_reexecute(), pd->rethrow_exception(),
2815                                      pd->return_oop());
2816        !sd->is_top(); sd = sd->sender()) {
2817     sd->verify();
2818   }
2819 }
2820 
2821 void nmethod::verify_scopes() {
2822   if( !method() ) return;       // Runtime stubs have no scope
2823   if (method()->is_native()) return; // Ignore stub methods.
2824   // iterate through all interrupt point
2825   // and verify the debug information is valid.
2826   RelocIterator iter((nmethod*)this);
2827   while (iter.next()) {
2828     address stub = NULL;
2829     switch (iter.type()) {
2830       case relocInfo::virtual_call_type:
2831         verify_interrupt_point(iter.addr());
2832         break;
2833       case relocInfo::opt_virtual_call_type:
2834         stub = iter.opt_virtual_call_reloc()->static_stub();
2835         verify_interrupt_point(iter.addr());
2836         break;
2837       case relocInfo::static_call_type:
2838         stub = iter.static_call_reloc()->static_stub();
2839         //verify_interrupt_point(iter.addr());
2840         break;
2841       case relocInfo::runtime_call_type:
2842         address destination = iter.reloc()->value();
2843         // Right now there is no way to find out which entries support
2844         // an interrupt point.  It would be nice if we had this
2845         // information in a table.
2846         break;
2847     }
2848     assert(stub == NULL || stub_contains(stub), "static call stub outside stub section");
2849   }
2850 }
2851 
2852 
2853 // -----------------------------------------------------------------------------
2854 // Non-product code
2855 #ifndef PRODUCT
2856 
2857 class DebugScavengeRoot: public OopClosure {
2858   nmethod* _nm;
2859   bool     _ok;
2860 public:
2861   DebugScavengeRoot(nmethod* nm) : _nm(nm), _ok(true) { }
2862   bool ok() { return _ok; }
2863   virtual void do_oop(oop* p) {
2864     if ((*p) == NULL || !(*p)->is_scavengable())  return;
2865     if (_ok) {
2866       _nm->print_nmethod(true);
2867       _ok = false;
2868     }
2869     tty->print_cr("*** scavengable oop " PTR_FORMAT " found at " PTR_FORMAT " (offset %d)",
2870                   p2i(*p), p2i(p), (int)((intptr_t)p - (intptr_t)_nm));
2871     (*p)->print();
2872   }
2873   virtual void do_oop(narrowOop* p) { ShouldNotReachHere(); }
2874 };
2875 
2876 void nmethod::verify_scavenge_root_oops() {
2877   if (UseG1GC) {
2878     return;
2879   }
2880 
2881   if (!on_scavenge_root_list()) {
2882     // Actually look inside, to verify the claim that it's clean.
2883     DebugScavengeRoot debug_scavenge_root(this);
2884     oops_do(&debug_scavenge_root);
2885     if (!debug_scavenge_root.ok())
2886       fatal("found an unadvertised bad scavengable oop in the code cache");
2887   }
2888   assert(scavenge_root_not_marked(), "");
2889 }
2890 
2891 #endif // PRODUCT
2892 
2893 // Printing operations
2894 
2895 void nmethod::print() const {
2896   ResourceMark rm;
2897   ttyLocker ttyl;   // keep the following output all in one block
2898 
2899   tty->print("Compiled method ");
2900 
2901   if (is_compiled_by_c1()) {
2902     tty->print("(c1) ");
2903   } else if (is_compiled_by_c2()) {
2904     tty->print("(c2) ");
2905   } else if (is_compiled_by_shark()) {
2906     tty->print("(shark) ");
2907   } else if (is_compiled_by_jvmci()) {
2908     tty->print("(JVMCI) ");
2909   } else {
2910     tty->print("(nm) ");
2911   }
2912 
2913   print_on(tty, NULL);
2914 
2915   if (WizardMode) {
2916     tty->print("((nmethod*) " INTPTR_FORMAT ") ", p2i(this));
2917     tty->print(" for method " INTPTR_FORMAT , p2i(method()));
2918     tty->print(" { ");
2919     if (is_in_use())      tty->print("in_use ");
2920     if (is_not_entrant()) tty->print("not_entrant ");
2921     if (is_zombie())      tty->print("zombie ");
2922     if (is_unloaded())    tty->print("unloaded ");
2923     if (on_scavenge_root_list())  tty->print("scavenge_root ");
2924     tty->print_cr("}:");
2925   }
2926   if (size              () > 0) tty->print_cr(" total in heap  [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
2927                                               p2i(this),
2928                                               p2i(this) + size(),
2929                                               size());
2930   if (relocation_size   () > 0) tty->print_cr(" relocation     [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
2931                                               p2i(relocation_begin()),
2932                                               p2i(relocation_end()),
2933                                               relocation_size());
2934   if (consts_size       () > 0) tty->print_cr(" constants      [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
2935                                               p2i(consts_begin()),
2936                                               p2i(consts_end()),
2937                                               consts_size());
2938   if (insts_size        () > 0) tty->print_cr(" main code      [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
2939                                               p2i(insts_begin()),
2940                                               p2i(insts_end()),
2941                                               insts_size());
2942   if (stub_size         () > 0) tty->print_cr(" stub code      [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
2943                                               p2i(stub_begin()),
2944                                               p2i(stub_end()),
2945                                               stub_size());
2946   if (oops_size         () > 0) tty->print_cr(" oops           [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
2947                                               p2i(oops_begin()),
2948                                               p2i(oops_end()),
2949                                               oops_size());
2950   if (metadata_size      () > 0) tty->print_cr(" metadata       [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
2951                                               p2i(metadata_begin()),
2952                                               p2i(metadata_end()),
2953                                               metadata_size());
2954   if (scopes_data_size  () > 0) tty->print_cr(" scopes data    [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
2955                                               p2i(scopes_data_begin()),
2956                                               p2i(scopes_data_end()),
2957                                               scopes_data_size());
2958   if (scopes_pcs_size   () > 0) tty->print_cr(" scopes pcs     [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
2959                                               p2i(scopes_pcs_begin()),
2960                                               p2i(scopes_pcs_end()),
2961                                               scopes_pcs_size());
2962   if (dependencies_size () > 0) tty->print_cr(" dependencies   [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
2963                                               p2i(dependencies_begin()),
2964                                               p2i(dependencies_end()),
2965                                               dependencies_size());
2966   if (handler_table_size() > 0) tty->print_cr(" handler table  [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
2967                                               p2i(handler_table_begin()),
2968                                               p2i(handler_table_end()),
2969                                               handler_table_size());
2970   if (nul_chk_table_size() > 0) tty->print_cr(" nul chk table  [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
2971                                               p2i(nul_chk_table_begin()),
2972                                               p2i(nul_chk_table_end()),
2973                                               nul_chk_table_size());
2974 }
2975 
2976 #ifndef PRODUCT
2977 
2978 void nmethod::print_scopes() {
2979   // Find the first pc desc for all scopes in the code and print it.
2980   ResourceMark rm;
2981   for (PcDesc* p = scopes_pcs_begin(); p < scopes_pcs_end(); p++) {
2982     if (p->scope_decode_offset() == DebugInformationRecorder::serialized_null)
2983       continue;
2984 
2985     ScopeDesc* sd = scope_desc_at(p->real_pc(this));
2986     while (sd != NULL) {
2987       sd->print_on(tty, p);
2988       sd = sd->sender();
2989     }
2990   }
2991 }
2992 
2993 void nmethod::print_dependencies() {
2994   ResourceMark rm;
2995   ttyLocker ttyl;   // keep the following output all in one block
2996   tty->print_cr("Dependencies:");
2997   for (Dependencies::DepStream deps(this); deps.next(); ) {
2998     deps.print_dependency();
2999     Klass* ctxk = deps.context_type();
3000     if (ctxk != NULL) {
3001       if (ctxk->is_instance_klass() && InstanceKlass::cast(ctxk)->is_dependent_nmethod(this)) {
3002         tty->print_cr("   [nmethod<=klass]%s", ctxk->external_name());
3003       }
3004     }
3005     deps.log_dependency();  // put it into the xml log also
3006   }
3007 }
3008 
3009 
3010 void nmethod::print_relocations() {
3011   ResourceMark m;       // in case methods get printed via the debugger
3012   tty->print_cr("relocations:");
3013   RelocIterator iter(this);
3014   iter.print();
3015   if (UseRelocIndex) {
3016     jint* index_end   = (jint*)relocation_end() - 1;
3017     jint  index_size  = *index_end;
3018     jint* index_start = (jint*)( (address)index_end - index_size );
3019     tty->print_cr("    index @" INTPTR_FORMAT ": index_size=%d", p2i(index_start), index_size);
3020     if (index_size > 0) {
3021       jint* ip;
3022       for (ip = index_start; ip+2 <= index_end; ip += 2)
3023         tty->print_cr("  (%d %d) addr=" INTPTR_FORMAT " @" INTPTR_FORMAT,
3024                       ip[0],
3025                       ip[1],
3026                       p2i(header_end()+ip[0]),
3027                       p2i(relocation_begin()-1+ip[1]));
3028       for (; ip < index_end; ip++)
3029         tty->print_cr("  (%d ?)", ip[0]);
3030       tty->print_cr("          @" INTPTR_FORMAT ": index_size=%d", p2i(ip), *ip);
3031       ip++;
3032       tty->print_cr("reloc_end @" INTPTR_FORMAT ":", p2i(ip));
3033     }
3034   }
3035 }
3036 
3037 
3038 void nmethod::print_pcs() {
3039   ResourceMark m;       // in case methods get printed via debugger
3040   tty->print_cr("pc-bytecode offsets:");
3041   for (PcDesc* p = scopes_pcs_begin(); p < scopes_pcs_end(); p++) {
3042     p->print(this);
3043   }
3044 }
3045 
3046 void nmethod::print_recorded_oops() {
3047   tty->print_cr("Recorded oops:");
3048   for (int i = 0; i < oops_count(); i++) {
3049     oop o = oop_at(i);
3050     tty->print("#%3d: " INTPTR_FORMAT " ", i, p2i(o));
3051     if (o == (oop)Universe::non_oop_word()) {
3052       tty->print("non-oop word");
3053     } else {
3054       o->print_value();
3055     }
3056     tty->cr();
3057   }
3058 }
3059 
3060 void nmethod::print_recorded_metadata() {
3061   tty->print_cr("Recorded metadata:");
3062   for (int i = 0; i < metadata_count(); i++) {
3063     Metadata* m = metadata_at(i);
3064     tty->print("#%3d: " INTPTR_FORMAT " ", i, p2i(m));
3065     if (m == (Metadata*)Universe::non_oop_word()) {
3066       tty->print("non-metadata word");
3067     } else {
3068       m->print_value_on_maybe_null(tty);
3069     }
3070     tty->cr();
3071   }
3072 }
3073 
3074 #endif // PRODUCT
3075 
3076 const char* nmethod::reloc_string_for(u_char* begin, u_char* end) {
3077   RelocIterator iter(this, begin, end);
3078   bool have_one = false;
3079   while (iter.next()) {
3080     have_one = true;
3081     switch (iter.type()) {
3082         case relocInfo::none:                  return "no_reloc";
3083         case relocInfo::oop_type: {
3084           stringStream st;
3085           oop_Relocation* r = iter.oop_reloc();
3086           oop obj = r->oop_value();
3087           st.print("oop(");
3088           if (obj == NULL) st.print("NULL");
3089           else obj->print_value_on(&st);
3090           st.print(")");
3091           return st.as_string();
3092         }
3093         case relocInfo::metadata_type: {
3094           stringStream st;
3095           metadata_Relocation* r = iter.metadata_reloc();
3096           Metadata* obj = r->metadata_value();
3097           st.print("metadata(");
3098           if (obj == NULL) st.print("NULL");
3099           else obj->print_value_on(&st);
3100           st.print(")");
3101           return st.as_string();
3102         }
3103         case relocInfo::runtime_call_type: {
3104           stringStream st;
3105           st.print("runtime_call");
3106           runtime_call_Relocation* r = iter.runtime_call_reloc();
3107           address dest = r->destination();
3108           CodeBlob* cb = CodeCache::find_blob(dest);
3109           if (cb != NULL) {
3110             st.print(" %s", cb->name());
3111           } else {
3112             ResourceMark rm;
3113             const int buflen = 1024;
3114             char* buf = NEW_RESOURCE_ARRAY(char, buflen);
3115             int offset;
3116             if (os::dll_address_to_function_name(dest, buf, buflen, &offset)) {
3117               st.print(" %s", buf);
3118               if (offset != 0) {
3119                 st.print("+%d", offset);
3120               }
3121             }
3122           }
3123           return st.as_string();
3124         }
3125         case relocInfo::virtual_call_type: {
3126           stringStream st;
3127           st.print_raw("virtual_call");
3128           virtual_call_Relocation* r = iter.virtual_call_reloc();
3129           Method* m = r->method_value();
3130           if (m != NULL) {
3131             assert(m->is_method(), "");
3132             m->print_short_name(&st);
3133           }
3134           return st.as_string();
3135         }
3136         case relocInfo::opt_virtual_call_type: {
3137           stringStream st;
3138           st.print_raw("optimized virtual_call");
3139           opt_virtual_call_Relocation* r = iter.opt_virtual_call_reloc();
3140           Method* m = r->method_value();
3141           if (m != NULL) {
3142             assert(m->is_method(), "");
3143             m->print_short_name(&st);
3144           }
3145           return st.as_string();
3146         }
3147         case relocInfo::static_call_type: {
3148           stringStream st;
3149           st.print_raw("static_call");
3150           static_call_Relocation* r = iter.static_call_reloc();
3151           Method* m = r->method_value();
3152           if (m != NULL) {
3153             assert(m->is_method(), "");
3154             m->print_short_name(&st);
3155           }
3156           return st.as_string();
3157         }
3158         case relocInfo::static_stub_type:      return "static_stub";
3159         case relocInfo::external_word_type:    return "external_word";
3160         case relocInfo::internal_word_type:    return "internal_word";
3161         case relocInfo::section_word_type:     return "section_word";
3162         case relocInfo::poll_type:             return "poll";
3163         case relocInfo::poll_return_type:      return "poll_return";
3164         case relocInfo::type_mask:             return "type_bit_mask";
3165     }
3166   }
3167   return have_one ? "other" : NULL;
3168 }
3169 
3170 // Return a the last scope in (begin..end]
3171 ScopeDesc* nmethod::scope_desc_in(address begin, address end) {
3172   PcDesc* p = pc_desc_near(begin+1);
3173   if (p != NULL && p->real_pc(this) <= end) {
3174     return new ScopeDesc(this, p->scope_decode_offset(),
3175                          p->obj_decode_offset(), p->should_reexecute(), p->rethrow_exception(),
3176                          p->return_oop());
3177   }
3178   return NULL;
3179 }
3180 
3181 void nmethod::print_nmethod_labels(outputStream* stream, address block_begin) const {
3182   if (block_begin == entry_point())             stream->print_cr("[Entry Point]");
3183   if (block_begin == verified_entry_point())    stream->print_cr("[Verified Entry Point]");
3184   if (JVMCI_ONLY(_exception_offset >= 0 &&) block_begin == exception_begin())         stream->print_cr("[Exception Handler]");
3185   if (block_begin == stub_begin())              stream->print_cr("[Stub Code]");
3186   if (JVMCI_ONLY(_deoptimize_offset >= 0 &&) block_begin == deopt_handler_begin())     stream->print_cr("[Deopt Handler Code]");
3187 
3188   if (has_method_handle_invokes())
3189     if (block_begin == deopt_mh_handler_begin())  stream->print_cr("[Deopt MH Handler Code]");
3190 
3191   if (block_begin == consts_begin())            stream->print_cr("[Constants]");
3192 
3193   if (block_begin == entry_point()) {
3194     methodHandle m = method();
3195     if (m.not_null()) {
3196       stream->print("  # ");
3197       m->print_value_on(stream);
3198       stream->cr();
3199     }
3200     if (m.not_null() && !is_osr_method()) {
3201       ResourceMark rm;
3202       int sizeargs = m->size_of_parameters();
3203       BasicType* sig_bt = NEW_RESOURCE_ARRAY(BasicType, sizeargs);
3204       VMRegPair* regs   = NEW_RESOURCE_ARRAY(VMRegPair, sizeargs);
3205       {
3206         int sig_index = 0;
3207         if (!m->is_static())
3208           sig_bt[sig_index++] = T_OBJECT; // 'this'
3209         for (SignatureStream ss(m->signature()); !ss.at_return_type(); ss.next()) {
3210           BasicType t = ss.type();
3211           sig_bt[sig_index++] = t;
3212           if (type2size[t] == 2) {
3213             sig_bt[sig_index++] = T_VOID;
3214           } else {
3215             assert(type2size[t] == 1, "size is 1 or 2");
3216           }
3217         }
3218         assert(sig_index == sizeargs, "");
3219       }
3220       const char* spname = "sp"; // make arch-specific?
3221       intptr_t out_preserve = SharedRuntime::java_calling_convention(sig_bt, regs, sizeargs, false);
3222       int stack_slot_offset = this->frame_size() * wordSize;
3223       int tab1 = 14, tab2 = 24;
3224       int sig_index = 0;
3225       int arg_index = (m->is_static() ? 0 : -1);
3226       bool did_old_sp = false;
3227       for (SignatureStream ss(m->signature()); !ss.at_return_type(); ) {
3228         bool at_this = (arg_index == -1);
3229         bool at_old_sp = false;
3230         BasicType t = (at_this ? T_OBJECT : ss.type());
3231         assert(t == sig_bt[sig_index], "sigs in sync");
3232         if (at_this)
3233           stream->print("  # this: ");
3234         else
3235           stream->print("  # parm%d: ", arg_index);
3236         stream->move_to(tab1);
3237         VMReg fst = regs[sig_index].first();
3238         VMReg snd = regs[sig_index].second();
3239         if (fst->is_reg()) {
3240           stream->print("%s", fst->name());
3241           if (snd->is_valid())  {
3242             stream->print(":%s", snd->name());
3243           }
3244         } else if (fst->is_stack()) {
3245           int offset = fst->reg2stack() * VMRegImpl::stack_slot_size + stack_slot_offset;
3246           if (offset == stack_slot_offset)  at_old_sp = true;
3247           stream->print("[%s+0x%x]", spname, offset);
3248         } else {
3249           stream->print("reg%d:%d??", (int)(intptr_t)fst, (int)(intptr_t)snd);
3250         }
3251         stream->print(" ");
3252         stream->move_to(tab2);
3253         stream->print("= ");
3254         if (at_this) {
3255           m->method_holder()->print_value_on(stream);
3256         } else {
3257           bool did_name = false;
3258           if (!at_this && ss.is_object()) {
3259             Symbol* name = ss.as_symbol_or_null();
3260             if (name != NULL) {
3261               name->print_value_on(stream);
3262               did_name = true;
3263             }
3264           }
3265           if (!did_name)
3266             stream->print("%s", type2name(t));
3267         }
3268         if (at_old_sp) {
3269           stream->print("  (%s of caller)", spname);
3270           did_old_sp = true;
3271         }
3272         stream->cr();
3273         sig_index += type2size[t];
3274         arg_index += 1;
3275         if (!at_this)  ss.next();
3276       }
3277       if (!did_old_sp) {
3278         stream->print("  # ");
3279         stream->move_to(tab1);
3280         stream->print("[%s+0x%x]", spname, stack_slot_offset);
3281         stream->print("  (%s of caller)", spname);
3282         stream->cr();
3283       }
3284     }
3285   }
3286 }
3287 
3288 void nmethod::print_code_comment_on(outputStream* st, int column, u_char* begin, u_char* end) {
3289   // First, find an oopmap in (begin, end].
3290   // We use the odd half-closed interval so that oop maps and scope descs
3291   // which are tied to the byte after a call are printed with the call itself.
3292   address base = code_begin();
3293   ImmutableOopMapSet* oms = oop_maps();
3294   if (oms != NULL) {
3295     for (int i = 0, imax = oms->count(); i < imax; i++) {
3296       const ImmutableOopMapPair* pair = oms->pair_at(i);
3297       const ImmutableOopMap* om = pair->get_from(oms);
3298       address pc = base + pair->pc_offset();
3299       if (pc > begin) {
3300         if (pc <= end) {
3301           st->move_to(column);
3302           st->print("; ");
3303           om->print_on(st);
3304         }
3305         break;
3306       }
3307     }
3308   }
3309 
3310   // Print any debug info present at this pc.
3311   ScopeDesc* sd  = scope_desc_in(begin, end);
3312   if (sd != NULL) {
3313     st->move_to(column);
3314     if (sd->bci() == SynchronizationEntryBCI) {
3315       st->print(";*synchronization entry");
3316     } else {
3317       if (sd->method() == NULL) {
3318         st->print("method is NULL");
3319       } else if (sd->method()->is_native()) {
3320         st->print("method is native");
3321       } else {
3322         Bytecodes::Code bc = sd->method()->java_code_at(sd->bci());
3323         st->print(";*%s", Bytecodes::name(bc));
3324         switch (bc) {
3325         case Bytecodes::_invokevirtual:
3326         case Bytecodes::_invokespecial:
3327         case Bytecodes::_invokestatic:
3328         case Bytecodes::_invokeinterface:
3329           {
3330             Bytecode_invoke invoke(sd->method(), sd->bci());
3331             st->print(" ");
3332             if (invoke.name() != NULL)
3333               invoke.name()->print_symbol_on(st);
3334             else
3335               st->print("<UNKNOWN>");
3336             break;
3337           }
3338         case Bytecodes::_getfield:
3339         case Bytecodes::_putfield:
3340         case Bytecodes::_getstatic:
3341         case Bytecodes::_putstatic:
3342           {
3343             Bytecode_field field(sd->method(), sd->bci());
3344             st->print(" ");
3345             if (field.name() != NULL)
3346               field.name()->print_symbol_on(st);
3347             else
3348               st->print("<UNKNOWN>");
3349           }
3350         }
3351       }
3352       st->print(" {reexecute=%d rethrow=%d return_oop=%d}", sd->should_reexecute(), sd->rethrow_exception(), sd->return_oop());
3353     }
3354 
3355     // Print all scopes
3356     for (;sd != NULL; sd = sd->sender()) {
3357       st->move_to(column);
3358       st->print("; -");
3359       if (sd->method() == NULL) {
3360         st->print("method is NULL");
3361       } else {
3362         sd->method()->print_short_name(st);
3363       }
3364       int lineno = sd->method()->line_number_from_bci(sd->bci());
3365       if (lineno != -1) {
3366         st->print("@%d (line %d)", sd->bci(), lineno);
3367       } else {
3368         st->print("@%d", sd->bci());
3369       }
3370       st->cr();
3371     }
3372   }
3373 
3374   // Print relocation information
3375   const char* str = reloc_string_for(begin, end);
3376   if (str != NULL) {
3377     if (sd != NULL) st->cr();
3378     st->move_to(column);
3379     st->print(";   {%s}", str);
3380   }
3381   int cont_offset = ImplicitExceptionTable(this).at(begin - code_begin());
3382   if (cont_offset != 0) {
3383     st->move_to(column);
3384     st->print("; implicit exception: dispatches to " INTPTR_FORMAT, p2i(code_begin() + cont_offset));
3385   }
3386 
3387 }
3388 
3389 #ifndef PRODUCT
3390 
3391 void nmethod::print_value_on(outputStream* st) const {
3392   st->print("nmethod");
3393   print_on(st, NULL);
3394 }
3395 
3396 void nmethod::print_calls(outputStream* st) {
3397   RelocIterator iter(this);
3398   while (iter.next()) {
3399     switch (iter.type()) {
3400     case relocInfo::virtual_call_type:
3401     case relocInfo::opt_virtual_call_type: {
3402       VerifyMutexLocker mc(CompiledIC_lock);
3403       CompiledIC_at(&iter)->print();
3404       break;
3405     }
3406     case relocInfo::static_call_type:
3407       st->print_cr("Static call at " INTPTR_FORMAT, p2i(iter.reloc()->addr()));
3408       compiledStaticCall_at(iter.reloc())->print();
3409       break;
3410     }
3411   }
3412 }
3413 
3414 void nmethod::print_handler_table() {
3415   ExceptionHandlerTable(this).print();
3416 }
3417 
3418 void nmethod::print_nul_chk_table() {
3419   ImplicitExceptionTable(this).print(code_begin());
3420 }
3421 
3422 void nmethod::print_statistics() {
3423   ttyLocker ttyl;
3424   if (xtty != NULL)  xtty->head("statistics type='nmethod'");
3425   native_nmethod_stats.print_native_nmethod_stats();
3426 #ifdef COMPILER1
3427   c1_java_nmethod_stats.print_nmethod_stats("C1");
3428 #endif
3429 #ifdef COMPILER2
3430   c2_java_nmethod_stats.print_nmethod_stats("C2");
3431 #endif
3432 #if INCLUDE_JVMCI
3433   jvmci_java_nmethod_stats.print_nmethod_stats("JVMCI");
3434 #endif
3435 #ifdef SHARK
3436   shark_java_nmethod_stats.print_nmethod_stats("Shark");
3437 #endif
3438   unknown_java_nmethod_stats.print_nmethod_stats("Unknown");
3439   DebugInformationRecorder::print_statistics();
3440 #ifndef PRODUCT
3441   pc_nmethod_stats.print_pc_stats();
3442 #endif
3443   Dependencies::print_statistics();
3444   if (xtty != NULL)  xtty->tail("statistics");
3445 }
3446 
3447 #endif // !PRODUCT
3448 
3449 #if INCLUDE_JVMCI
3450 void nmethod::clear_jvmci_installed_code() {
3451   // write_ref_method_pre/post can only be safely called at a
3452   // safepoint or while holding the CodeCache_lock
3453   assert(CodeCache_lock->is_locked() ||
3454          SafepointSynchronize::is_at_safepoint(), "should be performed under a lock for consistency");
3455   if (_jvmci_installed_code != NULL) {
3456     // This must be done carefully to maintain nmethod remembered sets properly
3457     BarrierSet* bs = Universe::heap()->barrier_set();
3458     bs->write_ref_nmethod_pre(&_jvmci_installed_code, this);
3459     _jvmci_installed_code = NULL;
3460     bs->write_ref_nmethod_post(&_jvmci_installed_code, this);
3461   }
3462 }
3463 
3464 void nmethod::maybe_invalidate_installed_code() {
3465   assert(Patching_lock->is_locked() ||
3466          SafepointSynchronize::is_at_safepoint(), "should be performed under a lock for consistency");
3467   oop installed_code = jvmci_installed_code();
3468   if (installed_code != NULL) {
3469     nmethod* nm = (nmethod*)InstalledCode::address(installed_code);
3470     if (nm == NULL || nm != this) {
3471       // The link has been broken or the InstalledCode instance is
3472       // associated with another nmethod so do nothing.
3473       return;
3474     }
3475     if (!is_alive()) {
3476       // Break the link between nmethod and InstalledCode such that the nmethod
3477       // can subsequently be flushed safely.  The link must be maintained while
3478       // the method could have live activations since invalidateInstalledCode
3479       // might want to invalidate all existing activations.
3480       InstalledCode::set_address(installed_code, 0);
3481       InstalledCode::set_entryPoint(installed_code, 0);
3482     } else if (is_not_entrant()) {
3483       // Remove the entry point so any invocation will fail but keep
3484       // the address link around that so that existing activations can
3485       // be invalidated.
3486       InstalledCode::set_entryPoint(installed_code, 0);
3487     }
3488   }
3489 }
3490 
3491 void nmethod::invalidate_installed_code(Handle installedCode, TRAPS) {
3492   if (installedCode() == NULL) {
3493     THROW(vmSymbols::java_lang_NullPointerException());
3494   }
3495   jlong nativeMethod = InstalledCode::address(installedCode);
3496   nmethod* nm = (nmethod*)nativeMethod;
3497   if (nm == NULL) {
3498     // Nothing to do
3499     return;
3500   }
3501 
3502   nmethodLocker nml(nm);
3503 #ifdef ASSERT
3504   {
3505     MutexLockerEx pl(Patching_lock, Mutex::_no_safepoint_check_flag);
3506     // This relationship can only be checked safely under a lock
3507     assert(nm == NULL || !nm->is_alive() || nm->jvmci_installed_code() == installedCode(), "sanity check");
3508   }
3509 #endif
3510 
3511   if (nm->is_alive()) {
3512     // The nmethod state machinery maintains the link between the
3513     // HotSpotInstalledCode and nmethod* so as long as the nmethod appears to be
3514     // alive assume there is work to do and deoptimize the nmethod.
3515     nm->mark_for_deoptimization();
3516     VM_Deoptimize op;
3517     VMThread::execute(&op);
3518   }
3519 
3520   MutexLockerEx pl(Patching_lock, Mutex::_no_safepoint_check_flag);
3521   // Check that it's still associated with the same nmethod and break
3522   // the link if it is.
3523   if (InstalledCode::address(installedCode) == nativeMethod) {
3524     InstalledCode::set_address(installedCode, 0);
3525   }
3526 }
3527 
3528 char* nmethod::jvmci_installed_code_name(char* buf, size_t buflen) {
3529   if (!this->is_compiled_by_jvmci()) {
3530     return NULL;
3531   }
3532   oop installedCode = this->jvmci_installed_code();
3533   if (installedCode != NULL) {
3534     oop installedCodeName = NULL;
3535     if (installedCode->is_a(InstalledCode::klass())) {
3536       installedCodeName = InstalledCode::name(installedCode);
3537     }
3538     if (installedCodeName != NULL) {
3539       return java_lang_String::as_utf8_string(installedCodeName, buf, (int)buflen);
3540     } else {
3541       jio_snprintf(buf, buflen, "null");
3542       return buf;
3543     }
3544   }
3545   jio_snprintf(buf, buflen, "noInstalledCode");
3546   return buf;
3547 }
3548 #endif
3549 
3550 Method* nmethod::attached_method(address call_instr) {
3551   assert(code_contains(call_instr), "not part of the nmethod");
3552   RelocIterator iter(this, call_instr, call_instr + 1);
3553   while (iter.next()) {
3554     if (iter.addr() == call_instr) {
3555       switch(iter.type()) {
3556         case relocInfo::static_call_type:      return iter.static_call_reloc()->method_value();
3557         case relocInfo::opt_virtual_call_type: return iter.opt_virtual_call_reloc()->method_value();
3558         case relocInfo::virtual_call_type:     return iter.virtual_call_reloc()->method_value();
3559       }
3560     }
3561   }
3562   return NULL; // not found
3563 }
3564 
3565 Method* nmethod::attached_method_before_pc(address pc) {
3566   if (NativeCall::is_call_before(pc)) {
3567     NativeCall* ncall = nativeCall_before(pc);
3568     return attached_method(ncall->instruction_address());
3569   }
3570   return NULL; // not a call
3571 }
3572