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