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