1 /*
   2  * Copyright (c) 1997, 2025, 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 "asm/assembler.inline.hpp"
  26 #include "code/aotCodeCache.hpp"
  27 #include "code/codeCache.hpp"
  28 #include "code/compiledIC.hpp"
  29 #include "code/dependencies.hpp"
  30 #include "code/nativeInst.hpp"
  31 #include "code/nmethod.inline.hpp"
  32 #include "code/scopeDesc.hpp"
  33 #include "compiler/abstractCompiler.hpp"
  34 #include "compiler/compilationLog.hpp"
  35 #include "compiler/compileBroker.hpp"
  36 #include "compiler/compileLog.hpp"
  37 #include "compiler/compilerDirectives.hpp"
  38 #include "compiler/compilerOracle.hpp"
  39 #include "compiler/compileTask.hpp"
  40 #include "compiler/directivesParser.hpp"
  41 #include "compiler/disassembler.hpp"
  42 #include "compiler/oopMap.inline.hpp"
  43 #include "gc/shared/barrierSet.hpp"
  44 #include "gc/shared/barrierSetNMethod.hpp"
  45 #include "gc/shared/classUnloadingContext.hpp"
  46 #include "gc/shared/collectedHeap.hpp"
  47 #include "interpreter/bytecode.inline.hpp"
  48 #include "jvm.h"
  49 #include "logging/log.hpp"
  50 #include "logging/logStream.hpp"
  51 #include "memory/allocation.inline.hpp"
  52 #include "memory/resourceArea.hpp"
  53 #include "memory/universe.hpp"
  54 #include "oops/access.inline.hpp"
  55 #include "oops/klass.inline.hpp"
  56 #include "oops/method.inline.hpp"
  57 #include "oops/methodData.hpp"
  58 #include "oops/oop.inline.hpp"
  59 #include "oops/weakHandle.inline.hpp"
  60 #include "prims/jvmtiImpl.hpp"
  61 #include "prims/jvmtiThreadState.hpp"
  62 #include "prims/methodHandles.hpp"
  63 #include "runtime/atomicAccess.hpp"
  64 #include "runtime/continuation.hpp"
  65 #include "runtime/deoptimization.hpp"
  66 #include "runtime/flags/flagSetting.hpp"
  67 #include "runtime/frame.inline.hpp"
  68 #include "runtime/handles.inline.hpp"
  69 #include "runtime/jniHandles.inline.hpp"
  70 #include "runtime/orderAccess.hpp"
  71 #include "runtime/os.hpp"
  72 #include "runtime/safepointVerifiers.hpp"
  73 #include "runtime/serviceThread.hpp"
  74 #include "runtime/sharedRuntime.hpp"
  75 #include "runtime/signature.hpp"
  76 #include "runtime/threadWXSetters.inline.hpp"
  77 #include "runtime/vmThread.hpp"
  78 #include "utilities/align.hpp"
  79 #include "utilities/copy.hpp"
  80 #include "utilities/dtrace.hpp"
  81 #include "utilities/events.hpp"
  82 #include "utilities/globalDefinitions.hpp"
  83 #include "utilities/hashTable.hpp"
  84 #include "utilities/xmlstream.hpp"
  85 #if INCLUDE_JVMCI
  86 #include "jvmci/jvmciRuntime.hpp"
  87 #endif
  88 
  89 #ifdef DTRACE_ENABLED
  90 
  91 // Only bother with this argument setup if dtrace is available
  92 
  93 #define DTRACE_METHOD_UNLOAD_PROBE(method)                                \
  94   {                                                                       \
  95     Method* m = (method);                                                 \
  96     if (m != nullptr) {                                                   \
  97       Symbol* klass_name = m->klass_name();                               \
  98       Symbol* name = m->name();                                           \
  99       Symbol* signature = m->signature();                                 \
 100       HOTSPOT_COMPILED_METHOD_UNLOAD(                                     \
 101         (char *) klass_name->bytes(), klass_name->utf8_length(),          \
 102         (char *) name->bytes(), name->utf8_length(),                      \
 103         (char *) signature->bytes(), signature->utf8_length());           \
 104     }                                                                     \
 105   }
 106 
 107 #else //  ndef DTRACE_ENABLED
 108 
 109 #define DTRACE_METHOD_UNLOAD_PROBE(method)
 110 
 111 #endif
 112 
 113 // Cast from int value to narrow type
 114 #define CHECKED_CAST(result, T, thing)      \
 115   result = static_cast<T>(thing); \
 116   guarantee(static_cast<int>(result) == thing, "failed: %d != %d", static_cast<int>(result), thing);
 117 
 118 //---------------------------------------------------------------------------------
 119 // NMethod statistics
 120 // They are printed under various flags, including:
 121 //   PrintC1Statistics, PrintOptoStatistics, LogVMOutput, and LogCompilation.
 122 // (In the latter two cases, they like other stats are printed to the log only.)
 123 
 124 #ifndef PRODUCT
 125 // These variables are put into one block to reduce relocations
 126 // and make it simpler to print from the debugger.
 127 struct java_nmethod_stats_struct {
 128   uint nmethod_count;
 129   uint total_nm_size;
 130   uint total_immut_size;
 131   uint total_mut_size;
 132   uint relocation_size;
 133   uint consts_size;
 134   uint insts_size;
 135   uint stub_size;
 136   uint oops_size;
 137   uint metadata_size;
 138   uint dependencies_size;
 139   uint nul_chk_table_size;
 140   uint handler_table_size;
 141   uint scopes_pcs_size;
 142   uint scopes_data_size;
 143 #if INCLUDE_JVMCI
 144   uint speculations_size;
 145   uint jvmci_data_size;
 146 #endif
 147 
 148   void note_nmethod(nmethod* nm) {
 149     nmethod_count += 1;
 150     total_nm_size       += nm->size();
 151     total_immut_size    += nm->immutable_data_size();
 152     total_mut_size      += nm->mutable_data_size();
 153     relocation_size     += nm->relocation_size();
 154     consts_size         += nm->consts_size();
 155     insts_size          += nm->insts_size();
 156     stub_size           += nm->stub_size();
 157     oops_size           += nm->oops_size();
 158     metadata_size       += nm->metadata_size();
 159     scopes_data_size    += nm->scopes_data_size();
 160     scopes_pcs_size     += nm->scopes_pcs_size();
 161     dependencies_size   += nm->dependencies_size();
 162     handler_table_size  += nm->handler_table_size();
 163     nul_chk_table_size  += nm->nul_chk_table_size();
 164 #if INCLUDE_JVMCI
 165     speculations_size   += nm->speculations_size();
 166     jvmci_data_size     += nm->jvmci_data_size();
 167 #endif
 168   }
 169   void print_nmethod_stats(const char* name) {
 170     if (nmethod_count == 0)  return;
 171     tty->print_cr("Statistics for %u bytecoded nmethods for %s:", nmethod_count, name);
 172     uint total_size = total_nm_size + total_immut_size + total_mut_size;
 173     if (total_nm_size != 0) {
 174       tty->print_cr(" total size      = %u (100%%)", total_size);
 175       tty->print_cr(" in CodeCache    = %u (%f%%)", total_nm_size, (total_nm_size * 100.0f)/total_size);
 176     }
 177     uint header_size = (uint)(nmethod_count * sizeof(nmethod));
 178     if (nmethod_count != 0) {
 179       tty->print_cr("   header        = %u (%f%%)", header_size, (header_size * 100.0f)/total_nm_size);
 180     }
 181     if (consts_size != 0) {
 182       tty->print_cr("   constants     = %u (%f%%)", consts_size, (consts_size * 100.0f)/total_nm_size);
 183     }
 184     if (insts_size != 0) {
 185       tty->print_cr("   main code     = %u (%f%%)", insts_size, (insts_size * 100.0f)/total_nm_size);
 186     }
 187     if (stub_size != 0) {
 188       tty->print_cr("   stub code     = %u (%f%%)", stub_size, (stub_size * 100.0f)/total_nm_size);
 189     }
 190     if (oops_size != 0) {
 191       tty->print_cr("   oops          = %u (%f%%)", oops_size, (oops_size * 100.0f)/total_nm_size);
 192     }
 193     if (total_mut_size != 0) {
 194       tty->print_cr(" mutable data    = %u (%f%%)", total_mut_size, (total_mut_size * 100.0f)/total_size);
 195     }
 196     if (relocation_size != 0) {
 197       tty->print_cr("   relocation    = %u (%f%%)", relocation_size, (relocation_size * 100.0f)/total_mut_size);
 198     }
 199     if (metadata_size != 0) {
 200       tty->print_cr("   metadata      = %u (%f%%)", metadata_size, (metadata_size * 100.0f)/total_mut_size);
 201     }
 202 #if INCLUDE_JVMCI
 203     if (jvmci_data_size != 0) {
 204       tty->print_cr("   JVMCI data    = %u (%f%%)", jvmci_data_size, (jvmci_data_size * 100.0f)/total_mut_size);
 205     }
 206 #endif
 207     if (total_immut_size != 0) {
 208       tty->print_cr(" immutable data  = %u (%f%%)", total_immut_size, (total_immut_size * 100.0f)/total_size);
 209     }
 210     if (dependencies_size != 0) {
 211       tty->print_cr("   dependencies  = %u (%f%%)", dependencies_size, (dependencies_size * 100.0f)/total_immut_size);
 212     }
 213     if (nul_chk_table_size != 0) {
 214       tty->print_cr("   nul chk table = %u (%f%%)", nul_chk_table_size, (nul_chk_table_size * 100.0f)/total_immut_size);
 215     }
 216     if (handler_table_size != 0) {
 217       tty->print_cr("   handler table = %u (%f%%)", handler_table_size, (handler_table_size * 100.0f)/total_immut_size);
 218     }
 219     if (scopes_pcs_size != 0) {
 220       tty->print_cr("   scopes pcs    = %u (%f%%)", scopes_pcs_size, (scopes_pcs_size * 100.0f)/total_immut_size);
 221     }
 222     if (scopes_data_size != 0) {
 223       tty->print_cr("   scopes data   = %u (%f%%)", scopes_data_size, (scopes_data_size * 100.0f)/total_immut_size);
 224     }
 225 #if INCLUDE_JVMCI
 226     if (speculations_size != 0) {
 227       tty->print_cr("   speculations  = %u (%f%%)", speculations_size, (speculations_size * 100.0f)/total_immut_size);
 228     }
 229 #endif
 230   }
 231 };
 232 
 233 struct native_nmethod_stats_struct {
 234   uint native_nmethod_count;
 235   uint native_total_size;
 236   uint native_relocation_size;
 237   uint native_insts_size;
 238   uint native_oops_size;
 239   uint native_metadata_size;
 240   void note_native_nmethod(nmethod* nm) {
 241     native_nmethod_count += 1;
 242     native_total_size       += nm->size();
 243     native_relocation_size  += nm->relocation_size();
 244     native_insts_size       += nm->insts_size();
 245     native_oops_size        += nm->oops_size();
 246     native_metadata_size    += nm->metadata_size();
 247   }
 248   void print_native_nmethod_stats() {
 249     if (native_nmethod_count == 0)  return;
 250     tty->print_cr("Statistics for %u native nmethods:", native_nmethod_count);
 251     if (native_total_size != 0)       tty->print_cr(" N. total size  = %u", native_total_size);
 252     if (native_relocation_size != 0)  tty->print_cr(" N. relocation  = %u", native_relocation_size);
 253     if (native_insts_size != 0)       tty->print_cr(" N. main code   = %u", native_insts_size);
 254     if (native_oops_size != 0)        tty->print_cr(" N. oops        = %u", native_oops_size);
 255     if (native_metadata_size != 0)    tty->print_cr(" N. metadata    = %u", native_metadata_size);
 256   }
 257 };
 258 
 259 struct pc_nmethod_stats_struct {
 260   uint pc_desc_init;     // number of initialization of cache (= number of caches)
 261   uint pc_desc_queries;  // queries to nmethod::find_pc_desc
 262   uint pc_desc_approx;   // number of those which have approximate true
 263   uint pc_desc_repeats;  // number of _pc_descs[0] hits
 264   uint pc_desc_hits;     // number of LRU cache hits
 265   uint pc_desc_tests;    // total number of PcDesc examinations
 266   uint pc_desc_searches; // total number of quasi-binary search steps
 267   uint pc_desc_adds;     // number of LUR cache insertions
 268 
 269   void print_pc_stats() {
 270     tty->print_cr("PcDesc Statistics:  %u queries, %.2f comparisons per query",
 271                   pc_desc_queries,
 272                   (double)(pc_desc_tests + pc_desc_searches)
 273                   / pc_desc_queries);
 274     tty->print_cr("  caches=%d queries=%u/%u, hits=%u+%u, tests=%u+%u, adds=%u",
 275                   pc_desc_init,
 276                   pc_desc_queries, pc_desc_approx,
 277                   pc_desc_repeats, pc_desc_hits,
 278                   pc_desc_tests, pc_desc_searches, pc_desc_adds);
 279   }
 280 };
 281 
 282 #ifdef COMPILER1
 283 static java_nmethod_stats_struct c1_java_nmethod_stats;
 284 #endif
 285 #ifdef COMPILER2
 286 static java_nmethod_stats_struct c2_java_nmethod_stats;
 287 #endif
 288 #if INCLUDE_JVMCI
 289 static java_nmethod_stats_struct jvmci_java_nmethod_stats;
 290 #endif
 291 static java_nmethod_stats_struct unknown_java_nmethod_stats;
 292 
 293 static native_nmethod_stats_struct native_nmethod_stats;
 294 static pc_nmethod_stats_struct pc_nmethod_stats;
 295 
 296 static void note_java_nmethod(nmethod* nm) {
 297 #ifdef COMPILER1
 298   if (nm->is_compiled_by_c1()) {
 299     c1_java_nmethod_stats.note_nmethod(nm);
 300   } else
 301 #endif
 302 #ifdef COMPILER2
 303   if (nm->is_compiled_by_c2()) {
 304     c2_java_nmethod_stats.note_nmethod(nm);
 305   } else
 306 #endif
 307 #if INCLUDE_JVMCI
 308   if (nm->is_compiled_by_jvmci()) {
 309     jvmci_java_nmethod_stats.note_nmethod(nm);
 310   } else
 311 #endif
 312   {
 313     unknown_java_nmethod_stats.note_nmethod(nm);
 314   }
 315 }
 316 #endif // !PRODUCT
 317 
 318 //---------------------------------------------------------------------------------
 319 
 320 
 321 ExceptionCache::ExceptionCache(Handle exception, address pc, address handler) {
 322   assert(pc != nullptr, "Must be non null");
 323   assert(exception.not_null(), "Must be non null");
 324   assert(handler != nullptr, "Must be non null");
 325 
 326   _count = 0;
 327   _exception_type = exception->klass();
 328   _next = nullptr;
 329   _purge_list_next = nullptr;
 330 
 331   add_address_and_handler(pc,handler);
 332 }
 333 
 334 
 335 address ExceptionCache::match(Handle exception, address pc) {
 336   assert(pc != nullptr,"Must be non null");
 337   assert(exception.not_null(),"Must be non null");
 338   if (exception->klass() == exception_type()) {
 339     return (test_address(pc));
 340   }
 341 
 342   return nullptr;
 343 }
 344 
 345 
 346 bool ExceptionCache::match_exception_with_space(Handle exception) {
 347   assert(exception.not_null(),"Must be non null");
 348   if (exception->klass() == exception_type() && count() < cache_size) {
 349     return true;
 350   }
 351   return false;
 352 }
 353 
 354 
 355 address ExceptionCache::test_address(address addr) {
 356   int limit = count();
 357   for (int i = 0; i < limit; i++) {
 358     if (pc_at(i) == addr) {
 359       return handler_at(i);
 360     }
 361   }
 362   return nullptr;
 363 }
 364 
 365 
 366 bool ExceptionCache::add_address_and_handler(address addr, address handler) {
 367   if (test_address(addr) == handler) return true;
 368 
 369   int index = count();
 370   if (index < cache_size) {
 371     set_pc_at(index, addr);
 372     set_handler_at(index, handler);
 373     increment_count();
 374     return true;
 375   }
 376   return false;
 377 }
 378 
 379 ExceptionCache* ExceptionCache::next() {
 380   return AtomicAccess::load(&_next);
 381 }
 382 
 383 void ExceptionCache::set_next(ExceptionCache *ec) {
 384   AtomicAccess::store(&_next, ec);
 385 }
 386 
 387 //-----------------------------------------------------------------------------
 388 
 389 
 390 // Helper used by both find_pc_desc methods.
 391 static inline bool match_desc(PcDesc* pc, int pc_offset, bool approximate) {
 392   NOT_PRODUCT(++pc_nmethod_stats.pc_desc_tests);
 393   if (!approximate) {
 394     return pc->pc_offset() == pc_offset;
 395   } else {
 396     // Do not look before the sentinel
 397     assert(pc_offset > PcDesc::lower_offset_limit, "illegal pc_offset");
 398     return pc_offset <= pc->pc_offset() && (pc-1)->pc_offset() < pc_offset;
 399   }
 400 }
 401 
 402 void PcDescCache::init_to(PcDesc* initial_pc_desc) {
 403   NOT_PRODUCT(++pc_nmethod_stats.pc_desc_init);
 404   // initialize the cache by filling it with benign (non-null) values
 405   assert(initial_pc_desc != nullptr && initial_pc_desc->pc_offset() == PcDesc::lower_offset_limit,
 406          "must start with a sentinel");
 407   for (int i = 0; i < cache_size; i++) {
 408     _pc_descs[i] = initial_pc_desc;
 409   }
 410 }
 411 
 412 PcDesc* PcDescCache::find_pc_desc(int pc_offset, bool approximate) {
 413   // Note: one might think that caching the most recently
 414   // read value separately would be a win, but one would be
 415   // wrong.  When many threads are updating it, the cache
 416   // line it's in would bounce between caches, negating
 417   // any benefit.
 418 
 419   // In order to prevent race conditions do not load cache elements
 420   // repeatedly, but use a local copy:
 421   PcDesc* res;
 422 
 423   // Step one:  Check the most recently added value.
 424   res = _pc_descs[0];
 425   assert(res != nullptr, "PcDesc cache should be initialized already");
 426 
 427   // Approximate only here since PcDescContainer::find_pc_desc() checked for exact case.
 428   if (approximate && match_desc(res, pc_offset, approximate)) {
 429     NOT_PRODUCT(++pc_nmethod_stats.pc_desc_repeats);
 430     return res;
 431   }
 432 
 433   // Step two:  Check the rest of the LRU cache.
 434   for (int i = 1; i < cache_size; ++i) {
 435     res = _pc_descs[i];
 436     if (res->pc_offset() < 0) break;  // optimization: skip empty cache
 437     if (match_desc(res, pc_offset, approximate)) {
 438       NOT_PRODUCT(++pc_nmethod_stats.pc_desc_hits);
 439       return res;
 440     }
 441   }
 442 
 443   // Report failure.
 444   return nullptr;
 445 }
 446 
 447 void PcDescCache::add_pc_desc(PcDesc* pc_desc) {
 448   NOT_PRODUCT(++pc_nmethod_stats.pc_desc_adds);
 449   // Update the LRU cache by shifting pc_desc forward.
 450   for (int i = 0; i < cache_size; i++)  {
 451     PcDesc* next = _pc_descs[i];
 452     _pc_descs[i] = pc_desc;
 453     pc_desc = next;
 454   }
 455 }
 456 
 457 // adjust pcs_size so that it is a multiple of both oopSize and
 458 // sizeof(PcDesc) (assumes that if sizeof(PcDesc) is not a multiple
 459 // of oopSize, then 2*sizeof(PcDesc) is)
 460 static int adjust_pcs_size(int pcs_size) {
 461   int nsize = align_up(pcs_size,   oopSize);
 462   if ((nsize % sizeof(PcDesc)) != 0) {
 463     nsize = pcs_size + sizeof(PcDesc);
 464   }
 465   assert((nsize % oopSize) == 0, "correct alignment");
 466   return nsize;
 467 }
 468 
 469 bool nmethod::is_method_handle_return(address return_pc) {
 470   if (!has_method_handle_invokes())  return false;
 471   PcDesc* pd = pc_desc_at(return_pc);
 472   if (pd == nullptr)
 473     return false;
 474   return pd->is_method_handle_invoke();
 475 }
 476 
 477 // Returns a string version of the method state.
 478 const char* nmethod::state() const {
 479   int state = get_state();
 480   switch (state) {
 481   case not_installed:
 482     return "not installed";
 483   case in_use:
 484     return "in use";
 485   case not_entrant:
 486     return "not_entrant";
 487   default:
 488     fatal("unexpected method state: %d", state);
 489     return nullptr;
 490   }
 491 }
 492 
 493 void nmethod::set_deoptimized_done() {
 494   ConditionalMutexLocker ml(NMethodState_lock, !NMethodState_lock->owned_by_self(), Mutex::_no_safepoint_check_flag);
 495   if (_deoptimization_status != deoptimize_done) { // can't go backwards
 496     AtomicAccess::store(&_deoptimization_status, deoptimize_done);
 497   }
 498 }
 499 
 500 ExceptionCache* nmethod::exception_cache_acquire() const {
 501   return AtomicAccess::load_acquire(&_exception_cache);
 502 }
 503 
 504 void nmethod::add_exception_cache_entry(ExceptionCache* new_entry) {
 505   assert(ExceptionCache_lock->owned_by_self(),"Must hold the ExceptionCache_lock");
 506   assert(new_entry != nullptr,"Must be non null");
 507   assert(new_entry->next() == nullptr, "Must be null");
 508 
 509   for (;;) {
 510     ExceptionCache *ec = exception_cache();
 511     if (ec != nullptr) {
 512       Klass* ex_klass = ec->exception_type();
 513       if (!ex_klass->is_loader_alive()) {
 514         // We must guarantee that entries are not inserted with new next pointer
 515         // edges to ExceptionCache entries with dead klasses, due to bad interactions
 516         // with concurrent ExceptionCache cleanup. Therefore, the inserts roll
 517         // the head pointer forward to the first live ExceptionCache, so that the new
 518         // next pointers always point at live ExceptionCaches, that are not removed due
 519         // to concurrent ExceptionCache cleanup.
 520         ExceptionCache* next = ec->next();
 521         if (AtomicAccess::cmpxchg(&_exception_cache, ec, next) == ec) {
 522           CodeCache::release_exception_cache(ec);
 523         }
 524         continue;
 525       }
 526       ec = exception_cache();
 527       if (ec != nullptr) {
 528         new_entry->set_next(ec);
 529       }
 530     }
 531     if (AtomicAccess::cmpxchg(&_exception_cache, ec, new_entry) == ec) {
 532       return;
 533     }
 534   }
 535 }
 536 
 537 void nmethod::clean_exception_cache() {
 538   // For each nmethod, only a single thread may call this cleanup function
 539   // at the same time, whether called in STW cleanup or concurrent cleanup.
 540   // Note that if the GC is processing exception cache cleaning in a concurrent phase,
 541   // then a single writer may contend with cleaning up the head pointer to the
 542   // first ExceptionCache node that has a Klass* that is alive. That is fine,
 543   // as long as there is no concurrent cleanup of next pointers from concurrent writers.
 544   // And the concurrent writers do not clean up next pointers, only the head.
 545   // Also note that concurrent readers will walk through Klass* pointers that are not
 546   // alive. That does not cause ABA problems, because Klass* is deleted after
 547   // a handshake with all threads, after all stale ExceptionCaches have been
 548   // unlinked. That is also when the CodeCache::exception_cache_purge_list()
 549   // is deleted, with all ExceptionCache entries that were cleaned concurrently.
 550   // That similarly implies that CAS operations on ExceptionCache entries do not
 551   // suffer from ABA problems as unlinking and deletion is separated by a global
 552   // handshake operation.
 553   ExceptionCache* prev = nullptr;
 554   ExceptionCache* curr = exception_cache_acquire();
 555 
 556   while (curr != nullptr) {
 557     ExceptionCache* next = curr->next();
 558 
 559     if (!curr->exception_type()->is_loader_alive()) {
 560       if (prev == nullptr) {
 561         // Try to clean head; this is contended by concurrent inserts, that
 562         // both lazily clean the head, and insert entries at the head. If
 563         // the CAS fails, the operation is restarted.
 564         if (AtomicAccess::cmpxchg(&_exception_cache, curr, next) != curr) {
 565           prev = nullptr;
 566           curr = exception_cache_acquire();
 567           continue;
 568         }
 569       } else {
 570         // It is impossible to during cleanup connect the next pointer to
 571         // an ExceptionCache that has not been published before a safepoint
 572         // prior to the cleanup. Therefore, release is not required.
 573         prev->set_next(next);
 574       }
 575       // prev stays the same.
 576 
 577       CodeCache::release_exception_cache(curr);
 578     } else {
 579       prev = curr;
 580     }
 581 
 582     curr = next;
 583   }
 584 }
 585 
 586 // public method for accessing the exception cache
 587 // These are the public access methods.
 588 address nmethod::handler_for_exception_and_pc(Handle exception, address pc) {
 589   // We never grab a lock to read the exception cache, so we may
 590   // have false negatives. This is okay, as it can only happen during
 591   // the first few exception lookups for a given nmethod.
 592   ExceptionCache* ec = exception_cache_acquire();
 593   while (ec != nullptr) {
 594     address ret_val;
 595     if ((ret_val = ec->match(exception,pc)) != nullptr) {
 596       return ret_val;
 597     }
 598     ec = ec->next();
 599   }
 600   return nullptr;
 601 }
 602 
 603 void nmethod::add_handler_for_exception_and_pc(Handle exception, address pc, address handler) {
 604   // There are potential race conditions during exception cache updates, so we
 605   // must own the ExceptionCache_lock before doing ANY modifications. Because
 606   // we don't lock during reads, it is possible to have several threads attempt
 607   // to update the cache with the same data. We need to check for already inserted
 608   // copies of the current data before adding it.
 609 
 610   MutexLocker ml(ExceptionCache_lock);
 611   ExceptionCache* target_entry = exception_cache_entry_for_exception(exception);
 612 
 613   if (target_entry == nullptr || !target_entry->add_address_and_handler(pc,handler)) {
 614     target_entry = new ExceptionCache(exception,pc,handler);
 615     add_exception_cache_entry(target_entry);
 616   }
 617 }
 618 
 619 // private method for handling exception cache
 620 // These methods are private, and used to manipulate the exception cache
 621 // directly.
 622 ExceptionCache* nmethod::exception_cache_entry_for_exception(Handle exception) {
 623   ExceptionCache* ec = exception_cache_acquire();
 624   while (ec != nullptr) {
 625     if (ec->match_exception_with_space(exception)) {
 626       return ec;
 627     }
 628     ec = ec->next();
 629   }
 630   return nullptr;
 631 }
 632 
 633 bool nmethod::is_at_poll_return(address pc) {
 634   RelocIterator iter(this, pc, pc+1);
 635   while (iter.next()) {
 636     if (iter.type() == relocInfo::poll_return_type)
 637       return true;
 638   }
 639   return false;
 640 }
 641 
 642 
 643 bool nmethod::is_at_poll_or_poll_return(address pc) {
 644   RelocIterator iter(this, pc, pc+1);
 645   while (iter.next()) {
 646     relocInfo::relocType t = iter.type();
 647     if (t == relocInfo::poll_return_type || t == relocInfo::poll_type)
 648       return true;
 649   }
 650   return false;
 651 }
 652 
 653 void nmethod::verify_oop_relocations() {
 654   // Ensure sure that the code matches the current oop values
 655   RelocIterator iter(this, nullptr, nullptr);
 656   while (iter.next()) {
 657     if (iter.type() == relocInfo::oop_type) {
 658       oop_Relocation* reloc = iter.oop_reloc();
 659       if (!reloc->oop_is_immediate()) {
 660         reloc->verify_oop_relocation();
 661       }
 662     }
 663   }
 664 }
 665 
 666 
 667 ScopeDesc* nmethod::scope_desc_at(address pc) {
 668   PcDesc* pd = pc_desc_at(pc);
 669   guarantee(pd != nullptr, "scope must be present");
 670   return new ScopeDesc(this, pd);
 671 }
 672 
 673 ScopeDesc* nmethod::scope_desc_near(address pc) {
 674   PcDesc* pd = pc_desc_near(pc);
 675   guarantee(pd != nullptr, "scope must be present");
 676   return new ScopeDesc(this, pd);
 677 }
 678 
 679 address nmethod::oops_reloc_begin() const {
 680   // If the method is not entrant then a JMP is plastered over the
 681   // first few bytes.  If an oop in the old code was there, that oop
 682   // should not get GC'd.  Skip the first few bytes of oops on
 683   // not-entrant methods.
 684   if (frame_complete_offset() != CodeOffsets::frame_never_safe &&
 685       code_begin() + frame_complete_offset() >
 686       verified_entry_point() + NativeJump::instruction_size)
 687   {
 688     // If we have a frame_complete_offset after the native jump, then there
 689     // is no point trying to look for oops before that. This is a requirement
 690     // for being allowed to scan oops concurrently.
 691     return code_begin() + frame_complete_offset();
 692   }
 693 
 694   address low_boundary = verified_entry_point();
 695   return low_boundary;
 696 }
 697 
 698 // Method that knows how to preserve outgoing arguments at call. This method must be
 699 // called with a frame corresponding to a Java invoke
 700 void nmethod::preserve_callee_argument_oops(frame fr, const RegisterMap *reg_map, OopClosure* f) {
 701   if (method() == nullptr) {
 702     return;
 703   }
 704 
 705   // handle the case of an anchor explicitly set in continuation code that doesn't have a callee
 706   JavaThread* thread = reg_map->thread();
 707   if ((thread->has_last_Java_frame() && fr.sp() == thread->last_Java_sp())
 708       JVMTI_ONLY(|| (method()->is_continuation_enter_intrinsic() && thread->on_monitor_waited_event()))) {
 709     return;
 710   }
 711 
 712   if (!method()->is_native()) {
 713     address pc = fr.pc();
 714     bool has_receiver, has_appendix;
 715     Symbol* signature;
 716 
 717     // The method attached by JIT-compilers should be used, if present.
 718     // Bytecode can be inaccurate in such case.
 719     Method* callee = attached_method_before_pc(pc);
 720     if (callee != nullptr) {
 721       has_receiver = !(callee->access_flags().is_static());
 722       has_appendix = false;
 723       signature    = callee->signature();
 724     } else {
 725       SimpleScopeDesc ssd(this, pc);
 726 
 727       Bytecode_invoke call(methodHandle(Thread::current(), ssd.method()), ssd.bci());
 728       has_receiver = call.has_receiver();
 729       has_appendix = call.has_appendix();
 730       signature    = call.signature();
 731     }
 732 
 733     fr.oops_compiled_arguments_do(signature, has_receiver, has_appendix, reg_map, f);
 734   } else if (method()->is_continuation_enter_intrinsic()) {
 735     // This method only calls Continuation.enter()
 736     Symbol* signature = vmSymbols::continuationEnter_signature();
 737     fr.oops_compiled_arguments_do(signature, false, false, reg_map, f);
 738   }
 739 }
 740 
 741 Method* nmethod::attached_method(address call_instr) {
 742   assert(code_contains(call_instr), "not part of the nmethod");
 743   RelocIterator iter(this, call_instr, call_instr + 1);
 744   while (iter.next()) {
 745     if (iter.addr() == call_instr) {
 746       switch(iter.type()) {
 747         case relocInfo::static_call_type:      return iter.static_call_reloc()->method_value();
 748         case relocInfo::opt_virtual_call_type: return iter.opt_virtual_call_reloc()->method_value();
 749         case relocInfo::virtual_call_type:     return iter.virtual_call_reloc()->method_value();
 750         default:                               break;
 751       }
 752     }
 753   }
 754   return nullptr; // not found
 755 }
 756 
 757 Method* nmethod::attached_method_before_pc(address pc) {
 758   if (NativeCall::is_call_before(pc)) {
 759     NativeCall* ncall = nativeCall_before(pc);
 760     return attached_method(ncall->instruction_address());
 761   }
 762   return nullptr; // not a call
 763 }
 764 
 765 void nmethod::clear_inline_caches() {
 766   assert(SafepointSynchronize::is_at_safepoint(), "clearing of IC's only allowed at safepoint");
 767   RelocIterator iter(this);
 768   while (iter.next()) {
 769     iter.reloc()->clear_inline_cache();
 770   }
 771 }
 772 
 773 #ifdef ASSERT
 774 // Check class_loader is alive for this bit of metadata.
 775 class CheckClass : public MetadataClosure {
 776   void do_metadata(Metadata* md) {
 777     Klass* klass = nullptr;
 778     if (md->is_klass()) {
 779       klass = ((Klass*)md);
 780     } else if (md->is_method()) {
 781       klass = ((Method*)md)->method_holder();
 782     } else if (md->is_methodData()) {
 783       klass = ((MethodData*)md)->method()->method_holder();
 784     } else if (md->is_methodCounters()) {
 785       klass = ((MethodCounters*)md)->method()->method_holder();
 786     } else {
 787       md->print();
 788       ShouldNotReachHere();
 789     }
 790     assert(klass->is_loader_alive(), "must be alive");
 791   }
 792 };
 793 #endif // ASSERT
 794 
 795 
 796 static void clean_ic_if_metadata_is_dead(CompiledIC *ic) {
 797   ic->clean_metadata();
 798 }
 799 
 800 // Clean references to unloaded nmethods at addr from this one, which is not unloaded.
 801 template <typename CallsiteT>
 802 static void clean_if_nmethod_is_unloaded(CallsiteT* callsite, nmethod* from,
 803                                          bool clean_all) {
 804   CodeBlob* cb = CodeCache::find_blob(callsite->destination());
 805   if (!cb->is_nmethod()) {
 806     return;
 807   }
 808   nmethod* nm = cb->as_nmethod();
 809   if (clean_all || !nm->is_in_use() || nm->is_unloading() || nm->method()->code() != nm) {
 810     callsite->set_to_clean();
 811   }
 812 }
 813 
 814 // Cleans caches in nmethods that point to either classes that are unloaded
 815 // or nmethods that are unloaded.
 816 //
 817 // Can be called either in parallel by G1 currently or after all
 818 // nmethods are unloaded.  Return postponed=true in the parallel case for
 819 // inline caches found that point to nmethods that are not yet visited during
 820 // the do_unloading walk.
 821 void nmethod::unload_nmethod_caches(bool unloading_occurred) {
 822   ResourceMark rm;
 823 
 824   // Exception cache only needs to be called if unloading occurred
 825   if (unloading_occurred) {
 826     clean_exception_cache();
 827   }
 828 
 829   cleanup_inline_caches_impl(unloading_occurred, false);
 830 
 831 #ifdef ASSERT
 832   // Check that the metadata embedded in the nmethod is alive
 833   CheckClass check_class;
 834   metadata_do(&check_class);
 835 #endif
 836 }
 837 
 838 void nmethod::run_nmethod_entry_barrier() {
 839   BarrierSetNMethod* bs_nm = BarrierSet::barrier_set()->barrier_set_nmethod();
 840   if (bs_nm != nullptr) {
 841     // We want to keep an invariant that nmethods found through iterations of a Thread's
 842     // nmethods found in safepoints have gone through an entry barrier and are not armed.
 843     // By calling this nmethod entry barrier, it plays along and acts
 844     // like any other nmethod found on the stack of a thread (fewer surprises).
 845     nmethod* nm = this;
 846     bool alive = bs_nm->nmethod_entry_barrier(nm);
 847     assert(alive, "should be alive");
 848   }
 849 }
 850 
 851 // Only called by whitebox test
 852 void nmethod::cleanup_inline_caches_whitebox() {
 853   assert_locked_or_safepoint(CodeCache_lock);
 854   CompiledICLocker ic_locker(this);
 855   cleanup_inline_caches_impl(false /* unloading_occurred */, true /* clean_all */);
 856 }
 857 
 858 address* nmethod::orig_pc_addr(const frame* fr) {
 859   return (address*) ((address)fr->unextended_sp() + orig_pc_offset());
 860 }
 861 
 862 // Called to clean up after class unloading for live nmethods
 863 void nmethod::cleanup_inline_caches_impl(bool unloading_occurred, bool clean_all) {
 864   assert(CompiledICLocker::is_safe(this), "mt unsafe call");
 865   ResourceMark rm;
 866 
 867   // Find all calls in an nmethod and clear the ones that point to bad nmethods.
 868   RelocIterator iter(this, oops_reloc_begin());
 869   bool is_in_static_stub = false;
 870   while(iter.next()) {
 871 
 872     switch (iter.type()) {
 873 
 874     case relocInfo::virtual_call_type:
 875       if (unloading_occurred) {
 876         // If class unloading occurred we first clear ICs where the cached metadata
 877         // is referring to an unloaded klass or method.
 878         clean_ic_if_metadata_is_dead(CompiledIC_at(&iter));
 879       }
 880 
 881       clean_if_nmethod_is_unloaded(CompiledIC_at(&iter), this, clean_all);
 882       break;
 883 
 884     case relocInfo::opt_virtual_call_type:
 885     case relocInfo::static_call_type:
 886       clean_if_nmethod_is_unloaded(CompiledDirectCall::at(iter.reloc()), this, clean_all);
 887       break;
 888 
 889     case relocInfo::static_stub_type: {
 890       is_in_static_stub = true;
 891       break;
 892     }
 893 
 894     case relocInfo::metadata_type: {
 895       // Only the metadata relocations contained in static/opt virtual call stubs
 896       // contains the Method* passed to c2i adapters. It is the only metadata
 897       // relocation that needs to be walked, as it is the one metadata relocation
 898       // that violates the invariant that all metadata relocations have an oop
 899       // in the compiled method (due to deferred resolution and code patching).
 900 
 901       // This causes dead metadata to remain in compiled methods that are not
 902       // unloading. Unless these slippery metadata relocations of the static
 903       // stubs are at least cleared, subsequent class redefinition operations
 904       // will access potentially free memory, and JavaThread execution
 905       // concurrent to class unloading may call c2i adapters with dead methods.
 906       if (!is_in_static_stub) {
 907         // The first metadata relocation after a static stub relocation is the
 908         // metadata relocation of the static stub used to pass the Method* to
 909         // c2i adapters.
 910         continue;
 911       }
 912       is_in_static_stub = false;
 913       if (is_unloading()) {
 914         // If the nmethod itself is dying, then it may point at dead metadata.
 915         // Nobody should follow that metadata; it is strictly unsafe.
 916         continue;
 917       }
 918       metadata_Relocation* r = iter.metadata_reloc();
 919       Metadata* md = r->metadata_value();
 920       if (md != nullptr && md->is_method()) {
 921         Method* method = static_cast<Method*>(md);
 922         if (!method->method_holder()->is_loader_alive()) {
 923           AtomicAccess::store(r->metadata_addr(), (Method*)nullptr);
 924 
 925           if (!r->metadata_is_immediate()) {
 926             r->fix_metadata_relocation();
 927           }
 928         }
 929       }
 930       break;
 931     }
 932 
 933     default:
 934       break;
 935     }
 936   }
 937 }
 938 
 939 address nmethod::continuation_for_implicit_exception(address pc, bool for_div0_check) {
 940   // Exception happened outside inline-cache check code => we are inside
 941   // an active nmethod => use cpc to determine a return address
 942   int exception_offset = int(pc - code_begin());
 943   int cont_offset = ImplicitExceptionTable(this).continuation_offset( exception_offset );
 944 #ifdef ASSERT
 945   if (cont_offset == 0) {
 946     Thread* thread = Thread::current();
 947     ResourceMark rm(thread);
 948     CodeBlob* cb = CodeCache::find_blob(pc);
 949     assert(cb != nullptr && cb == this, "");
 950 
 951     // Keep tty output consistent. To avoid ttyLocker, we buffer in stream, and print all at once.
 952     stringStream ss;
 953     ss.print_cr("implicit exception happened at " INTPTR_FORMAT, p2i(pc));
 954     print_on(&ss);
 955     method()->print_codes_on(&ss);
 956     print_code_on(&ss);
 957     print_pcs_on(&ss);
 958     tty->print("%s", ss.as_string()); // print all at once
 959   }
 960 #endif
 961   if (cont_offset == 0) {
 962     // Let the normal error handling report the exception
 963     return nullptr;
 964   }
 965   if (cont_offset == exception_offset) {
 966 #if INCLUDE_JVMCI
 967     Deoptimization::DeoptReason deopt_reason = for_div0_check ? Deoptimization::Reason_div0_check : Deoptimization::Reason_null_check;
 968     JavaThread *thread = JavaThread::current();
 969     thread->set_jvmci_implicit_exception_pc(pc);
 970     thread->set_pending_deoptimization(Deoptimization::make_trap_request(deopt_reason,
 971                                                                          Deoptimization::Action_reinterpret));
 972     return (SharedRuntime::deopt_blob()->implicit_exception_uncommon_trap());
 973 #else
 974     ShouldNotReachHere();
 975 #endif
 976   }
 977   return code_begin() + cont_offset;
 978 }
 979 
 980 class HasEvolDependency : public MetadataClosure {
 981   bool _has_evol_dependency;
 982  public:
 983   HasEvolDependency() : _has_evol_dependency(false) {}
 984   void do_metadata(Metadata* md) {
 985     if (md->is_method()) {
 986       Method* method = (Method*)md;
 987       if (method->is_old()) {
 988         _has_evol_dependency = true;
 989       }
 990     }
 991   }
 992   bool has_evol_dependency() const { return _has_evol_dependency; }
 993 };
 994 
 995 bool nmethod::has_evol_metadata() {
 996   // Check the metadata in relocIter and CompiledIC and also deoptimize
 997   // any nmethod that has reference to old methods.
 998   HasEvolDependency check_evol;
 999   metadata_do(&check_evol);
1000   if (check_evol.has_evol_dependency() && log_is_enabled(Debug, redefine, class, nmethod)) {
1001     ResourceMark rm;
1002     log_debug(redefine, class, nmethod)
1003             ("Found evol dependency of nmethod %s.%s(%s) compile_id=%d on in nmethod metadata",
1004              _method->method_holder()->external_name(),
1005              _method->name()->as_C_string(),
1006              _method->signature()->as_C_string(),
1007              compile_id());
1008   }
1009   return check_evol.has_evol_dependency();
1010 }
1011 
1012 int nmethod::total_size() const {
1013   return
1014     consts_size()        +
1015     insts_size()         +
1016     stub_size()          +
1017     scopes_data_size()   +
1018     scopes_pcs_size()    +
1019     handler_table_size() +
1020     nul_chk_table_size();
1021 }
1022 
1023 const char* nmethod::compile_kind() const {
1024   if (is_osr_method()) return "osr";
1025   if (preloaded())     return "AP";
1026   if (is_aot())        return "A";
1027 
1028   if (method() != nullptr && is_native_method()) {
1029     if (method()->is_continuation_native_intrinsic()) {
1030       return "cnt";
1031     }
1032     return "c2n";
1033   }
1034   return nullptr;
1035 }
1036 
1037 const char* nmethod::compiler_name() const {
1038   return compilertype2name(_compiler_type);
1039 }
1040 
1041 #ifdef ASSERT
1042 class CheckForOopsClosure : public OopClosure {
1043   bool _found_oop = false;
1044  public:
1045   virtual void do_oop(oop* o) { _found_oop = true; }
1046   virtual void do_oop(narrowOop* o) { _found_oop = true; }
1047   bool found_oop() { return _found_oop; }
1048 };
1049 class CheckForMetadataClosure : public MetadataClosure {
1050   bool _found_metadata = false;
1051   Metadata* _ignore = nullptr;
1052  public:
1053   CheckForMetadataClosure(Metadata* ignore) : _ignore(ignore) {}
1054   virtual void do_metadata(Metadata* md) { if (md != _ignore) _found_metadata = true; }
1055   bool found_metadata() { return _found_metadata; }
1056 };
1057 
1058 static void assert_no_oops_or_metadata(nmethod* nm) {
1059   if (nm == nullptr) return;
1060   assert(nm->oop_maps() == nullptr, "expectation");
1061 
1062   CheckForOopsClosure cfo;
1063   nm->oops_do(&cfo);
1064   assert(!cfo.found_oop(), "no oops allowed");
1065 
1066   // We allow an exception for the own Method, but require its class to be permanent.
1067   Method* own_method = nm->method();
1068   CheckForMetadataClosure cfm(/* ignore reference to own Method */ own_method);
1069   nm->metadata_do(&cfm);
1070   assert(!cfm.found_metadata(), "no metadata allowed");
1071 
1072   assert(own_method->method_holder()->class_loader_data()->is_permanent_class_loader_data(),
1073          "Method's class needs to be permanent");
1074 }
1075 #endif
1076 
1077 static int required_mutable_data_size(CodeBuffer* code_buffer,
1078                                       int jvmci_data_size = 0) {
1079   return align_up(code_buffer->total_relocation_size(), oopSize) +
1080          align_up(code_buffer->total_metadata_size(), oopSize) +
1081          align_up(jvmci_data_size, oopSize);
1082 }
1083 
1084 nmethod* nmethod::new_native_nmethod(const methodHandle& method,
1085   int compile_id,
1086   CodeBuffer *code_buffer,
1087   int vep_offset,
1088   int frame_complete,
1089   int frame_size,
1090   ByteSize basic_lock_owner_sp_offset,
1091   ByteSize basic_lock_sp_offset,
1092   OopMapSet* oop_maps,
1093   int exception_handler) {
1094   code_buffer->finalize_oop_references(method);
1095   // create nmethod
1096   nmethod* nm = nullptr;
1097   int native_nmethod_size = CodeBlob::allocation_size(code_buffer, sizeof(nmethod));
1098   {
1099     MutexLocker mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
1100 
1101     CodeOffsets offsets;
1102     offsets.set_value(CodeOffsets::Verified_Entry, vep_offset);
1103     offsets.set_value(CodeOffsets::Frame_Complete, frame_complete);
1104     if (exception_handler != -1) {
1105       offsets.set_value(CodeOffsets::Exceptions, exception_handler);
1106     }
1107 
1108     int mutable_data_size = required_mutable_data_size(code_buffer);
1109 
1110     // MH intrinsics are dispatch stubs which are compatible with NonNMethod space.
1111     // IsUnloadingBehaviour::is_unloading needs to handle them separately.
1112     bool allow_NonNMethod_space = method->can_be_allocated_in_NonNMethod_space();
1113     nm = new (native_nmethod_size, allow_NonNMethod_space)
1114     nmethod(method(), compiler_none, native_nmethod_size,
1115             compile_id, &offsets,
1116             code_buffer, frame_size,
1117             basic_lock_owner_sp_offset,
1118             basic_lock_sp_offset,
1119             oop_maps, mutable_data_size);
1120     DEBUG_ONLY( if (allow_NonNMethod_space) assert_no_oops_or_metadata(nm); )
1121     NOT_PRODUCT(if (nm != nullptr) native_nmethod_stats.note_native_nmethod(nm));
1122   }
1123 
1124   if (nm != nullptr) {
1125     // verify nmethod
1126     DEBUG_ONLY(nm->verify();) // might block
1127 
1128     nm->log_new_nmethod();
1129   }
1130   return nm;
1131 }
1132 
1133 void nmethod::record_nmethod_dependency() {
1134   // To make dependency checking during class loading fast, record
1135   // the nmethod dependencies in the classes it is dependent on.
1136   // This allows the dependency checking code to simply walk the
1137   // class hierarchy above the loaded class, checking only nmethods
1138   // which are dependent on those classes.  The slow way is to
1139   // check every nmethod for dependencies which makes it linear in
1140   // the number of methods compiled.  For applications with a lot
1141   // classes the slow way is too slow.
1142   for (Dependencies::DepStream deps(this); deps.next(); ) {
1143     if (deps.type() == Dependencies::call_site_target_value) {
1144       // CallSite dependencies are managed on per-CallSite instance basis.
1145       oop call_site = deps.argument_oop(0);
1146       MethodHandles::add_dependent_nmethod(call_site, this);
1147     } else {
1148       InstanceKlass* ik = deps.context_type();
1149       if (ik == nullptr) {
1150         continue;  // ignore things like evol_method
1151       }
1152       // record this nmethod as dependent on this klass
1153       ik->add_dependent_nmethod(this);
1154     }
1155   }
1156 }
1157 
1158 nmethod* nmethod::new_nmethod(const methodHandle& method,
1159   int compile_id,
1160   int entry_bci,
1161   CodeOffsets* offsets,
1162   int orig_pc_offset,
1163   DebugInformationRecorder* debug_info,
1164   Dependencies* dependencies,
1165   CodeBuffer* code_buffer, int frame_size,
1166   OopMapSet* oop_maps,
1167   ExceptionHandlerTable* handler_table,
1168   ImplicitExceptionTable* nul_chk_table,
1169   AbstractCompiler* compiler,
1170   CompLevel comp_level
1171 #if INCLUDE_JVMCI
1172   , char* speculations,
1173   int speculations_len,
1174   JVMCINMethodData* jvmci_data
1175 #endif
1176 )
1177 {
1178   assert(debug_info->oop_recorder() == code_buffer->oop_recorder(), "shared OR");
1179   code_buffer->finalize_oop_references(method);
1180   // create nmethod
1181   nmethod* nm = nullptr;
1182   int nmethod_size = CodeBlob::allocation_size(code_buffer, sizeof(nmethod));
1183 
1184   int immutable_data_size =
1185       adjust_pcs_size(debug_info->pcs_size())
1186     + align_up((int)dependencies->size_in_bytes(), oopSize)
1187     + align_up(handler_table->size_in_bytes()    , oopSize)
1188     + align_up(nul_chk_table->size_in_bytes()    , oopSize)
1189 #if INCLUDE_JVMCI
1190     + align_up(speculations_len                  , oopSize)
1191 #endif
1192     + align_up(debug_info->data_size()           , oopSize);
1193 
1194   // First, allocate space for immutable data in C heap.
1195   address immutable_data = nullptr;
1196   if (immutable_data_size > 0) {
1197     immutable_data = (address)os::malloc(immutable_data_size, mtCode);
1198     if (immutable_data == nullptr) {
1199       vm_exit_out_of_memory(immutable_data_size, OOM_MALLOC_ERROR, "nmethod: no space for immutable data");
1200       return nullptr;
1201     }
1202   }
1203 
1204   int mutable_data_size = required_mutable_data_size(code_buffer
1205     JVMCI_ONLY(COMMA (compiler->is_jvmci() ? jvmci_data->size() : 0)));
1206 
1207   {
1208     MutexLocker mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
1209 
1210     nm = new (nmethod_size, comp_level)
1211     nmethod(method(), compiler->type(), nmethod_size, immutable_data_size, mutable_data_size,
1212             compile_id, entry_bci, immutable_data, offsets, orig_pc_offset,
1213             debug_info, dependencies, code_buffer, frame_size, oop_maps,
1214             handler_table, nul_chk_table, compiler, comp_level
1215 #if INCLUDE_JVMCI
1216             , speculations,
1217             speculations_len,
1218             jvmci_data
1219 #endif
1220             );
1221 
1222     if (nm != nullptr) {
1223       nm->record_nmethod_dependency();
1224       NOT_PRODUCT(note_java_nmethod(nm));
1225     }
1226   }
1227   // Do verification and logging outside CodeCache_lock.
1228   if (nm != nullptr) {
1229 
1230 #ifdef ASSERT
1231     LogTarget(Debug, aot, codecache, nmethod) log;
1232     if (log.is_enabled()) {
1233       LogStream out(log);
1234       out.print_cr("== new_nmethod 2");
1235       FlagSetting fs(PrintRelocations, true);
1236       nm->print_on_impl(&out);
1237       nm->decode(&out);
1238     }
1239 #endif
1240 
1241     // Safepoints in nmethod::verify aren't allowed because nm hasn't been installed yet.
1242     DEBUG_ONLY(nm->verify();)
1243     nm->log_new_nmethod();
1244   }
1245   return nm;
1246 }
1247 
1248 nmethod* nmethod::restore(address code_cache_buffer,
1249                           const methodHandle& method,
1250                           int compile_id,
1251                           address reloc_data,
1252                           GrowableArray<Handle>& oop_list,
1253                           GrowableArray<Metadata*>& metadata_list,
1254                           ImmutableOopMapSet* oop_maps,
1255                           address immutable_data,
1256                           GrowableArray<Handle>& reloc_imm_oop_list,
1257                           GrowableArray<Metadata*>& reloc_imm_metadata_list,
1258                           AOTCodeReader* aot_code_reader)
1259 {
1260   CodeBlob::restore(code_cache_buffer, "nmethod", reloc_data, oop_maps);
1261   nmethod* nm = (nmethod*)code_cache_buffer;
1262   nm->set_method(method());
1263   nm->_compile_id = compile_id;
1264   nm->set_immutable_data(immutable_data);
1265   nm->copy_values(&oop_list);
1266   nm->copy_values(&metadata_list);
1267 
1268   aot_code_reader->fix_relocations(nm, &reloc_imm_oop_list, &reloc_imm_metadata_list);
1269 
1270 #ifndef PRODUCT
1271   nm->asm_remarks().init();
1272   aot_code_reader->read_asm_remarks(nm->asm_remarks(), /* use_string_table */ false);
1273   nm->dbg_strings().init();
1274   aot_code_reader->read_dbg_strings(nm->dbg_strings(), /* use_string_table */ false);
1275 #endif
1276 
1277   // Flush the code block
1278   ICache::invalidate_range(nm->code_begin(), nm->code_size());
1279 
1280   // Create cache after PcDesc data is copied - it will be used to initialize cache
1281   nm->_pc_desc_container = new PcDescContainer(nm->scopes_pcs_begin());
1282 
1283   nm->set_aot_code_entry(aot_code_reader->aot_code_entry());
1284 
1285   nm->post_init();
1286   return nm;
1287 }
1288 
1289 nmethod* nmethod::new_nmethod(nmethod* archived_nm,
1290                               const methodHandle& method,
1291                               AbstractCompiler* compiler,
1292                               int compile_id,
1293                               address reloc_data,
1294                               GrowableArray<Handle>& oop_list,
1295                               GrowableArray<Metadata*>& metadata_list,
1296                               ImmutableOopMapSet* oop_maps,
1297                               address immutable_data,
1298                               GrowableArray<Handle>& reloc_imm_oop_list,
1299                               GrowableArray<Metadata*>& reloc_imm_metadata_list,
1300                               AOTCodeReader* aot_code_reader)
1301 {
1302   nmethod* nm = nullptr;
1303   int nmethod_size = archived_nm->size();
1304   // create nmethod
1305   {
1306     MutexLocker mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
1307     address code_cache_buffer = (address)CodeCache::allocate(nmethod_size, CodeCache::get_code_blob_type(archived_nm->comp_level()));
1308     if (code_cache_buffer != nullptr) {
1309       nm = archived_nm->restore(code_cache_buffer,
1310                                 method,
1311                                 compile_id,
1312                                 reloc_data,
1313                                 oop_list,
1314                                 metadata_list,
1315                                 oop_maps,
1316                                 immutable_data,
1317                                 reloc_imm_oop_list,
1318                                 reloc_imm_metadata_list,
1319                                 aot_code_reader);
1320       nm->record_nmethod_dependency();
1321       NOT_PRODUCT(note_java_nmethod(nm));
1322     }
1323   }
1324   // Do verification and logging outside CodeCache_lock.
1325   if (nm != nullptr) {
1326 #ifdef ASSERT
1327     LogTarget(Debug, aot, codecache, nmethod) log;
1328     if (log.is_enabled()) {
1329       LogStream out(log);
1330       out.print_cr("== new_nmethod 2");
1331       FlagSetting fs(PrintRelocations, true);
1332       nm->print_on_impl(&out);
1333       nm->decode(&out);
1334     }
1335 #endif
1336     // Safepoints in nmethod::verify aren't allowed because nm hasn't been installed yet.
1337     DEBUG_ONLY(nm->verify();)
1338     nm->log_new_nmethod();
1339   }
1340   return nm;
1341 }
1342 
1343 // Fill in default values for various fields
1344 void nmethod::init_defaults(CodeBuffer *code_buffer, CodeOffsets* offsets) {
1345   // avoid uninitialized fields, even for short time periods
1346   _exception_cache            = nullptr;
1347   _gc_data                    = nullptr;
1348   _oops_do_mark_link          = nullptr;
1349   _compiled_ic_data           = nullptr;
1350 
1351   _is_unloading_state         = 0;
1352   _state                      = not_installed;
1353 
1354   _has_unsafe_access          = 0;
1355   _has_method_handle_invokes  = 0;
1356   _has_wide_vectors           = 0;
1357   _has_monitors               = 0;
1358   _has_scoped_access          = 0;
1359   _has_flushed_dependencies   = 0;
1360   _is_unlinked                = 0;
1361   _load_reported              = 0; // jvmti state
1362   _preloaded                  = 0;
1363   _has_clinit_barriers        = 0;
1364 
1365   _used                       = false;
1366   _deoptimization_status      = not_marked;
1367 
1368   // SECT_CONSTS is first in code buffer so the offset should be 0.
1369   int consts_offset = code_buffer->total_offset_of(code_buffer->consts());
1370   assert(consts_offset == 0, "const_offset: %d", consts_offset);
1371 
1372   _stub_offset = content_offset() + code_buffer->total_offset_of(code_buffer->stubs());
1373 
1374   CHECKED_CAST(_entry_offset,              uint16_t, (offsets->value(CodeOffsets::Entry)));
1375   CHECKED_CAST(_verified_entry_offset,     uint16_t, (offsets->value(CodeOffsets::Verified_Entry)));
1376 
1377   _skipped_instructions_size = code_buffer->total_skipped_instructions_size();
1378 }
1379 
1380 // Post initialization
1381 void nmethod::post_init() {
1382   clear_unloading_state();
1383 
1384   finalize_relocations();
1385 
1386   Universe::heap()->register_nmethod(this);
1387   DEBUG_ONLY(Universe::heap()->verify_nmethod(this));
1388 
1389   CodeCache::commit(this);
1390 }
1391 
1392 // For native wrappers
1393 nmethod::nmethod(
1394   Method* method,
1395   CompilerType type,
1396   int nmethod_size,
1397   int compile_id,
1398   CodeOffsets* offsets,
1399   CodeBuffer* code_buffer,
1400   int frame_size,
1401   ByteSize basic_lock_owner_sp_offset,
1402   ByteSize basic_lock_sp_offset,
1403   OopMapSet* oop_maps,
1404   int mutable_data_size)
1405   : CodeBlob("native nmethod", CodeBlobKind::Nmethod, code_buffer, nmethod_size, sizeof(nmethod),
1406              offsets->value(CodeOffsets::Frame_Complete), frame_size, oop_maps, false, mutable_data_size),
1407   _deoptimization_generation(0),
1408   _gc_epoch(CodeCache::gc_epoch()),
1409   _method(method),
1410   _native_receiver_sp_offset(basic_lock_owner_sp_offset),
1411   _native_basic_lock_sp_offset(basic_lock_sp_offset)
1412 {
1413   {
1414     DEBUG_ONLY(NoSafepointVerifier nsv;)
1415     assert_locked_or_safepoint(CodeCache_lock);
1416 
1417     init_defaults(code_buffer, offsets);
1418 
1419     _osr_entry_point         = nullptr;
1420     _pc_desc_container       = nullptr;
1421     _entry_bci               = InvocationEntryBci;
1422     _compile_id              = compile_id;
1423     _comp_level              = CompLevel_none;
1424     _compiler_type           = type;
1425     _orig_pc_offset          = 0;
1426     _num_stack_arg_slots     = 0;
1427 
1428     if (offsets->value(CodeOffsets::Exceptions) != -1) {
1429       // Continuation enter intrinsic
1430       _exception_offset      = code_offset() + offsets->value(CodeOffsets::Exceptions);
1431     } else {
1432       _exception_offset      = 0;
1433     }
1434     // Native wrappers do not have deopt handlers. Make the values
1435     // something that will never match a pc like the nmethod vtable entry
1436     _deopt_handler_offset    = 0;
1437     _deopt_mh_handler_offset = 0;
1438     _aot_code_entry          = nullptr;
1439     _method_profiling_count  = 0;
1440     _unwind_handler_offset   = 0;
1441 
1442     CHECKED_CAST(_oops_size, uint16_t, align_up(code_buffer->total_oop_size(), oopSize));
1443     uint16_t metadata_size;
1444     CHECKED_CAST(metadata_size, uint16_t, align_up(code_buffer->total_metadata_size(), wordSize));
1445     JVMCI_ONLY( _metadata_size = metadata_size; )
1446     assert(_mutable_data_size == _relocation_size + metadata_size,
1447            "wrong mutable data size: %d != %d + %d",
1448            _mutable_data_size, _relocation_size, metadata_size);
1449 
1450     // native wrapper does not have read-only data but we need unique not null address
1451     _immutable_data          = blob_end();
1452     _immutable_data_size     = 0;
1453     _nul_chk_table_offset    = 0;
1454     _handler_table_offset    = 0;
1455     _scopes_pcs_offset       = 0;
1456     _scopes_data_offset      = 0;
1457 #if INCLUDE_JVMCI
1458     _speculations_offset     = 0;
1459 #endif
1460 
1461     code_buffer->copy_code_and_locs_to(this);
1462     code_buffer->copy_values_to(this);
1463 
1464     post_init();
1465   }
1466 
1467   if (PrintNativeNMethods || PrintDebugInfo || PrintRelocations || PrintDependencies) {
1468     ttyLocker ttyl;  // keep the following output all in one block
1469     // This output goes directly to the tty, not the compiler log.
1470     // To enable tools to match it up with the compilation activity,
1471     // be sure to tag this tty output with the compile ID.
1472     if (xtty != nullptr) {
1473       xtty->begin_head("print_native_nmethod");
1474       xtty->method(_method);
1475       xtty->stamp();
1476       xtty->end_head(" address='" INTPTR_FORMAT "'", (intptr_t) this);
1477     }
1478     // Print the header part, then print the requested information.
1479     // This is both handled in decode2(), called via print_code() -> decode()
1480     if (PrintNativeNMethods) {
1481       tty->print_cr("-------------------------- Assembly (native nmethod) ---------------------------");
1482       print_code();
1483       tty->print_cr("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ");
1484 #if defined(SUPPORT_DATA_STRUCTS)
1485       if (AbstractDisassembler::show_structs()) {
1486         if (oop_maps != nullptr) {
1487           tty->print("oop maps:"); // oop_maps->print_on(tty) outputs a cr() at the beginning
1488           oop_maps->print_on(tty);
1489           tty->print_cr("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ");
1490         }
1491       }
1492 #endif
1493     } else {
1494       print(); // print the header part only.
1495     }
1496 #if defined(SUPPORT_DATA_STRUCTS)
1497     if (AbstractDisassembler::show_structs()) {
1498       if (PrintRelocations) {
1499         print_relocations_on(tty);
1500         tty->print_cr("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ");
1501       }
1502     }
1503 #endif
1504     if (xtty != nullptr) {
1505       xtty->tail("print_native_nmethod");
1506     }
1507   }
1508 }
1509 
1510 void* nmethod::operator new(size_t size, int nmethod_size, int comp_level) throw () {
1511   return CodeCache::allocate(nmethod_size, CodeCache::get_code_blob_type(comp_level));
1512 }
1513 
1514 void* nmethod::operator new(size_t size, int nmethod_size, bool allow_NonNMethod_space) throw () {
1515   // Try MethodNonProfiled and MethodProfiled.
1516   void* return_value = CodeCache::allocate(nmethod_size, CodeBlobType::MethodNonProfiled);
1517   if (return_value != nullptr || !allow_NonNMethod_space) return return_value;
1518   // Try NonNMethod or give up.
1519   return CodeCache::allocate(nmethod_size, CodeBlobType::NonNMethod);
1520 }
1521 
1522 // For normal JIT compiled code
1523 nmethod::nmethod(
1524   Method* method,
1525   CompilerType type,
1526   int nmethod_size,
1527   int immutable_data_size,
1528   int mutable_data_size,
1529   int compile_id,
1530   int entry_bci,
1531   address immutable_data,
1532   CodeOffsets* offsets,
1533   int orig_pc_offset,
1534   DebugInformationRecorder* debug_info,
1535   Dependencies* dependencies,
1536   CodeBuffer *code_buffer,
1537   int frame_size,
1538   OopMapSet* oop_maps,
1539   ExceptionHandlerTable* handler_table,
1540   ImplicitExceptionTable* nul_chk_table,
1541   AbstractCompiler* compiler,
1542   CompLevel comp_level
1543 #if INCLUDE_JVMCI
1544   , char* speculations,
1545   int speculations_len,
1546   JVMCINMethodData* jvmci_data
1547 #endif
1548   )
1549   : CodeBlob("nmethod", CodeBlobKind::Nmethod, code_buffer, nmethod_size, sizeof(nmethod),
1550              offsets->value(CodeOffsets::Frame_Complete), frame_size, oop_maps, false, mutable_data_size),
1551   _deoptimization_generation(0),
1552   _gc_epoch(CodeCache::gc_epoch()),
1553   _method(method),
1554   _osr_link(nullptr)
1555 {
1556   assert(debug_info->oop_recorder() == code_buffer->oop_recorder(), "shared OR");
1557   {
1558     DEBUG_ONLY(NoSafepointVerifier nsv;)
1559     assert_locked_or_safepoint(CodeCache_lock);
1560 
1561     init_defaults(code_buffer, offsets);
1562     _aot_code_entry          = nullptr; // runtime compiled nmethod does not have AOTCodeEntry
1563     _method_profiling_count  = 0;
1564 
1565     _osr_entry_point = code_begin() + offsets->value(CodeOffsets::OSR_Entry);
1566     _entry_bci       = entry_bci;
1567     _compile_id      = compile_id;
1568     _comp_level      = comp_level;
1569     _compiler_type   = type;
1570     _orig_pc_offset  = orig_pc_offset;
1571 
1572     _num_stack_arg_slots = entry_bci != InvocationEntryBci ? 0 : _method->constMethod()->num_stack_arg_slots();
1573 
1574     set_ctable_begin(header_begin() + content_offset());
1575 
1576 #if INCLUDE_JVMCI
1577     if (compiler->is_jvmci()) {
1578       // JVMCI might not produce any stub sections
1579       if (offsets->value(CodeOffsets::Exceptions) != -1) {
1580         _exception_offset        = code_offset() + offsets->value(CodeOffsets::Exceptions);
1581       } else {
1582         _exception_offset        = -1;
1583       }
1584       if (offsets->value(CodeOffsets::Deopt) != -1) {
1585         _deopt_handler_offset    = code_offset() + offsets->value(CodeOffsets::Deopt);
1586       } else {
1587         _deopt_handler_offset    = -1;
1588       }
1589       if (offsets->value(CodeOffsets::DeoptMH) != -1) {
1590         _deopt_mh_handler_offset = code_offset() + offsets->value(CodeOffsets::DeoptMH);
1591       } else {
1592         _deopt_mh_handler_offset = -1;
1593       }
1594     } else
1595 #endif
1596     {
1597       // Exception handler and deopt handler are in the stub section
1598       assert(offsets->value(CodeOffsets::Exceptions) != -1, "must be set");
1599       assert(offsets->value(CodeOffsets::Deopt     ) != -1, "must be set");
1600 
1601       _exception_offset          = _stub_offset + offsets->value(CodeOffsets::Exceptions);
1602       _deopt_handler_offset      = _stub_offset + offsets->value(CodeOffsets::Deopt);
1603       if (offsets->value(CodeOffsets::DeoptMH) != -1) {
1604         _deopt_mh_handler_offset = _stub_offset + offsets->value(CodeOffsets::DeoptMH);
1605       } else {
1606         _deopt_mh_handler_offset = -1;
1607       }
1608     }
1609     if (offsets->value(CodeOffsets::UnwindHandler) != -1) {
1610       // C1 generates UnwindHandler at the end of instructions section.
1611       // Calculate positive offset as distance between the start of stubs section
1612       // (which is also the end of instructions section) and the start of the handler.
1613       int unwind_handler_offset = code_offset() + offsets->value(CodeOffsets::UnwindHandler);
1614       CHECKED_CAST(_unwind_handler_offset, int16_t, (_stub_offset - unwind_handler_offset));
1615     } else {
1616       _unwind_handler_offset = -1;
1617     }
1618 
1619     CHECKED_CAST(_oops_size, uint16_t, align_up(code_buffer->total_oop_size(), oopSize));
1620     uint16_t metadata_size;
1621     CHECKED_CAST(metadata_size, uint16_t, align_up(code_buffer->total_metadata_size(), wordSize));
1622     JVMCI_ONLY( _metadata_size = metadata_size; )
1623     int jvmci_data_size = 0 JVMCI_ONLY( + align_up(compiler->is_jvmci() ? jvmci_data->size() : 0, oopSize));
1624     assert(_mutable_data_size == _relocation_size + metadata_size + jvmci_data_size,
1625            "wrong mutable data size: %d != %d + %d + %d",
1626            _mutable_data_size, _relocation_size, metadata_size, jvmci_data_size);
1627     assert(nmethod_size == data_end() - header_begin(), "wrong nmethod size: %d != %d",
1628            nmethod_size, (int)(code_end() - header_begin()));
1629 
1630     _immutable_data_size  = immutable_data_size;
1631     if (immutable_data_size > 0) {
1632       assert(immutable_data != nullptr, "required");
1633       _immutable_data     = immutable_data;
1634     } else {
1635       // We need unique not null address
1636       _immutable_data     = blob_end();
1637     }
1638     CHECKED_CAST(_nul_chk_table_offset, uint16_t, (align_up((int)dependencies->size_in_bytes(), oopSize)));
1639     CHECKED_CAST(_handler_table_offset, uint16_t, (_nul_chk_table_offset + align_up(nul_chk_table->size_in_bytes(), oopSize)));
1640     _scopes_pcs_offset    = _handler_table_offset + align_up(handler_table->size_in_bytes(), oopSize);
1641     _scopes_data_offset   = _scopes_pcs_offset    + adjust_pcs_size(debug_info->pcs_size());
1642 
1643 #if INCLUDE_JVMCI
1644     _speculations_offset  = _scopes_data_offset   + align_up(debug_info->data_size(), oopSize);
1645     DEBUG_ONLY( int immutable_data_end_offset = _speculations_offset  + align_up(speculations_len, oopSize); )
1646 #else
1647     DEBUG_ONLY( int immutable_data_end_offset = _scopes_data_offset + align_up(debug_info->data_size(), oopSize); )
1648 #endif
1649     assert(immutable_data_end_offset <= immutable_data_size, "wrong read-only data size: %d > %d",
1650            immutable_data_end_offset, immutable_data_size);
1651 
1652     // Copy code and relocation info
1653     code_buffer->copy_code_and_locs_to(this);
1654     // Copy oops and metadata
1655     code_buffer->copy_values_to(this);
1656     dependencies->copy_to(this);
1657     // Copy PcDesc and ScopeDesc data
1658     debug_info->copy_to(this);
1659 
1660     // Create cache after PcDesc data is copied - it will be used to initialize cache
1661     _pc_desc_container = new PcDescContainer(scopes_pcs_begin());
1662 
1663 #if INCLUDE_JVMCI
1664     if (compiler->is_jvmci()) {
1665       // Initialize the JVMCINMethodData object inlined into nm
1666       jvmci_nmethod_data()->copy(jvmci_data);
1667     }
1668 #endif
1669 
1670     // Copy contents of ExceptionHandlerTable to nmethod
1671     handler_table->copy_to(this);
1672     nul_chk_table->copy_to(this);
1673 
1674 #if INCLUDE_JVMCI
1675     // Copy speculations to nmethod
1676     if (speculations_size() != 0) {
1677       memcpy(speculations_begin(), speculations, speculations_len);
1678     }
1679 #endif
1680 
1681     post_init();
1682 
1683     // we use the information of entry points to find out if a method is
1684     // static or non static
1685     assert(compiler->is_c2() || compiler->is_jvmci() ||
1686            _method->is_static() == (entry_point() == verified_entry_point()),
1687            " entry points must be same for static methods and vice versa");
1688   }
1689 }
1690 
1691 // Print a short set of xml attributes to identify this nmethod.  The
1692 // output should be embedded in some other element.
1693 void nmethod::log_identity(xmlStream* log) const {
1694   assert(log->inside_attrs_or_error(), "printing attributes");
1695   log->print(" compile_id='%d'", compile_id());
1696   const char* nm_kind = compile_kind();
1697   if (nm_kind != nullptr)  log->print(" compile_kind='%s'", nm_kind);
1698   log->print(" compiler='%s'", compiler_name());
1699   if (TieredCompilation) {
1700     log->print(" compile_level='%d'", comp_level());
1701   }
1702 #if INCLUDE_JVMCI
1703   if (jvmci_nmethod_data() != nullptr) {
1704     const char* jvmci_name = jvmci_nmethod_data()->name();
1705     if (jvmci_name != nullptr) {
1706       log->print(" jvmci_mirror_name='");
1707       log->text("%s", jvmci_name);
1708       log->print("'");
1709     }
1710   }
1711 #endif
1712 }
1713 
1714 
1715 #define LOG_OFFSET(log, name)                    \
1716   if (p2i(name##_end()) - p2i(name##_begin())) \
1717     log->print(" " XSTR(name) "_offset='%zd'"    , \
1718                p2i(name##_begin()) - p2i(this))
1719 
1720 
1721 void nmethod::log_new_nmethod() const {
1722   if (LogCompilation && xtty != nullptr) {
1723     ttyLocker ttyl;
1724     xtty->begin_elem("nmethod");
1725     log_identity(xtty);
1726     xtty->print(" entry='" INTPTR_FORMAT "' size='%d'", p2i(code_begin()), size());
1727     xtty->print(" address='" INTPTR_FORMAT "'", p2i(this));
1728 
1729     LOG_OFFSET(xtty, relocation);
1730     LOG_OFFSET(xtty, consts);
1731     LOG_OFFSET(xtty, insts);
1732     LOG_OFFSET(xtty, stub);
1733     LOG_OFFSET(xtty, scopes_data);
1734     LOG_OFFSET(xtty, scopes_pcs);
1735     LOG_OFFSET(xtty, dependencies);
1736     LOG_OFFSET(xtty, handler_table);
1737     LOG_OFFSET(xtty, nul_chk_table);
1738     LOG_OFFSET(xtty, oops);
1739     LOG_OFFSET(xtty, metadata);
1740 
1741     xtty->method(method());
1742     xtty->stamp();
1743     xtty->end_elem();
1744   }
1745 }
1746 
1747 #undef LOG_OFFSET
1748 
1749 
1750 // Print out more verbose output usually for a newly created nmethod.
1751 void nmethod::print_on_with_msg(outputStream* st, const char* msg) const {
1752   if (st != nullptr) {
1753     ttyLocker ttyl;
1754     if (WizardMode) {
1755       CompileTask::print(st, this, msg, /*short_form:*/ true);
1756       st->print_cr(" (" INTPTR_FORMAT ")", p2i(this));
1757     } else {
1758       CompileTask::print(st, this, msg, /*short_form:*/ false);
1759     }
1760   }
1761 }
1762 
1763 void nmethod::maybe_print_nmethod(const DirectiveSet* directive) {
1764   bool printnmethods = directive->PrintAssemblyOption || directive->PrintNMethodsOption;
1765   if (printnmethods || PrintDebugInfo || PrintRelocations || PrintDependencies || PrintExceptionHandlers) {
1766     print_nmethod(printnmethods);
1767   }
1768 }
1769 
1770 void nmethod::print_nmethod(bool printmethod) {
1771   ttyLocker ttyl;  // keep the following output all in one block
1772   if (xtty != nullptr) {
1773     xtty->begin_head("print_nmethod");
1774     log_identity(xtty);
1775     xtty->stamp();
1776     xtty->end_head();
1777   }
1778   // Print the header part, then print the requested information.
1779   // This is both handled in decode2().
1780   if (printmethod) {
1781     ResourceMark m;
1782     if (is_compiled_by_c1()) {
1783       tty->cr();
1784       tty->print_cr("============================= C1-compiled nmethod ==============================");
1785     }
1786     if (is_compiled_by_jvmci()) {
1787       tty->cr();
1788       tty->print_cr("=========================== JVMCI-compiled nmethod =============================");
1789     }
1790     tty->print_cr("----------------------------------- Assembly -----------------------------------");
1791     decode2(tty);
1792 #if defined(SUPPORT_DATA_STRUCTS)
1793     if (AbstractDisassembler::show_structs()) {
1794       // Print the oops from the underlying CodeBlob as well.
1795       tty->print_cr("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ");
1796       print_oops(tty);
1797       tty->print_cr("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ");
1798       print_metadata(tty);
1799       tty->print_cr("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ");
1800       print_pcs_on(tty);
1801       tty->print_cr("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ");
1802       if (oop_maps() != nullptr) {
1803         tty->print("oop maps:"); // oop_maps()->print_on(tty) outputs a cr() at the beginning
1804         oop_maps()->print_on(tty);
1805         tty->print_cr("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ");
1806       }
1807     }
1808 #endif
1809   } else {
1810     print(); // print the header part only.
1811   }
1812 
1813 #if defined(SUPPORT_DATA_STRUCTS)
1814   if (AbstractDisassembler::show_structs()) {
1815     methodHandle mh(Thread::current(), _method);
1816     if (printmethod || PrintDebugInfo || CompilerOracle::has_option(mh, CompileCommandEnum::PrintDebugInfo)) {
1817       print_scopes();
1818       tty->print_cr("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ");
1819     }
1820     if (printmethod || PrintRelocations || CompilerOracle::has_option(mh, CompileCommandEnum::PrintRelocations)) {
1821       print_relocations_on(tty);
1822       tty->print_cr("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ");
1823     }
1824     if (printmethod || PrintDependencies || CompilerOracle::has_option(mh, CompileCommandEnum::PrintDependencies)) {
1825       print_dependencies_on(tty);
1826       tty->print_cr("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ");
1827     }
1828     if (printmethod || PrintExceptionHandlers) {
1829       print_handler_table();
1830       tty->print_cr("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ");
1831       print_nul_chk_table();
1832       tty->print_cr("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ");
1833     }
1834 
1835     if (printmethod) {
1836       print_recorded_oops();
1837       tty->print_cr("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ");
1838       print_recorded_metadata();
1839       tty->print_cr("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ");
1840     }
1841   }
1842 #endif
1843 
1844   if (xtty != nullptr) {
1845     xtty->tail("print_nmethod");
1846   }
1847 }
1848 
1849 
1850 // Promote one word from an assembly-time handle to a live embedded oop.
1851 inline void nmethod::initialize_immediate_oop(oop* dest, jobject handle) {
1852   if (handle == nullptr ||
1853       // As a special case, IC oops are initialized to 1 or -1.
1854       handle == (jobject) Universe::non_oop_word()) {
1855     *(void**)dest = handle;
1856   } else {
1857     *dest = JNIHandles::resolve_non_null(handle);
1858   }
1859 }
1860 
1861 void nmethod::copy_values(GrowableArray<Handle>* array) {
1862   int length = array->length();
1863   assert((address)(oops_begin() + length) <= (address)oops_end(), "oops big enough");
1864   oop* dest = oops_begin();
1865   for (int index = 0 ; index < length; index++) {
1866     dest[index] = array->at(index)();
1867   }
1868 }
1869 
1870 // Have to have the same name because it's called by a template
1871 void nmethod::copy_values(GrowableArray<jobject>* array) {
1872   int length = array->length();
1873   assert((address)(oops_begin() + length) <= (address)oops_end(), "oops big enough");
1874   oop* dest = oops_begin();
1875   for (int index = 0 ; index < length; index++) {
1876     initialize_immediate_oop(&dest[index], array->at(index));
1877   }
1878 
1879   // Now we can fix up all the oops in the code.  We need to do this
1880   // in the code because the assembler uses jobjects as placeholders.
1881   // The code and relocations have already been initialized by the
1882   // CodeBlob constructor, so it is valid even at this early point to
1883   // iterate over relocations and patch the code.
1884   fix_oop_relocations(nullptr, nullptr, /*initialize_immediates=*/ true);
1885 }
1886 
1887 void nmethod::copy_values(GrowableArray<Metadata*>* array) {
1888   int length = array->length();
1889   assert((address)(metadata_begin() + length) <= (address)metadata_end(), "big enough");
1890   Metadata** dest = metadata_begin();
1891   for (int index = 0 ; index < length; index++) {
1892     dest[index] = array->at(index);
1893   }
1894 }
1895 
1896 void nmethod::fix_oop_relocations(address begin, address end, bool initialize_immediates) {
1897   // re-patch all oop-bearing instructions, just in case some oops moved
1898   RelocIterator iter(this, begin, end);
1899   while (iter.next()) {
1900     if (iter.type() == relocInfo::oop_type) {
1901       oop_Relocation* reloc = iter.oop_reloc();
1902       if (initialize_immediates && reloc->oop_is_immediate()) {
1903         oop* dest = reloc->oop_addr();
1904         jobject obj = *reinterpret_cast<jobject*>(dest);
1905         initialize_immediate_oop(dest, obj);
1906       }
1907       // Refresh the oop-related bits of this instruction.
1908       reloc->fix_oop_relocation();
1909     } else if (iter.type() == relocInfo::metadata_type) {
1910       metadata_Relocation* reloc = iter.metadata_reloc();
1911       reloc->fix_metadata_relocation();
1912     }
1913   }
1914 }
1915 
1916 void nmethod::create_reloc_immediates_list(JavaThread* thread, GrowableArray<Handle>& oop_list, GrowableArray<Metadata*>& metadata_list) {
1917   RelocIterator iter(this);
1918   while (iter.next()) {
1919     if (iter.type() == relocInfo::oop_type) {
1920       oop_Relocation* reloc = iter.oop_reloc();
1921       if (reloc->oop_is_immediate()) {
1922         oop dest = reloc->oop_value();
1923         Handle h(thread, dest);
1924         oop_list.append(h);
1925       }
1926     } else if (iter.type() == relocInfo::metadata_type) {
1927       metadata_Relocation* reloc = iter.metadata_reloc();
1928       if (reloc->metadata_is_immediate()) {
1929         Metadata* m = reloc->metadata_value();
1930         metadata_list.append(m);
1931       }
1932     }
1933   }
1934 }
1935 
1936 static void install_post_call_nop_displacement(nmethod* nm, address pc) {
1937   NativePostCallNop* nop = nativePostCallNop_at((address) pc);
1938   intptr_t cbaddr = (intptr_t) nm;
1939   intptr_t offset = ((intptr_t) pc) - cbaddr;
1940 
1941   int oopmap_slot = nm->oop_maps()->find_slot_for_offset(int((intptr_t) pc - (intptr_t) nm->code_begin()));
1942   if (oopmap_slot < 0) { // this can happen at asynchronous (non-safepoint) stackwalks
1943     log_debug(codecache)("failed to find oopmap for cb: " INTPTR_FORMAT " offset: %d", cbaddr, (int) offset);
1944   } else if (!nop->patch(oopmap_slot, offset)) {
1945     log_debug(codecache)("failed to encode %d %d", oopmap_slot, (int) offset);
1946   }
1947 }
1948 
1949 void nmethod::finalize_relocations() {
1950   NoSafepointVerifier nsv;
1951 
1952   GrowableArray<NativeMovConstReg*> virtual_call_data;
1953 
1954   // Make sure that post call nops fill in nmethod offsets eagerly so
1955   // we don't have to race with deoptimization
1956   RelocIterator iter(this);
1957   while (iter.next()) {
1958     if (iter.type() == relocInfo::virtual_call_type) {
1959       virtual_call_Relocation* r = iter.virtual_call_reloc();
1960       NativeMovConstReg* value = nativeMovConstReg_at(r->cached_value());
1961       virtual_call_data.append(value);
1962     } else if (iter.type() == relocInfo::post_call_nop_type) {
1963       post_call_nop_Relocation* const reloc = iter.post_call_nop_reloc();
1964       address pc = reloc->addr();
1965       install_post_call_nop_displacement(this, pc);
1966     }
1967   }
1968 
1969   if (virtual_call_data.length() > 0) {
1970     // We allocate a block of CompiledICData per nmethod so the GC can purge this faster.
1971     _compiled_ic_data = new CompiledICData[virtual_call_data.length()];
1972     CompiledICData* next_data = _compiled_ic_data;
1973 
1974     for (NativeMovConstReg* value : virtual_call_data) {
1975       value->set_data((intptr_t)next_data);
1976       next_data++;
1977     }
1978   }
1979 }
1980 
1981 void nmethod::make_deoptimized() {
1982   if (!Continuations::enabled()) {
1983     // Don't deopt this again.
1984     set_deoptimized_done();
1985     return;
1986   }
1987 
1988   assert(method() == nullptr || can_be_deoptimized(), "");
1989 
1990   CompiledICLocker ml(this);
1991   assert(CompiledICLocker::is_safe(this), "mt unsafe call");
1992 
1993   // If post call nops have been already patched, we can just bail-out.
1994   if (has_been_deoptimized()) {
1995     return;
1996   }
1997 
1998   ResourceMark rm;
1999   RelocIterator iter(this, oops_reloc_begin());
2000 
2001   while (iter.next()) {
2002 
2003     switch (iter.type()) {
2004       case relocInfo::virtual_call_type: {
2005         CompiledIC *ic = CompiledIC_at(&iter);
2006         address pc = ic->end_of_call();
2007         NativePostCallNop* nop = nativePostCallNop_at(pc);
2008         if (nop != nullptr) {
2009           nop->make_deopt();
2010         }
2011         assert(NativeDeoptInstruction::is_deopt_at(pc), "check");
2012         break;
2013       }
2014       case relocInfo::static_call_type:
2015       case relocInfo::opt_virtual_call_type: {
2016         CompiledDirectCall *csc = CompiledDirectCall::at(iter.reloc());
2017         address pc = csc->end_of_call();
2018         NativePostCallNop* nop = nativePostCallNop_at(pc);
2019         //tty->print_cr(" - static pc %p", pc);
2020         if (nop != nullptr) {
2021           nop->make_deopt();
2022         }
2023         // We can't assert here, there are some calls to stubs / runtime
2024         // that have reloc data and doesn't have a post call NOP.
2025         //assert(NativeDeoptInstruction::is_deopt_at(pc), "check");
2026         break;
2027       }
2028       default:
2029         break;
2030     }
2031   }
2032   // Don't deopt this again.
2033   set_deoptimized_done();
2034 }
2035 
2036 void nmethod::verify_clean_inline_caches() {
2037   assert(CompiledICLocker::is_safe(this), "mt unsafe call");
2038 
2039   ResourceMark rm;
2040   RelocIterator iter(this, oops_reloc_begin());
2041   while(iter.next()) {
2042     switch(iter.type()) {
2043       case relocInfo::virtual_call_type: {
2044         CompiledIC *ic = CompiledIC_at(&iter);
2045         CodeBlob *cb = CodeCache::find_blob(ic->destination());
2046         assert(cb != nullptr, "destination not in CodeBlob?");
2047         nmethod* nm = cb->as_nmethod_or_null();
2048         if (nm != nullptr) {
2049           // Verify that inline caches pointing to bad nmethods are clean
2050           if (!nm->is_in_use() || nm->is_unloading()) {
2051             assert(ic->is_clean(), "IC should be clean");
2052           }
2053         }
2054         break;
2055       }
2056       case relocInfo::static_call_type:
2057       case relocInfo::opt_virtual_call_type: {
2058         CompiledDirectCall *cdc = CompiledDirectCall::at(iter.reloc());
2059         CodeBlob *cb = CodeCache::find_blob(cdc->destination());
2060         assert(cb != nullptr, "destination not in CodeBlob?");
2061         nmethod* nm = cb->as_nmethod_or_null();
2062         if (nm != nullptr) {
2063           // Verify that inline caches pointing to bad nmethods are clean
2064           if (!nm->is_in_use() || nm->is_unloading() || nm->method()->code() != nm) {
2065             assert(cdc->is_clean(), "IC should be clean");
2066           }
2067         }
2068         break;
2069       }
2070       default:
2071         break;
2072     }
2073   }
2074 }
2075 
2076 void nmethod::mark_as_maybe_on_stack() {
2077   AtomicAccess::store(&_gc_epoch, CodeCache::gc_epoch());
2078 }
2079 
2080 bool nmethod::is_maybe_on_stack() {
2081   // If the condition below is true, it means that the nmethod was found to
2082   // be alive the previous completed marking cycle.
2083   return AtomicAccess::load(&_gc_epoch) >= CodeCache::previous_completed_gc_marking_cycle();
2084 }
2085 
2086 void nmethod::inc_decompile_count() {
2087   if (!is_compiled_by_c2() && !is_compiled_by_jvmci()) return;
2088   // Could be gated by ProfileTraps, but do not bother...
2089 #if INCLUDE_JVMCI
2090   if (jvmci_skip_profile_deopt()) {
2091     return;
2092   }
2093 #endif
2094   Method* m = method();
2095   if (m == nullptr)  return;
2096   MethodData* mdo = m->method_data();
2097   if (mdo == nullptr)  return;
2098   // There is a benign race here.  See comments in methodData.hpp.
2099   mdo->inc_decompile_count();
2100 }
2101 
2102 void nmethod::inc_method_profiling_count() {
2103   AtomicAccess::inc(&_method_profiling_count);
2104 }
2105 
2106 uint64_t nmethod::method_profiling_count() {
2107   return _method_profiling_count;
2108 }
2109 
2110 bool nmethod::try_transition(signed char new_state_int) {
2111   signed char new_state = new_state_int;
2112   assert_lock_strong(NMethodState_lock);
2113   signed char old_state = _state;
2114   if (old_state >= new_state) {
2115     // Ensure monotonicity of transitions.
2116     return false;
2117   }
2118   AtomicAccess::store(&_state, new_state);
2119   return true;
2120 }
2121 
2122 void nmethod::invalidate_osr_method() {
2123   assert(_entry_bci != InvocationEntryBci, "wrong kind of nmethod");
2124   // Remove from list of active nmethods
2125   if (method() != nullptr) {
2126     method()->method_holder()->remove_osr_nmethod(this);
2127   }
2128 }
2129 
2130 void nmethod::log_state_change(InvalidationReason invalidation_reason) const {
2131   if (LogCompilation) {
2132     if (xtty != nullptr) {
2133       ttyLocker ttyl;  // keep the following output all in one block
2134       xtty->begin_elem("make_not_entrant thread='%zu' reason='%s'",
2135                        os::current_thread_id(), invalidation_reason_to_string(invalidation_reason));
2136       log_identity(xtty);
2137       xtty->stamp();
2138       xtty->end_elem();
2139     }
2140   }
2141 
2142   ResourceMark rm;
2143   stringStream ss(NEW_RESOURCE_ARRAY(char, 256), 256);
2144   ss.print("made not entrant: %s", invalidation_reason_to_string(invalidation_reason));
2145 
2146   CompileTask::print_ul(this, ss.freeze());
2147   if (PrintCompilation) {
2148     print_on_with_msg(tty, ss.freeze());
2149   }
2150 }
2151 
2152 void nmethod::unlink_from_method() {
2153   if (method() != nullptr) {
2154     method()->unlink_code(this);
2155   }
2156 }
2157 
2158 // Invalidate code
2159 bool nmethod::make_not_entrant(InvalidationReason invalidation_reason, bool keep_aot_entry) {
2160   // This can be called while the system is already at a safepoint which is ok
2161   NoSafepointVerifier nsv;
2162 
2163   if (is_unloading()) {
2164     // If the nmethod is unloading, then it is already not entrant through
2165     // the nmethod entry barriers. No need to do anything; GC will unload it.
2166     return false;
2167   }
2168 
2169   if (AtomicAccess::load(&_state) == not_entrant) {
2170     // Avoid taking the lock if already in required state.
2171     // This is safe from races because the state is an end-state,
2172     // which the nmethod cannot back out of once entered.
2173     // No need for fencing either.
2174     return false;
2175   }
2176 
2177   {
2178     // Enter critical section.  Does not block for safepoint.
2179     ConditionalMutexLocker ml(NMethodState_lock, !NMethodState_lock->owned_by_self(), Mutex::_no_safepoint_check_flag);
2180 
2181     if (AtomicAccess::load(&_state) == not_entrant) {
2182       // another thread already performed this transition so nothing
2183       // to do, but return false to indicate this.
2184       return false;
2185     }
2186 
2187     if (is_osr_method()) {
2188       // This logic is equivalent to the logic below for patching the
2189       // verified entry point of regular methods.
2190       // this effectively makes the osr nmethod not entrant
2191       invalidate_osr_method();
2192     } else {
2193       // The caller can be calling the method statically or through an inline
2194       // cache call.
2195       BarrierSet::barrier_set()->barrier_set_nmethod()->make_not_entrant(this);
2196     }
2197 
2198     if (update_recompile_counts()) {
2199       // Mark the method as decompiled.
2200       inc_decompile_count();
2201     }
2202 
2203     BarrierSetNMethod* bs_nm = BarrierSet::barrier_set()->barrier_set_nmethod();
2204     if (bs_nm == nullptr || !bs_nm->supports_entry_barrier(this)) {
2205       // If nmethod entry barriers are not supported, we won't mark
2206       // nmethods as on-stack when they become on-stack. So we
2207       // degrade to a less accurate flushing strategy, for now.
2208       mark_as_maybe_on_stack();
2209     }
2210 
2211     // Change state
2212     bool success = try_transition(not_entrant);
2213     assert(success, "Transition can't fail");
2214 
2215     // Log the transition once
2216     log_state_change(invalidation_reason);
2217 
2218     // Remove nmethod from method.
2219     unlink_from_method();
2220 
2221     if (!keep_aot_entry) {
2222       // Keep AOT code if it was simply replaced
2223       // otherwise make it not entrant too.
2224       AOTCodeCache::invalidate(_aot_code_entry);
2225     }
2226 
2227     CompileBroker::log_not_entrant(this);
2228   } // leave critical region under NMethodState_lock
2229 
2230 #if INCLUDE_JVMCI
2231   // Invalidate can't occur while holding the NMethodState_lock
2232   JVMCINMethodData* nmethod_data = jvmci_nmethod_data();
2233   if (nmethod_data != nullptr) {
2234     nmethod_data->invalidate_nmethod_mirror(this, invalidation_reason);
2235   }
2236 #endif
2237 
2238 #ifdef ASSERT
2239   if (is_osr_method() && method() != nullptr) {
2240     // Make sure osr nmethod is invalidated, i.e. not on the list
2241     bool found = method()->method_holder()->remove_osr_nmethod(this);
2242     assert(!found, "osr nmethod should have been invalidated");
2243   }
2244 #endif
2245 
2246   return true;
2247 }
2248 
2249 // For concurrent GCs, there must be a handshake between unlink and flush
2250 void nmethod::unlink() {
2251   if (is_unlinked()) {
2252     // Already unlinked.
2253     return;
2254   }
2255 
2256   flush_dependencies();
2257 
2258   // unlink_from_method will take the NMethodState_lock.
2259   // In this case we don't strictly need it when unlinking nmethods from
2260   // the Method, because it is only concurrently unlinked by
2261   // the entry barrier, which acquires the per nmethod lock.
2262   unlink_from_method();
2263 
2264   if (is_osr_method()) {
2265     invalidate_osr_method();
2266   }
2267 
2268 #if INCLUDE_JVMCI
2269   // Clear the link between this nmethod and a HotSpotNmethod mirror
2270   JVMCINMethodData* nmethod_data = jvmci_nmethod_data();
2271   if (nmethod_data != nullptr) {
2272     nmethod_data->invalidate_nmethod_mirror(this, is_cold() ?
2273             nmethod::InvalidationReason::UNLOADING_COLD :
2274             nmethod::InvalidationReason::UNLOADING);
2275   }
2276 #endif
2277 
2278   // Post before flushing as jmethodID is being used
2279   post_compiled_method_unload();
2280 
2281   // Register for flushing when it is safe. For concurrent class unloading,
2282   // that would be after the unloading handshake, and for STW class unloading
2283   // that would be when getting back to the VM thread.
2284   ClassUnloadingContext::context()->register_unlinked_nmethod(this);
2285 }
2286 
2287 void nmethod::purge(bool unregister_nmethod) {
2288 
2289   MutexLocker ml(CodeCache_lock, Mutex::_no_safepoint_check_flag);
2290 
2291   // completely deallocate this method
2292   Events::log_nmethod_flush(Thread::current(), "flushing %s nmethod " INTPTR_FORMAT, compile_kind(), p2i(this));
2293 
2294   LogTarget(Debug, codecache) lt;
2295   if (lt.is_enabled()) {
2296     ResourceMark rm;
2297     LogStream ls(lt);
2298     const char* method_name = method()->name()->as_C_string();
2299     const size_t codecache_capacity = CodeCache::capacity()/1024;
2300     const size_t codecache_free_space = CodeCache::unallocated_capacity(CodeCache::get_code_blob_type(this))/1024;
2301     ls.print("Flushing %s nmethod %6d/" INTPTR_FORMAT ", level=%d, cold=%d, epoch=" UINT64_FORMAT ", cold_count=" UINT64_FORMAT ". "
2302               "Cache capacity: %zuKb, free space: %zuKb. method %s (%s)",
2303               compile_kind(), _compile_id, p2i(this), _comp_level, is_cold(), _gc_epoch, CodeCache::cold_gc_count(),
2304               codecache_capacity, codecache_free_space, method_name, compiler_name());
2305   }
2306 
2307   // We need to deallocate any ExceptionCache data.
2308   // Note that we do not need to grab the nmethod lock for this, it
2309   // better be thread safe if we're disposing of it!
2310   ExceptionCache* ec = exception_cache();
2311   while(ec != nullptr) {
2312     ExceptionCache* next = ec->next();
2313     delete ec;
2314     ec = next;
2315   }
2316   if (_pc_desc_container != nullptr) {
2317     delete _pc_desc_container;
2318   }
2319   if (_compiled_ic_data != nullptr) {
2320     delete[] _compiled_ic_data;
2321   }
2322 
2323   if (_immutable_data != data_end() && !AOTCodeCache::is_address_in_aot_cache((address)_oop_maps)) {
2324     os::free(_immutable_data);
2325     _immutable_data = blob_end(); // Valid not null address
2326   }
2327   if (unregister_nmethod) {
2328     Universe::heap()->unregister_nmethod(this);
2329   }
2330   CodeCache::unregister_old_nmethod(this);
2331 
2332   JVMCI_ONLY( _metadata_size = 0; )
2333   CodeBlob::purge();
2334 }
2335 
2336 oop nmethod::oop_at(int index) const {
2337   if (index == 0) {
2338     return nullptr;
2339   }
2340 
2341   BarrierSetNMethod* bs_nm = BarrierSet::barrier_set()->barrier_set_nmethod();
2342   return bs_nm->oop_load_no_keepalive(this, index);
2343 }
2344 
2345 oop nmethod::oop_at_phantom(int index) const {
2346   if (index == 0) {
2347     return nullptr;
2348   }
2349 
2350   BarrierSetNMethod* bs_nm = BarrierSet::barrier_set()->barrier_set_nmethod();
2351   return bs_nm->oop_load_phantom(this, index);
2352 }
2353 
2354 //
2355 // Notify all classes this nmethod is dependent on that it is no
2356 // longer dependent.
2357 
2358 void nmethod::flush_dependencies() {
2359   if (!has_flushed_dependencies()) {
2360     set_has_flushed_dependencies(true);
2361     for (Dependencies::DepStream deps(this); deps.next(); ) {
2362       if (deps.type() == Dependencies::call_site_target_value) {
2363         // CallSite dependencies are managed on per-CallSite instance basis.
2364         oop call_site = deps.argument_oop(0);
2365         MethodHandles::clean_dependency_context(call_site);
2366       } else {
2367         InstanceKlass* ik = deps.context_type();
2368         if (ik == nullptr) {
2369           continue;  // ignore things like evol_method
2370         }
2371         // During GC liveness of dependee determines class that needs to be updated.
2372         // The GC may clean dependency contexts concurrently and in parallel.
2373         ik->clean_dependency_context();
2374       }
2375     }
2376   }
2377 }
2378 
2379 void nmethod::post_compiled_method(CompileTask* task) {
2380   task->mark_success();
2381   task->set_nm_content_size(content_size());
2382   task->set_nm_insts_size(insts_size());
2383   task->set_nm_total_size(total_size());
2384 
2385   // task->is_aot_load() is true only for loaded AOT code.
2386   // nmethod::_aot_code_entry is set for loaded and stored AOT code
2387   // to invalidate the entry when nmethod is deoptimized.
2388   // VerifyAOTCode is option to not store in archive AOT code.
2389   guarantee((_aot_code_entry != nullptr) || !task->is_aot_load() || VerifyAOTCode, "sanity");
2390 
2391   // JVMTI -- compiled method notification (must be done outside lock)
2392   post_compiled_method_load_event();
2393 
2394   if (CompilationLog::log() != nullptr) {
2395     CompilationLog::log()->log_nmethod(JavaThread::current(), this);
2396   }
2397 
2398   const DirectiveSet* directive = task->directive();
2399   maybe_print_nmethod(directive);
2400 }
2401 
2402 // ------------------------------------------------------------------
2403 // post_compiled_method_load_event
2404 // new method for install_code() path
2405 // Transfer information from compilation to jvmti
2406 void nmethod::post_compiled_method_load_event(JvmtiThreadState* state) {
2407   // This is a bad time for a safepoint.  We don't want
2408   // this nmethod to get unloaded while we're queueing the event.
2409   NoSafepointVerifier nsv;
2410 
2411   Method* m = method();
2412   HOTSPOT_COMPILED_METHOD_LOAD(
2413       (char *) m->klass_name()->bytes(),
2414       m->klass_name()->utf8_length(),
2415       (char *) m->name()->bytes(),
2416       m->name()->utf8_length(),
2417       (char *) m->signature()->bytes(),
2418       m->signature()->utf8_length(),
2419       insts_begin(), insts_size());
2420 
2421 
2422   if (JvmtiExport::should_post_compiled_method_load()) {
2423     // Only post unload events if load events are found.
2424     set_load_reported();
2425     // If a JavaThread hasn't been passed in, let the Service thread
2426     // (which is a real Java thread) post the event
2427     JvmtiDeferredEvent event = JvmtiDeferredEvent::compiled_method_load_event(this);
2428     if (state == nullptr) {
2429       // Execute any barrier code for this nmethod as if it's called, since
2430       // keeping it alive looks like stack walking.
2431       run_nmethod_entry_barrier();
2432       ServiceThread::enqueue_deferred_event(&event);
2433     } else {
2434       // This enters the nmethod barrier outside in the caller.
2435       state->enqueue_event(&event);
2436     }
2437   }
2438 }
2439 
2440 void nmethod::post_compiled_method_unload() {
2441   assert(_method != nullptr, "just checking");
2442   DTRACE_METHOD_UNLOAD_PROBE(method());
2443 
2444   // If a JVMTI agent has enabled the CompiledMethodUnload event then
2445   // post the event. The Method* will not be valid when this is freed.
2446 
2447   // Don't bother posting the unload if the load event wasn't posted.
2448   if (load_reported() && JvmtiExport::should_post_compiled_method_unload()) {
2449     JvmtiDeferredEvent event =
2450       JvmtiDeferredEvent::compiled_method_unload_event(
2451           method()->jmethod_id(), insts_begin());
2452     ServiceThread::enqueue_deferred_event(&event);
2453   }
2454 }
2455 
2456 // Iterate over metadata calling this function.   Used by RedefineClasses
2457 void nmethod::metadata_do(MetadataClosure* f) {
2458   {
2459     // Visit all immediate references that are embedded in the instruction stream.
2460     RelocIterator iter(this, oops_reloc_begin());
2461     while (iter.next()) {
2462       if (iter.type() == relocInfo::metadata_type) {
2463         metadata_Relocation* r = iter.metadata_reloc();
2464         // In this metadata, we must only follow those metadatas directly embedded in
2465         // the code.  Other metadatas (oop_index>0) are seen as part of
2466         // the metadata section below.
2467         assert(1 == (r->metadata_is_immediate()) +
2468                (r->metadata_addr() >= metadata_begin() && r->metadata_addr() < metadata_end()),
2469                "metadata must be found in exactly one place");
2470         if (r->metadata_is_immediate() && r->metadata_value() != nullptr) {
2471           Metadata* md = r->metadata_value();
2472           if (md != _method) f->do_metadata(md);
2473         }
2474       } else if (iter.type() == relocInfo::virtual_call_type) {
2475         // Check compiledIC holders associated with this nmethod
2476         ResourceMark rm;
2477         CompiledIC *ic = CompiledIC_at(&iter);
2478         ic->metadata_do(f);
2479       }
2480     }
2481   }
2482 
2483   // Visit the metadata section
2484   for (Metadata** p = metadata_begin(); p < metadata_end(); p++) {
2485     if (*p == Universe::non_oop_word() || *p == nullptr)  continue;  // skip non-oops
2486     Metadata* md = *p;
2487     f->do_metadata(md);
2488   }
2489 
2490   // Visit metadata not embedded in the other places.
2491   if (_method != nullptr) f->do_metadata(_method);
2492 }
2493 
2494 // Heuristic for nuking nmethods even though their oops are live.
2495 // Main purpose is to reduce code cache pressure and get rid of
2496 // nmethods that don't seem to be all that relevant any longer.
2497 bool nmethod::is_cold() {
2498   if (!MethodFlushing || is_native_method() || is_not_installed()) {
2499     // No heuristic unloading at all
2500     return false;
2501   }
2502 
2503   if (!is_maybe_on_stack() && is_not_entrant()) {
2504     // Not entrant nmethods that are not on any stack can just
2505     // be removed
2506     return true;
2507   }
2508 
2509   BarrierSetNMethod* bs_nm = BarrierSet::barrier_set()->barrier_set_nmethod();
2510   if (bs_nm == nullptr || !bs_nm->supports_entry_barrier(this)) {
2511     // On platforms that don't support nmethod entry barriers, we can't
2512     // trust the temporal aspect of the gc epochs. So we can't detect
2513     // cold nmethods on such platforms.
2514     return false;
2515   }
2516 
2517   if (!UseCodeCacheFlushing) {
2518     // Bail out if we don't heuristically remove nmethods
2519     return false;
2520   }
2521 
2522   // Other code can be phased out more gradually after N GCs
2523   return CodeCache::previous_completed_gc_marking_cycle() > _gc_epoch + 2 * CodeCache::cold_gc_count();
2524 }
2525 
2526 // The _is_unloading_state encodes a tuple comprising the unloading cycle
2527 // and the result of IsUnloadingBehaviour::is_unloading() for that cycle.
2528 // This is the bit layout of the _is_unloading_state byte: 00000CCU
2529 // CC refers to the cycle, which has 2 bits, and U refers to the result of
2530 // IsUnloadingBehaviour::is_unloading() for that unloading cycle.
2531 
2532 class IsUnloadingState: public AllStatic {
2533   static const uint8_t _is_unloading_mask = 1;
2534   static const uint8_t _is_unloading_shift = 0;
2535   static const uint8_t _unloading_cycle_mask = 6;
2536   static const uint8_t _unloading_cycle_shift = 1;
2537 
2538   static uint8_t set_is_unloading(uint8_t state, bool value) {
2539     state &= (uint8_t)~_is_unloading_mask;
2540     if (value) {
2541       state |= 1 << _is_unloading_shift;
2542     }
2543     assert(is_unloading(state) == value, "unexpected unloading cycle overflow");
2544     return state;
2545   }
2546 
2547   static uint8_t set_unloading_cycle(uint8_t state, uint8_t value) {
2548     state &= (uint8_t)~_unloading_cycle_mask;
2549     state |= (uint8_t)(value << _unloading_cycle_shift);
2550     assert(unloading_cycle(state) == value, "unexpected unloading cycle overflow");
2551     return state;
2552   }
2553 
2554 public:
2555   static bool is_unloading(uint8_t state) { return (state & _is_unloading_mask) >> _is_unloading_shift == 1; }
2556   static uint8_t unloading_cycle(uint8_t state) { return (state & _unloading_cycle_mask) >> _unloading_cycle_shift; }
2557 
2558   static uint8_t create(bool is_unloading, uint8_t unloading_cycle) {
2559     uint8_t state = 0;
2560     state = set_is_unloading(state, is_unloading);
2561     state = set_unloading_cycle(state, unloading_cycle);
2562     return state;
2563   }
2564 };
2565 
2566 bool nmethod::is_unloading() {
2567   uint8_t state = AtomicAccess::load(&_is_unloading_state);
2568   bool state_is_unloading = IsUnloadingState::is_unloading(state);
2569   if (state_is_unloading) {
2570     return true;
2571   }
2572   uint8_t state_unloading_cycle = IsUnloadingState::unloading_cycle(state);
2573   uint8_t current_cycle = CodeCache::unloading_cycle();
2574   if (state_unloading_cycle == current_cycle) {
2575     return false;
2576   }
2577 
2578   // The IsUnloadingBehaviour is responsible for calculating if the nmethod
2579   // should be unloaded. This can be either because there is a dead oop,
2580   // or because is_cold() heuristically determines it is time to unload.
2581   state_unloading_cycle = current_cycle;
2582   state_is_unloading = IsUnloadingBehaviour::is_unloading(this);
2583   uint8_t new_state = IsUnloadingState::create(state_is_unloading, state_unloading_cycle);
2584 
2585   // Note that if an nmethod has dead oops, everyone will agree that the
2586   // nmethod is_unloading. However, the is_cold heuristics can yield
2587   // different outcomes, so we guard the computed result with a CAS
2588   // to ensure all threads have a shared view of whether an nmethod
2589   // is_unloading or not.
2590   uint8_t found_state = AtomicAccess::cmpxchg(&_is_unloading_state, state, new_state, memory_order_relaxed);
2591 
2592   if (found_state == state) {
2593     // First to change state, we win
2594     return state_is_unloading;
2595   } else {
2596     // State already set, so use it
2597     return IsUnloadingState::is_unloading(found_state);
2598   }
2599 }
2600 
2601 void nmethod::clear_unloading_state() {
2602   uint8_t state = IsUnloadingState::create(false, CodeCache::unloading_cycle());
2603   AtomicAccess::store(&_is_unloading_state, state);
2604 }
2605 
2606 
2607 // This is called at the end of the strong tracing/marking phase of a
2608 // GC to unload an nmethod if it contains otherwise unreachable
2609 // oops or is heuristically found to be not important.
2610 void nmethod::do_unloading(bool unloading_occurred) {
2611   // Make sure the oop's ready to receive visitors
2612   if (is_unloading()) {
2613     unlink();
2614   } else {
2615     unload_nmethod_caches(unloading_occurred);
2616     BarrierSetNMethod* bs_nm = BarrierSet::barrier_set()->barrier_set_nmethod();
2617     if (bs_nm != nullptr) {
2618       bs_nm->disarm(this);
2619     }
2620   }
2621 }
2622 
2623 void nmethod::oops_do(OopClosure* f) {
2624   // Prevent extra code cache walk for platforms that don't have immediate oops.
2625   if (relocInfo::mustIterateImmediateOopsInCode()) {
2626     RelocIterator iter(this, oops_reloc_begin());
2627 
2628     while (iter.next()) {
2629       if (iter.type() == relocInfo::oop_type ) {
2630         oop_Relocation* r = iter.oop_reloc();
2631         // In this loop, we must only follow those oops directly embedded in
2632         // the code.  Other oops (oop_index>0) are seen as part of scopes_oops.
2633         assert(1 == (r->oop_is_immediate()) +
2634                (r->oop_addr() >= oops_begin() && r->oop_addr() < oops_end()),
2635                "oop must be found in exactly one place");
2636         if (r->oop_is_immediate() && r->oop_value() != nullptr) {
2637           f->do_oop(r->oop_addr());
2638         }
2639       }
2640     }
2641   }
2642 
2643   // Scopes
2644   // This includes oop constants not inlined in the code stream.
2645   for (oop* p = oops_begin(); p < oops_end(); p++) {
2646     if (*p == Universe::non_oop_word())  continue;  // skip non-oops
2647     f->do_oop(p);
2648   }
2649 }
2650 
2651 void nmethod::follow_nmethod(OopIterateClosure* cl) {
2652   // Process oops in the nmethod
2653   oops_do(cl);
2654 
2655   // CodeCache unloading support
2656   mark_as_maybe_on_stack();
2657 
2658   BarrierSetNMethod* bs_nm = BarrierSet::barrier_set()->barrier_set_nmethod();
2659   bs_nm->disarm(this);
2660 
2661   // There's an assumption made that this function is not used by GCs that
2662   // relocate objects, and therefore we don't call fix_oop_relocations.
2663 }
2664 
2665 nmethod* volatile nmethod::_oops_do_mark_nmethods;
2666 
2667 void nmethod::oops_do_log_change(const char* state) {
2668   LogTarget(Trace, gc, nmethod) lt;
2669   if (lt.is_enabled()) {
2670     LogStream ls(lt);
2671     CompileTask::print(&ls, this, state, true /* short_form */);
2672   }
2673 }
2674 
2675 bool nmethod::oops_do_try_claim() {
2676   if (oops_do_try_claim_weak_request()) {
2677     nmethod* result = oops_do_try_add_to_list_as_weak_done();
2678     assert(result == nullptr, "adding to global list as weak done must always succeed.");
2679     return true;
2680   }
2681   return false;
2682 }
2683 
2684 bool nmethod::oops_do_try_claim_weak_request() {
2685   assert(SafepointSynchronize::is_at_safepoint(), "only at safepoint");
2686 
2687   if ((_oops_do_mark_link == nullptr) &&
2688       (AtomicAccess::replace_if_null(&_oops_do_mark_link, mark_link(this, claim_weak_request_tag)))) {
2689     oops_do_log_change("oops_do, mark weak request");
2690     return true;
2691   }
2692   return false;
2693 }
2694 
2695 void nmethod::oops_do_set_strong_done(nmethod* old_head) {
2696   _oops_do_mark_link = mark_link(old_head, claim_strong_done_tag);
2697 }
2698 
2699 nmethod::oops_do_mark_link* nmethod::oops_do_try_claim_strong_done() {
2700   assert(SafepointSynchronize::is_at_safepoint(), "only at safepoint");
2701 
2702   oops_do_mark_link* old_next = AtomicAccess::cmpxchg(&_oops_do_mark_link, mark_link(nullptr, claim_weak_request_tag), mark_link(this, claim_strong_done_tag));
2703   if (old_next == nullptr) {
2704     oops_do_log_change("oops_do, mark strong done");
2705   }
2706   return old_next;
2707 }
2708 
2709 nmethod::oops_do_mark_link* nmethod::oops_do_try_add_strong_request(nmethod::oops_do_mark_link* next) {
2710   assert(SafepointSynchronize::is_at_safepoint(), "only at safepoint");
2711   assert(next == mark_link(this, claim_weak_request_tag), "Should be claimed as weak");
2712 
2713   oops_do_mark_link* old_next = AtomicAccess::cmpxchg(&_oops_do_mark_link, next, mark_link(this, claim_strong_request_tag));
2714   if (old_next == next) {
2715     oops_do_log_change("oops_do, mark strong request");
2716   }
2717   return old_next;
2718 }
2719 
2720 bool nmethod::oops_do_try_claim_weak_done_as_strong_done(nmethod::oops_do_mark_link* next) {
2721   assert(SafepointSynchronize::is_at_safepoint(), "only at safepoint");
2722   assert(extract_state(next) == claim_weak_done_tag, "Should be claimed as weak done");
2723 
2724   oops_do_mark_link* old_next = AtomicAccess::cmpxchg(&_oops_do_mark_link, next, mark_link(extract_nmethod(next), claim_strong_done_tag));
2725   if (old_next == next) {
2726     oops_do_log_change("oops_do, mark weak done -> mark strong done");
2727     return true;
2728   }
2729   return false;
2730 }
2731 
2732 nmethod* nmethod::oops_do_try_add_to_list_as_weak_done() {
2733   assert(SafepointSynchronize::is_at_safepoint(), "only at safepoint");
2734 
2735   assert(extract_state(_oops_do_mark_link) == claim_weak_request_tag ||
2736          extract_state(_oops_do_mark_link) == claim_strong_request_tag,
2737          "must be but is nmethod " PTR_FORMAT " %u", p2i(extract_nmethod(_oops_do_mark_link)), extract_state(_oops_do_mark_link));
2738 
2739   nmethod* old_head = AtomicAccess::xchg(&_oops_do_mark_nmethods, this);
2740   // Self-loop if needed.
2741   if (old_head == nullptr) {
2742     old_head = this;
2743   }
2744   // Try to install end of list and weak done tag.
2745   if (AtomicAccess::cmpxchg(&_oops_do_mark_link, mark_link(this, claim_weak_request_tag), mark_link(old_head, claim_weak_done_tag)) == mark_link(this, claim_weak_request_tag)) {
2746     oops_do_log_change("oops_do, mark weak done");
2747     return nullptr;
2748   } else {
2749     return old_head;
2750   }
2751 }
2752 
2753 void nmethod::oops_do_add_to_list_as_strong_done() {
2754   assert(SafepointSynchronize::is_at_safepoint(), "only at safepoint");
2755 
2756   nmethod* old_head = AtomicAccess::xchg(&_oops_do_mark_nmethods, this);
2757   // Self-loop if needed.
2758   if (old_head == nullptr) {
2759     old_head = this;
2760   }
2761   assert(_oops_do_mark_link == mark_link(this, claim_strong_done_tag), "must be but is nmethod " PTR_FORMAT " state %u",
2762          p2i(extract_nmethod(_oops_do_mark_link)), extract_state(_oops_do_mark_link));
2763 
2764   oops_do_set_strong_done(old_head);
2765 }
2766 
2767 void nmethod::oops_do_process_weak(OopsDoProcessor* p) {
2768   if (!oops_do_try_claim_weak_request()) {
2769     // Failed to claim for weak processing.
2770     oops_do_log_change("oops_do, mark weak request fail");
2771     return;
2772   }
2773 
2774   p->do_regular_processing(this);
2775 
2776   nmethod* old_head = oops_do_try_add_to_list_as_weak_done();
2777   if (old_head == nullptr) {
2778     return;
2779   }
2780   oops_do_log_change("oops_do, mark weak done fail");
2781   // Adding to global list failed, another thread added a strong request.
2782   assert(extract_state(_oops_do_mark_link) == claim_strong_request_tag,
2783          "must be but is %u", extract_state(_oops_do_mark_link));
2784 
2785   oops_do_log_change("oops_do, mark weak request -> mark strong done");
2786 
2787   oops_do_set_strong_done(old_head);
2788   // Do missing strong processing.
2789   p->do_remaining_strong_processing(this);
2790 }
2791 
2792 void nmethod::oops_do_process_strong(OopsDoProcessor* p) {
2793   oops_do_mark_link* next_raw = oops_do_try_claim_strong_done();
2794   if (next_raw == nullptr) {
2795     p->do_regular_processing(this);
2796     oops_do_add_to_list_as_strong_done();
2797     return;
2798   }
2799   // Claim failed. Figure out why and handle it.
2800   if (oops_do_has_weak_request(next_raw)) {
2801     oops_do_mark_link* old = next_raw;
2802     // Claim failed because being weak processed (state == "weak request").
2803     // Try to request deferred strong processing.
2804     next_raw = oops_do_try_add_strong_request(old);
2805     if (next_raw == old) {
2806       // Successfully requested deferred strong processing.
2807       return;
2808     }
2809     // Failed because of a concurrent transition. No longer in "weak request" state.
2810   }
2811   if (oops_do_has_any_strong_state(next_raw)) {
2812     // Already claimed for strong processing or requested for such.
2813     return;
2814   }
2815   if (oops_do_try_claim_weak_done_as_strong_done(next_raw)) {
2816     // Successfully claimed "weak done" as "strong done". Do the missing marking.
2817     p->do_remaining_strong_processing(this);
2818     return;
2819   }
2820   // Claim failed, some other thread got it.
2821 }
2822 
2823 void nmethod::oops_do_marking_prologue() {
2824   assert_at_safepoint();
2825 
2826   log_trace(gc, nmethod)("oops_do_marking_prologue");
2827   assert(_oops_do_mark_nmethods == nullptr, "must be empty");
2828 }
2829 
2830 void nmethod::oops_do_marking_epilogue() {
2831   assert_at_safepoint();
2832 
2833   nmethod* next = _oops_do_mark_nmethods;
2834   _oops_do_mark_nmethods = nullptr;
2835   if (next != nullptr) {
2836     nmethod* cur;
2837     do {
2838       cur = next;
2839       next = extract_nmethod(cur->_oops_do_mark_link);
2840       cur->_oops_do_mark_link = nullptr;
2841       DEBUG_ONLY(cur->verify_oop_relocations());
2842 
2843       LogTarget(Trace, gc, nmethod) lt;
2844       if (lt.is_enabled()) {
2845         LogStream ls(lt);
2846         CompileTask::print(&ls, cur, "oops_do, unmark", /*short_form:*/ true);
2847       }
2848       // End if self-loop has been detected.
2849     } while (cur != next);
2850   }
2851   log_trace(gc, nmethod)("oops_do_marking_epilogue");
2852 }
2853 
2854 inline bool includes(void* p, void* from, void* to) {
2855   return from <= p && p < to;
2856 }
2857 
2858 
2859 void nmethod::copy_scopes_pcs(PcDesc* pcs, int count) {
2860   assert(count >= 2, "must be sentinel values, at least");
2861 
2862 #ifdef ASSERT
2863   // must be sorted and unique; we do a binary search in find_pc_desc()
2864   int prev_offset = pcs[0].pc_offset();
2865   assert(prev_offset == PcDesc::lower_offset_limit,
2866          "must start with a sentinel");
2867   for (int i = 1; i < count; i++) {
2868     int this_offset = pcs[i].pc_offset();
2869     assert(this_offset > prev_offset, "offsets must be sorted");
2870     prev_offset = this_offset;
2871   }
2872   assert(prev_offset == PcDesc::upper_offset_limit,
2873          "must end with a sentinel");
2874 #endif //ASSERT
2875 
2876   // Search for MethodHandle invokes and tag the nmethod.
2877   for (int i = 0; i < count; i++) {
2878     if (pcs[i].is_method_handle_invoke()) {
2879       set_has_method_handle_invokes(true);
2880       break;
2881     }
2882   }
2883   assert(has_method_handle_invokes() == (_deopt_mh_handler_offset != -1), "must have deopt mh handler");
2884 
2885   int size = count * sizeof(PcDesc);
2886   assert(scopes_pcs_size() >= size, "oob");
2887   memcpy(scopes_pcs_begin(), pcs, size);
2888 
2889   // Adjust the final sentinel downward.
2890   PcDesc* last_pc = &scopes_pcs_begin()[count-1];
2891   assert(last_pc->pc_offset() == PcDesc::upper_offset_limit, "sanity");
2892   last_pc->set_pc_offset(content_size() + 1);
2893   for (; last_pc + 1 < scopes_pcs_end(); last_pc += 1) {
2894     // Fill any rounding gaps with copies of the last record.
2895     last_pc[1] = last_pc[0];
2896   }
2897   // The following assert could fail if sizeof(PcDesc) is not
2898   // an integral multiple of oopSize (the rounding term).
2899   // If it fails, change the logic to always allocate a multiple
2900   // of sizeof(PcDesc), and fill unused words with copies of *last_pc.
2901   assert(last_pc + 1 == scopes_pcs_end(), "must match exactly");
2902 }
2903 
2904 void nmethod::copy_scopes_data(u_char* buffer, int size) {
2905   assert(scopes_data_size() >= size, "oob");
2906   memcpy(scopes_data_begin(), buffer, size);
2907 }
2908 
2909 #ifdef ASSERT
2910 static PcDesc* linear_search(int pc_offset, bool approximate, PcDesc* lower, PcDesc* upper) {
2911   PcDesc* res = nullptr;
2912   assert(lower != nullptr && lower->pc_offset() == PcDesc::lower_offset_limit,
2913          "must start with a sentinel");
2914   // lower + 1 to exclude initial sentinel
2915   for (PcDesc* p = lower + 1; p < upper; p++) {
2916     NOT_PRODUCT(--pc_nmethod_stats.pc_desc_tests);  // don't count this call to match_desc
2917     if (match_desc(p, pc_offset, approximate)) {
2918       if (res == nullptr) {
2919         res = p;
2920       } else {
2921         res = (PcDesc*) badAddress;
2922       }
2923     }
2924   }
2925   return res;
2926 }
2927 #endif
2928 
2929 
2930 #ifndef PRODUCT
2931 // Version of method to collect statistic
2932 PcDesc* PcDescContainer::find_pc_desc(address pc, bool approximate, address code_begin,
2933                                       PcDesc* lower, PcDesc* upper) {
2934   ++pc_nmethod_stats.pc_desc_queries;
2935   if (approximate) ++pc_nmethod_stats.pc_desc_approx;
2936 
2937   PcDesc* desc = _pc_desc_cache.last_pc_desc();
2938   assert(desc != nullptr, "PcDesc cache should be initialized already");
2939   if (desc->pc_offset() == (pc - code_begin)) {
2940     // Cached value matched
2941     ++pc_nmethod_stats.pc_desc_tests;
2942     ++pc_nmethod_stats.pc_desc_repeats;
2943     return desc;
2944   }
2945   return find_pc_desc_internal(pc, approximate, code_begin, lower, upper);
2946 }
2947 #endif
2948 
2949 // Finds a PcDesc with real-pc equal to "pc"
2950 PcDesc* PcDescContainer::find_pc_desc_internal(address pc, bool approximate, address code_begin,
2951                                                PcDesc* lower_incl, PcDesc* upper_incl) {
2952   if ((pc < code_begin) ||
2953       (pc - code_begin) >= (ptrdiff_t) PcDesc::upper_offset_limit) {
2954     return nullptr;  // PC is wildly out of range
2955   }
2956   int pc_offset = (int) (pc - code_begin);
2957 
2958   // Check the PcDesc cache if it contains the desired PcDesc
2959   // (This as an almost 100% hit rate.)
2960   PcDesc* res = _pc_desc_cache.find_pc_desc(pc_offset, approximate);
2961   if (res != nullptr) {
2962     assert(res == linear_search(pc_offset, approximate, lower_incl, upper_incl), "cache ok");
2963     return res;
2964   }
2965 
2966   // Fallback algorithm: quasi-linear search for the PcDesc
2967   // Find the last pc_offset less than the given offset.
2968   // The successor must be the required match, if there is a match at all.
2969   // (Use a fixed radix to avoid expensive affine pointer arithmetic.)
2970   PcDesc* lower = lower_incl;     // this is initial sentinel
2971   PcDesc* upper = upper_incl - 1; // exclude final sentinel
2972   if (lower >= upper)  return nullptr;  // no PcDescs at all
2973 
2974 #define assert_LU_OK \
2975   /* invariant on lower..upper during the following search: */ \
2976   assert(lower->pc_offset() <  pc_offset, "sanity"); \
2977   assert(upper->pc_offset() >= pc_offset, "sanity")
2978   assert_LU_OK;
2979 
2980   // Use the last successful return as a split point.
2981   PcDesc* mid = _pc_desc_cache.last_pc_desc();
2982   NOT_PRODUCT(++pc_nmethod_stats.pc_desc_searches);
2983   if (mid->pc_offset() < pc_offset) {
2984     lower = mid;
2985   } else {
2986     upper = mid;
2987   }
2988 
2989   // Take giant steps at first (4096, then 256, then 16, then 1)
2990   const int LOG2_RADIX = 4 /*smaller steps in debug mode:*/ DEBUG_ONLY(-1);
2991   const int RADIX = (1 << LOG2_RADIX);
2992   for (int step = (1 << (LOG2_RADIX*3)); step > 1; step >>= LOG2_RADIX) {
2993     while ((mid = lower + step) < upper) {
2994       assert_LU_OK;
2995       NOT_PRODUCT(++pc_nmethod_stats.pc_desc_searches);
2996       if (mid->pc_offset() < pc_offset) {
2997         lower = mid;
2998       } else {
2999         upper = mid;
3000         break;
3001       }
3002     }
3003     assert_LU_OK;
3004   }
3005 
3006   // Sneak up on the value with a linear search of length ~16.
3007   while (true) {
3008     assert_LU_OK;
3009     mid = lower + 1;
3010     NOT_PRODUCT(++pc_nmethod_stats.pc_desc_searches);
3011     if (mid->pc_offset() < pc_offset) {
3012       lower = mid;
3013     } else {
3014       upper = mid;
3015       break;
3016     }
3017   }
3018 #undef assert_LU_OK
3019 
3020   if (match_desc(upper, pc_offset, approximate)) {
3021     assert(upper == linear_search(pc_offset, approximate, lower_incl, upper_incl), "search mismatch");
3022     if (!Thread::current_in_asgct()) {
3023       // we don't want to modify the cache if we're in ASGCT
3024       // which is typically called in a signal handler
3025       _pc_desc_cache.add_pc_desc(upper);
3026     }
3027     return upper;
3028   } else {
3029     assert(nullptr == linear_search(pc_offset, approximate, lower_incl, upper_incl), "search mismatch");
3030     return nullptr;
3031   }
3032 }
3033 
3034 bool nmethod::check_dependency_on(DepChange& changes) {
3035   // What has happened:
3036   // 1) a new class dependee has been added
3037   // 2) dependee and all its super classes have been marked
3038   bool found_check = false;  // set true if we are upset
3039   for (Dependencies::DepStream deps(this); deps.next(); ) {
3040     // Evaluate only relevant dependencies.
3041     if (deps.spot_check_dependency_at(changes) != nullptr) {
3042       found_check = true;
3043       NOT_DEBUG(break);
3044     }
3045   }
3046   return found_check;
3047 }
3048 
3049 // Called from mark_for_deoptimization, when dependee is invalidated.
3050 bool nmethod::is_dependent_on_method(Method* dependee) {
3051   for (Dependencies::DepStream deps(this); deps.next(); ) {
3052     if (deps.type() != Dependencies::evol_method)
3053       continue;
3054     Method* method = deps.method_argument(0);
3055     if (method == dependee) return true;
3056   }
3057   return false;
3058 }
3059 
3060 void nmethod_init() {
3061   // make sure you didn't forget to adjust the filler fields
3062   assert(sizeof(nmethod) % oopSize == 0, "nmethod size must be multiple of a word");
3063 }
3064 
3065 // -----------------------------------------------------------------------------
3066 // Verification
3067 
3068 class VerifyOopsClosure: public OopClosure {
3069   nmethod* _nm;
3070   bool     _ok;
3071 public:
3072   VerifyOopsClosure(nmethod* nm) : _nm(nm), _ok(true) { }
3073   bool ok() { return _ok; }
3074   virtual void do_oop(oop* p) {
3075     if (oopDesc::is_oop_or_null(*p)) return;
3076     // Print diagnostic information before calling print_nmethod().
3077     // Assertions therein might prevent call from returning.
3078     tty->print_cr("*** non-oop " PTR_FORMAT " found at " PTR_FORMAT " (offset %d)",
3079                   p2i(*p), p2i(p), (int)((intptr_t)p - (intptr_t)_nm));
3080     if (_ok) {
3081       _nm->print_nmethod(true);
3082       _ok = false;
3083     }
3084   }
3085   virtual void do_oop(narrowOop* p) { ShouldNotReachHere(); }
3086 };
3087 
3088 class VerifyMetadataClosure: public MetadataClosure {
3089  public:
3090   void do_metadata(Metadata* md) {
3091     if (md->is_method()) {
3092       Method* method = (Method*)md;
3093       assert(!method->is_old(), "Should not be installing old methods");
3094     }
3095   }
3096 };
3097 
3098 
3099 void nmethod::verify() {
3100   if (is_not_entrant())
3101     return;
3102 
3103   // assert(oopDesc::is_oop(method()), "must be valid");
3104 
3105   ResourceMark rm;
3106 
3107   if (!CodeCache::contains(this)) {
3108     fatal("nmethod at " INTPTR_FORMAT " not in zone", p2i(this));
3109   }
3110 
3111   if(is_native_method() )
3112     return;
3113 
3114   nmethod* nm = CodeCache::find_nmethod(verified_entry_point());
3115   if (nm != this) {
3116     fatal("find_nmethod did not find this nmethod (" INTPTR_FORMAT ")", p2i(this));
3117   }
3118 
3119   // Verification can triggered during shutdown after AOTCodeCache is closed.
3120   // If the Scopes data is in the AOT code cache, then we should avoid verification during shutdown.
3121   if (!is_aot() || AOTCodeCache::is_on()) {
3122     for (PcDesc* p = scopes_pcs_begin(); p < scopes_pcs_end(); p++) {
3123       if (! p->verify(this)) {
3124         tty->print_cr("\t\tin nmethod at " INTPTR_FORMAT " (pcs)", p2i(this));
3125       }
3126     }
3127 
3128 #ifdef ASSERT
3129 #if INCLUDE_JVMCI
3130     {
3131       // Verify that implicit exceptions that deoptimize have a PcDesc and OopMap
3132       ImmutableOopMapSet* oms = oop_maps();
3133       ImplicitExceptionTable implicit_table(this);
3134       for (uint i = 0; i < implicit_table.len(); i++) {
3135         int exec_offset = (int) implicit_table.get_exec_offset(i);
3136         if (implicit_table.get_exec_offset(i) == implicit_table.get_cont_offset(i)) {
3137           assert(pc_desc_at(code_begin() + exec_offset) != nullptr, "missing PcDesc");
3138           bool found = false;
3139           for (int i = 0, imax = oms->count(); i < imax; i++) {
3140             if (oms->pair_at(i)->pc_offset() == exec_offset) {
3141               found = true;
3142               break;
3143             }
3144           }
3145           assert(found, "missing oopmap");
3146         }
3147       }
3148     }
3149 #endif
3150 #endif
3151   }
3152 
3153   VerifyOopsClosure voc(this);
3154   oops_do(&voc);
3155   assert(voc.ok(), "embedded oops must be OK");
3156   Universe::heap()->verify_nmethod(this);
3157 
3158   assert(_oops_do_mark_link == nullptr, "_oops_do_mark_link for %s should be nullptr but is " PTR_FORMAT,
3159          nm->method()->external_name(), p2i(_oops_do_mark_link));
3160   if (!is_aot() || AOTCodeCache::is_on()) {
3161     verify_scopes();
3162   }
3163 
3164   CompiledICLocker nm_verify(this);
3165   VerifyMetadataClosure vmc;
3166   metadata_do(&vmc);
3167 }
3168 
3169 
3170 void nmethod::verify_interrupt_point(address call_site, bool is_inline_cache) {
3171 
3172   // Verify IC only when nmethod installation is finished.
3173   if (!is_not_installed()) {
3174     if (CompiledICLocker::is_safe(this)) {
3175       if (is_inline_cache) {
3176         CompiledIC_at(this, call_site);
3177       } else {
3178         CompiledDirectCall::at(call_site);
3179       }
3180     } else {
3181       CompiledICLocker ml_verify(this);
3182       if (is_inline_cache) {
3183         CompiledIC_at(this, call_site);
3184       } else {
3185         CompiledDirectCall::at(call_site);
3186       }
3187     }
3188   }
3189 
3190   HandleMark hm(Thread::current());
3191 
3192   PcDesc* pd = pc_desc_at(nativeCall_at(call_site)->return_address());
3193   assert(pd != nullptr, "PcDesc must exist");
3194   for (ScopeDesc* sd = new ScopeDesc(this, pd);
3195        !sd->is_top(); sd = sd->sender()) {
3196     sd->verify();
3197   }
3198 }
3199 
3200 void nmethod::verify_scopes() {
3201   if( !method() ) return;       // Runtime stubs have no scope
3202   if (method()->is_native()) return; // Ignore stub methods.
3203   // iterate through all interrupt point
3204   // and verify the debug information is valid.
3205   RelocIterator iter(this);
3206   while (iter.next()) {
3207     address stub = nullptr;
3208     switch (iter.type()) {
3209       case relocInfo::virtual_call_type:
3210         verify_interrupt_point(iter.addr(), true /* is_inline_cache */);
3211         break;
3212       case relocInfo::opt_virtual_call_type:
3213         stub = iter.opt_virtual_call_reloc()->static_stub();
3214         verify_interrupt_point(iter.addr(), false /* is_inline_cache */);
3215         break;
3216       case relocInfo::static_call_type:
3217         stub = iter.static_call_reloc()->static_stub();
3218         verify_interrupt_point(iter.addr(), false /* is_inline_cache */);
3219         break;
3220       case relocInfo::runtime_call_type:
3221       case relocInfo::runtime_call_w_cp_type: {
3222         address destination = iter.reloc()->value();
3223         // Right now there is no way to find out which entries support
3224         // an interrupt point.  It would be nice if we had this
3225         // information in a table.
3226         break;
3227       }
3228       default:
3229         break;
3230     }
3231     assert(stub == nullptr || stub_contains(stub), "static call stub outside stub section");
3232   }
3233 }
3234 
3235 
3236 // -----------------------------------------------------------------------------
3237 // Printing operations
3238 
3239 void nmethod::print_on_impl(outputStream* st) const {
3240   ResourceMark rm;
3241 
3242   st->print("Compiled method ");
3243 
3244   if (is_compiled_by_c1()) {
3245     st->print("(c1) ");
3246   } else if (is_compiled_by_c2()) {
3247     st->print("(c2) ");
3248   } else if (is_compiled_by_jvmci()) {
3249     st->print("(JVMCI) ");
3250   } else {
3251     st->print("(n/a) ");
3252   }
3253 
3254   print_on_with_msg(st, nullptr);
3255 
3256   if (WizardMode) {
3257     st->print("((nmethod*) " INTPTR_FORMAT ") ", p2i(this));
3258     st->print(" for method " INTPTR_FORMAT , p2i(method()));
3259     st->print(" { ");
3260     st->print_cr("%s ", state());
3261     st->print_cr("}:");
3262   }
3263   if (size              () > 0) st->print_cr(" total in heap  [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
3264                                              p2i(this),
3265                                              p2i(this) + size(),
3266                                              size());
3267   if (consts_size       () > 0) st->print_cr(" constants      [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
3268                                              p2i(consts_begin()),
3269                                              p2i(consts_end()),
3270                                              consts_size());
3271   if (insts_size        () > 0) st->print_cr(" main code      [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
3272                                              p2i(insts_begin()),
3273                                              p2i(insts_end()),
3274                                              insts_size());
3275   if (stub_size         () > 0) st->print_cr(" stub code      [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
3276                                              p2i(stub_begin()),
3277                                              p2i(stub_end()),
3278                                              stub_size());
3279   if (oops_size         () > 0) st->print_cr(" oops           [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
3280                                              p2i(oops_begin()),
3281                                              p2i(oops_end()),
3282                                              oops_size());
3283   if (mutable_data_size() > 0) st->print_cr(" mutable data [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
3284                                              p2i(mutable_data_begin()),
3285                                              p2i(mutable_data_end()),
3286                                              mutable_data_size());
3287   if (relocation_size() > 0)   st->print_cr(" relocation     [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
3288                                              p2i(relocation_begin()),
3289                                              p2i(relocation_end()),
3290                                              relocation_size());
3291   if (metadata_size     () > 0) st->print_cr(" metadata       [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
3292                                              p2i(metadata_begin()),
3293                                              p2i(metadata_end()),
3294                                              metadata_size());
3295 #if INCLUDE_JVMCI
3296   if (jvmci_data_size   () > 0) st->print_cr(" JVMCI data     [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
3297                                              p2i(jvmci_data_begin()),
3298                                              p2i(jvmci_data_end()),
3299                                              jvmci_data_size());
3300 #endif
3301   if (immutable_data_size() > 0) st->print_cr(" immutable data [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
3302                                              p2i(immutable_data_begin()),
3303                                              p2i(immutable_data_end()),
3304                                              immutable_data_size());
3305   if (dependencies_size () > 0) st->print_cr(" dependencies   [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
3306                                              p2i(dependencies_begin()),
3307                                              p2i(dependencies_end()),
3308                                              dependencies_size());
3309   if (nul_chk_table_size() > 0) st->print_cr(" nul chk table  [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
3310                                              p2i(nul_chk_table_begin()),
3311                                              p2i(nul_chk_table_end()),
3312                                              nul_chk_table_size());
3313   if (handler_table_size() > 0) st->print_cr(" handler table  [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
3314                                              p2i(handler_table_begin()),
3315                                              p2i(handler_table_end()),
3316                                              handler_table_size());
3317   if (scopes_pcs_size   () > 0) st->print_cr(" scopes pcs     [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
3318                                              p2i(scopes_pcs_begin()),
3319                                              p2i(scopes_pcs_end()),
3320                                              scopes_pcs_size());
3321   if (scopes_data_size  () > 0) st->print_cr(" scopes data    [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
3322                                              p2i(scopes_data_begin()),
3323                                              p2i(scopes_data_end()),
3324                                              scopes_data_size());
3325 #if INCLUDE_JVMCI
3326   if (speculations_size () > 0) st->print_cr(" speculations   [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
3327                                              p2i(speculations_begin()),
3328                                              p2i(speculations_end()),
3329                                              speculations_size());
3330 #endif
3331   if (AOTCodeCache::is_on() && _aot_code_entry != nullptr) {
3332     _aot_code_entry->print(st);
3333   }
3334 }
3335 
3336 void nmethod::print_code() {
3337   ResourceMark m;
3338   ttyLocker ttyl;
3339   // Call the specialized decode method of this class.
3340   decode(tty);
3341 }
3342 
3343 #ifndef PRODUCT  // called InstanceKlass methods are available only then. Declared as PRODUCT_RETURN
3344 
3345 void nmethod::print_dependencies_on(outputStream* out) {
3346   ResourceMark rm;
3347   stringStream st;
3348   st.print_cr("Dependencies:");
3349   for (Dependencies::DepStream deps(this); deps.next(); ) {
3350     deps.print_dependency(&st);
3351     InstanceKlass* ctxk = deps.context_type();
3352     if (ctxk != nullptr) {
3353       if (ctxk->is_dependent_nmethod(this)) {
3354         st.print_cr("   [nmethod<=klass]%s", ctxk->external_name());
3355       }
3356     }
3357     deps.log_dependency();  // put it into the xml log also
3358   }
3359   out->print_raw(st.as_string());
3360 }
3361 #endif
3362 
3363 #if defined(SUPPORT_DATA_STRUCTS)
3364 
3365 // Print the oops from the underlying CodeBlob.
3366 void nmethod::print_oops(outputStream* st) {
3367   ResourceMark m;
3368   st->print("Oops:");
3369   if (oops_begin() < oops_end()) {
3370     st->cr();
3371     for (oop* p = oops_begin(); p < oops_end(); p++) {
3372       Disassembler::print_location((unsigned char*)p, (unsigned char*)oops_begin(), (unsigned char*)oops_end(), st, true, false);
3373       st->print(PTR_FORMAT " ", *((uintptr_t*)p));
3374       if (Universe::contains_non_oop_word(p)) {
3375         st->print_cr("NON_OOP");
3376         continue;  // skip non-oops
3377       }
3378       if (*p == nullptr) {
3379         st->print_cr("nullptr-oop");
3380         continue;  // skip non-oops
3381       }
3382       (*p)->print_value_on(st);
3383       st->cr();
3384     }
3385   } else {
3386     st->print_cr(" <list empty>");
3387   }
3388 }
3389 
3390 // Print metadata pool.
3391 void nmethod::print_metadata(outputStream* st) {
3392   ResourceMark m;
3393   st->print("Metadata:");
3394   if (metadata_begin() < metadata_end()) {
3395     st->cr();
3396     for (Metadata** p = metadata_begin(); p < metadata_end(); p++) {
3397       Disassembler::print_location((unsigned char*)p, (unsigned char*)metadata_begin(), (unsigned char*)metadata_end(), st, true, false);
3398       st->print(PTR_FORMAT " ", *((uintptr_t*)p));
3399       if (*p && *p != Universe::non_oop_word()) {
3400         (*p)->print_value_on(st);
3401       }
3402       st->cr();
3403     }
3404   } else {
3405     st->print_cr(" <list empty>");
3406   }
3407 }
3408 
3409 #ifndef PRODUCT  // ScopeDesc::print_on() is available only then. Declared as PRODUCT_RETURN
3410 void nmethod::print_scopes_on(outputStream* st) {
3411   // Find the first pc desc for all scopes in the code and print it.
3412   ResourceMark rm;
3413   st->print("scopes:");
3414   if (scopes_pcs_begin() < scopes_pcs_end()) {
3415     st->cr();
3416     for (PcDesc* p = scopes_pcs_begin(); p < scopes_pcs_end(); p++) {
3417       if (p->scope_decode_offset() == DebugInformationRecorder::serialized_null)
3418         continue;
3419 
3420       ScopeDesc* sd = scope_desc_at(p->real_pc(this));
3421       while (sd != nullptr) {
3422         sd->print_on(st, p);  // print output ends with a newline
3423         sd = sd->sender();
3424       }
3425     }
3426   } else {
3427     st->print_cr(" <list empty>");
3428   }
3429 }
3430 #endif
3431 
3432 #ifndef PRODUCT  // RelocIterator does support printing only then.
3433 void nmethod::print_relocations_on(outputStream* st) {
3434   ResourceMark m;       // in case methods get printed via the debugger
3435   st->print_cr("relocations:");
3436   RelocIterator iter(this);
3437   iter.print_on(st);
3438 }
3439 #endif
3440 
3441 void nmethod::print_pcs_on(outputStream* st) {
3442   ResourceMark m;       // in case methods get printed via debugger
3443   st->print("pc-bytecode offsets:");
3444   if (scopes_pcs_begin() < scopes_pcs_end()) {
3445     st->cr();
3446     for (PcDesc* p = scopes_pcs_begin(); p < scopes_pcs_end(); p++) {
3447       p->print_on(st, this);  // print output ends with a newline
3448     }
3449   } else {
3450     st->print_cr(" <list empty>");
3451   }
3452 }
3453 
3454 void nmethod::print_handler_table() {
3455   ExceptionHandlerTable(this).print(code_begin());
3456 }
3457 
3458 void nmethod::print_nul_chk_table() {
3459   ImplicitExceptionTable(this).print(code_begin());
3460 }
3461 
3462 void nmethod::print_recorded_oop(int log_n, int i) {
3463   void* value;
3464 
3465   if (i == 0) {
3466     value = nullptr;
3467   } else {
3468     // Be careful around non-oop words. Don't create an oop
3469     // with that value, or it will assert in verification code.
3470     if (Universe::contains_non_oop_word(oop_addr_at(i))) {
3471       value = Universe::non_oop_word();
3472     } else {
3473       value = oop_at(i);
3474     }
3475   }
3476 
3477   tty->print("#%*d: " INTPTR_FORMAT " ", log_n, i, p2i(value));
3478 
3479   if (value == Universe::non_oop_word()) {
3480     tty->print("non-oop word");
3481   } else {
3482     if (value == nullptr) {
3483       tty->print("nullptr-oop");
3484     } else {
3485       oop_at(i)->print_value_on(tty);
3486     }
3487   }
3488 
3489   tty->cr();
3490 }
3491 
3492 void nmethod::print_recorded_oops() {
3493   const int n = oops_count();
3494   const int log_n = (n<10) ? 1 : (n<100) ? 2 : (n<1000) ? 3 : (n<10000) ? 4 : 6;
3495   tty->print("Recorded oops:");
3496   if (n > 0) {
3497     tty->cr();
3498     for (int i = 0; i < n; i++) {
3499       print_recorded_oop(log_n, i);
3500     }
3501   } else {
3502     tty->print_cr(" <list empty>");
3503   }
3504 }
3505 
3506 void nmethod::print_recorded_metadata() {
3507   const int n = metadata_count();
3508   const int log_n = (n<10) ? 1 : (n<100) ? 2 : (n<1000) ? 3 : (n<10000) ? 4 : 6;
3509   tty->print("Recorded metadata:");
3510   if (n > 0) {
3511     tty->cr();
3512     for (int i = 0; i < n; i++) {
3513       Metadata* m = metadata_at(i);
3514       tty->print("#%*d: " INTPTR_FORMAT " ", log_n, i, p2i(m));
3515       if (m == (Metadata*)Universe::non_oop_word()) {
3516         tty->print("non-metadata word");
3517       } else if (m == nullptr) {
3518         tty->print("nullptr-oop");
3519       } else {
3520         Metadata::print_value_on_maybe_null(tty, m);
3521       }
3522       tty->cr();
3523     }
3524   } else {
3525     tty->print_cr(" <list empty>");
3526   }
3527 }
3528 #endif
3529 
3530 #if defined(SUPPORT_ASSEMBLY) || defined(SUPPORT_ABSTRACT_ASSEMBLY)
3531 
3532 void nmethod::print_constant_pool(outputStream* st) {
3533   //-----------------------------------
3534   //---<  Print the constant pool  >---
3535   //-----------------------------------
3536   int consts_size = this->consts_size();
3537   if ( consts_size > 0 ) {
3538     unsigned char* cstart = this->consts_begin();
3539     unsigned char* cp     = cstart;
3540     unsigned char* cend   = cp + consts_size;
3541     unsigned int   bytes_per_line = 4;
3542     unsigned int   CP_alignment   = 8;
3543     unsigned int   n;
3544 
3545     st->cr();
3546 
3547     //---<  print CP header to make clear what's printed  >---
3548     if( ((uintptr_t)cp&(CP_alignment-1)) == 0 ) {
3549       n = bytes_per_line;
3550       st->print_cr("[Constant Pool]");
3551       Disassembler::print_location(cp, cstart, cend, st, true, true);
3552       Disassembler::print_hexdata(cp, n, st, true);
3553       st->cr();
3554     } else {
3555       n = (int)((uintptr_t)cp & (bytes_per_line-1));
3556       st->print_cr("[Constant Pool (unaligned)]");
3557     }
3558 
3559     //---<  print CP contents, bytes_per_line at a time  >---
3560     while (cp < cend) {
3561       Disassembler::print_location(cp, cstart, cend, st, true, false);
3562       Disassembler::print_hexdata(cp, n, st, false);
3563       cp += n;
3564       n   = bytes_per_line;
3565       st->cr();
3566     }
3567 
3568     //---<  Show potential alignment gap between constant pool and code  >---
3569     cend = code_begin();
3570     if( cp < cend ) {
3571       n = 4;
3572       st->print_cr("[Code entry alignment]");
3573       while (cp < cend) {
3574         Disassembler::print_location(cp, cstart, cend, st, false, false);
3575         cp += n;
3576         st->cr();
3577       }
3578     }
3579   } else {
3580     st->print_cr("[Constant Pool (empty)]");
3581   }
3582   st->cr();
3583 }
3584 
3585 #endif
3586 
3587 // Disassemble this nmethod.
3588 // Print additional debug information, if requested. This could be code
3589 // comments, block comments, profiling counters, etc.
3590 // The undisassembled format is useful no disassembler library is available.
3591 // The resulting hex dump (with markers) can be disassembled later, or on
3592 // another system, when/where a disassembler library is available.
3593 void nmethod::decode2(outputStream* ost) const {
3594 
3595   // Called from frame::back_trace_with_decode without ResourceMark.
3596   ResourceMark rm;
3597 
3598   // Make sure we have a valid stream to print on.
3599   outputStream* st = ost ? ost : tty;
3600 
3601 #if defined(SUPPORT_ABSTRACT_ASSEMBLY) && ! defined(SUPPORT_ASSEMBLY)
3602   const bool use_compressed_format    = true;
3603   const bool compressed_with_comments = use_compressed_format && (AbstractDisassembler::show_comment() ||
3604                                                                   AbstractDisassembler::show_block_comment());
3605 #else
3606   const bool use_compressed_format    = Disassembler::is_abstract();
3607   const bool compressed_with_comments = use_compressed_format && (AbstractDisassembler::show_comment() ||
3608                                                                   AbstractDisassembler::show_block_comment());
3609 #endif
3610 
3611   st->cr();
3612   this->print_on(st);
3613   st->cr();
3614 
3615 #if defined(SUPPORT_ASSEMBLY)
3616   //----------------------------------
3617   //---<  Print real disassembly  >---
3618   //----------------------------------
3619   if (! use_compressed_format) {
3620     st->print_cr("[Disassembly]");
3621     Disassembler::decode(const_cast<nmethod*>(this), st);
3622     st->bol();
3623     st->print_cr("[/Disassembly]");
3624     return;
3625   }
3626 #endif
3627 
3628 #if defined(SUPPORT_ABSTRACT_ASSEMBLY)
3629 
3630   // Compressed undisassembled disassembly format.
3631   // The following status values are defined/supported:
3632   //   = 0 - currently at bol() position, nothing printed yet on current line.
3633   //   = 1 - currently at position after print_location().
3634   //   > 1 - in the midst of printing instruction stream bytes.
3635   int        compressed_format_idx    = 0;
3636   int        code_comment_column      = 0;
3637   const int  instr_maxlen             = Assembler::instr_maxlen();
3638   const uint tabspacing               = 8;
3639   unsigned char* start = this->code_begin();
3640   unsigned char* p     = this->code_begin();
3641   unsigned char* end   = this->code_end();
3642   unsigned char* pss   = p; // start of a code section (used for offsets)
3643 
3644   if ((start == nullptr) || (end == nullptr)) {
3645     st->print_cr("PrintAssembly not possible due to uninitialized section pointers");
3646     return;
3647   }
3648 #endif
3649 
3650 #if defined(SUPPORT_ABSTRACT_ASSEMBLY)
3651   //---<  plain abstract disassembly, no comments or anything, just section headers  >---
3652   if (use_compressed_format && ! compressed_with_comments) {
3653     const_cast<nmethod*>(this)->print_constant_pool(st);
3654 
3655     st->bol();
3656     st->cr();
3657     st->print_cr("Loading hsdis library failed, undisassembled code is shown in MachCode section");
3658     //---<  Open the output (Marker for post-mortem disassembler)  >---
3659     st->print_cr("[MachCode]");
3660     const char* header = nullptr;
3661     address p0 = p;
3662     while (p < end) {
3663       address pp = p;
3664       while ((p < end) && (header == nullptr)) {
3665         header = nmethod_section_label(p);
3666         pp  = p;
3667         p  += Assembler::instr_len(p);
3668       }
3669       if (pp > p0) {
3670         AbstractDisassembler::decode_range_abstract(p0, pp, start, end, st, Assembler::instr_maxlen());
3671         p0 = pp;
3672         p  = pp;
3673         header = nullptr;
3674       } else if (header != nullptr) {
3675         st->bol();
3676         st->print_cr("%s", header);
3677         header = nullptr;
3678       }
3679     }
3680     //---<  Close the output (Marker for post-mortem disassembler)  >---
3681     st->bol();
3682     st->print_cr("[/MachCode]");
3683     return;
3684   }
3685 #endif
3686 
3687 #if defined(SUPPORT_ABSTRACT_ASSEMBLY)
3688   //---<  abstract disassembly with comments and section headers merged in  >---
3689   if (compressed_with_comments) {
3690     const_cast<nmethod*>(this)->print_constant_pool(st);
3691 
3692     st->bol();
3693     st->cr();
3694     st->print_cr("Loading hsdis library failed, undisassembled code is shown in MachCode section");
3695     //---<  Open the output (Marker for post-mortem disassembler)  >---
3696     st->print_cr("[MachCode]");
3697     while ((p < end) && (p != nullptr)) {
3698       const int instruction_size_in_bytes = Assembler::instr_len(p);
3699 
3700       //---<  Block comments for nmethod. Interrupts instruction stream, if any.  >---
3701       // Outputs a bol() before and a cr() after, but only if a comment is printed.
3702       // Prints nmethod_section_label as well.
3703       if (AbstractDisassembler::show_block_comment()) {
3704         print_block_comment(st, p);
3705         if (st->position() == 0) {
3706           compressed_format_idx = 0;
3707         }
3708       }
3709 
3710       //---<  New location information after line break  >---
3711       if (compressed_format_idx == 0) {
3712         code_comment_column   = Disassembler::print_location(p, pss, end, st, false, false);
3713         compressed_format_idx = 1;
3714       }
3715 
3716       //---<  Code comment for current instruction. Address range [p..(p+len))  >---
3717       unsigned char* p_end = p + (ssize_t)instruction_size_in_bytes;
3718       S390_ONLY(if (p_end > end) p_end = end;) // avoid getting past the end
3719 
3720       if (AbstractDisassembler::show_comment() && const_cast<nmethod*>(this)->has_code_comment(p, p_end)) {
3721         //---<  interrupt instruction byte stream for code comment  >---
3722         if (compressed_format_idx > 1) {
3723           st->cr();  // interrupt byte stream
3724           st->cr();  // add an empty line
3725           code_comment_column = Disassembler::print_location(p, pss, end, st, false, false);
3726         }
3727         const_cast<nmethod*>(this)->print_code_comment_on(st, code_comment_column, p, p_end );
3728         st->bol();
3729         compressed_format_idx = 0;
3730       }
3731 
3732       //---<  New location information after line break  >---
3733       if (compressed_format_idx == 0) {
3734         code_comment_column   = Disassembler::print_location(p, pss, end, st, false, false);
3735         compressed_format_idx = 1;
3736       }
3737 
3738       //---<  Nicely align instructions for readability  >---
3739       if (compressed_format_idx > 1) {
3740         Disassembler::print_delimiter(st);
3741       }
3742 
3743       //---<  Now, finally, print the actual instruction bytes  >---
3744       unsigned char* p0 = p;
3745       p = Disassembler::decode_instruction_abstract(p, st, instruction_size_in_bytes, instr_maxlen);
3746       compressed_format_idx += (int)(p - p0);
3747 
3748       if (Disassembler::start_newline(compressed_format_idx-1)) {
3749         st->cr();
3750         compressed_format_idx = 0;
3751       }
3752     }
3753     //---<  Close the output (Marker for post-mortem disassembler)  >---
3754     st->bol();
3755     st->print_cr("[/MachCode]");
3756     return;
3757   }
3758 #endif
3759 }
3760 
3761 #if defined(SUPPORT_ASSEMBLY) || defined(SUPPORT_ABSTRACT_ASSEMBLY)
3762 
3763 const char* nmethod::reloc_string_for(u_char* begin, u_char* end) {
3764   RelocIterator iter(this, begin, end);
3765   bool have_one = false;
3766   while (iter.next()) {
3767     have_one = true;
3768     switch (iter.type()) {
3769         case relocInfo::none: {
3770           // Skip it and check next
3771           break;
3772         }
3773         case relocInfo::oop_type: {
3774           // Get a non-resizable resource-allocated stringStream.
3775           // Our callees make use of (nested) ResourceMarks.
3776           stringStream st(NEW_RESOURCE_ARRAY(char, 1024), 1024);
3777           oop_Relocation* r = iter.oop_reloc();
3778           oop obj = r->oop_value();
3779           st.print("oop(");
3780           if (obj == nullptr) st.print("nullptr");
3781           else obj->print_value_on(&st);
3782           st.print(")");
3783           return st.as_string();
3784         }
3785         case relocInfo::metadata_type: {
3786           stringStream st;
3787           metadata_Relocation* r = iter.metadata_reloc();
3788           Metadata* obj = r->metadata_value();
3789           st.print("metadata(");
3790           if (obj == nullptr) st.print("nullptr");
3791           else obj->print_value_on(&st);
3792           st.print(")");
3793           return st.as_string();
3794         }
3795         case relocInfo::runtime_call_type:
3796         case relocInfo::runtime_call_w_cp_type: {
3797           stringStream st;
3798           st.print("runtime_call");
3799           CallRelocation* r = (CallRelocation*)iter.reloc();
3800           address dest = r->destination();
3801           if (StubRoutines::contains(dest)) {
3802             StubCodeDesc* desc = StubCodeDesc::desc_for(dest);
3803             if (desc == nullptr) {
3804               desc = StubCodeDesc::desc_for(dest + frame::pc_return_offset);
3805             }
3806             if (desc != nullptr) {
3807               st.print(" Stub::%s", desc->name());
3808               return st.as_string();
3809             }
3810           }
3811           CodeBlob* cb = CodeCache::find_blob(dest);
3812           if (cb != nullptr) {
3813             st.print(" %s", cb->name());
3814           } else {
3815             ResourceMark rm;
3816             const int buflen = 1024;
3817             char* buf = NEW_RESOURCE_ARRAY(char, buflen);
3818             int offset;
3819             if (os::dll_address_to_function_name(dest, buf, buflen, &offset)) {
3820               st.print(" %s", buf);
3821               if (offset != 0) {
3822                 st.print("+%d", offset);
3823               }
3824             }
3825           }
3826           return st.as_string();
3827         }
3828         case relocInfo::virtual_call_type: {
3829           stringStream st;
3830           st.print_raw("virtual_call");
3831           virtual_call_Relocation* r = iter.virtual_call_reloc();
3832           Method* m = r->method_value();
3833           if (m != nullptr) {
3834             assert(m->is_method(), "");
3835             m->print_short_name(&st);
3836           }
3837           return st.as_string();
3838         }
3839         case relocInfo::opt_virtual_call_type: {
3840           stringStream st;
3841           st.print_raw("optimized virtual_call");
3842           opt_virtual_call_Relocation* r = iter.opt_virtual_call_reloc();
3843           Method* m = r->method_value();
3844           if (m != nullptr) {
3845             assert(m->is_method(), "");
3846             m->print_short_name(&st);
3847           }
3848           return st.as_string();
3849         }
3850         case relocInfo::static_call_type: {
3851           stringStream st;
3852           st.print_raw("static_call");
3853           static_call_Relocation* r = iter.static_call_reloc();
3854           Method* m = r->method_value();
3855           if (m != nullptr) {
3856             assert(m->is_method(), "");
3857             m->print_short_name(&st);
3858           }
3859           return st.as_string();
3860         }
3861         case relocInfo::static_stub_type:      return "static_stub";
3862         case relocInfo::external_word_type:    return "external_word";
3863         case relocInfo::internal_word_type:    return "internal_word";
3864         case relocInfo::section_word_type:     return "section_word";
3865         case relocInfo::poll_type:             return "poll";
3866         case relocInfo::poll_return_type:      return "poll_return";
3867         case relocInfo::trampoline_stub_type:  return "trampoline_stub";
3868         case relocInfo::entry_guard_type:      return "entry_guard";
3869         case relocInfo::post_call_nop_type:    return "post_call_nop";
3870         case relocInfo::barrier_type: {
3871           barrier_Relocation* const reloc = iter.barrier_reloc();
3872           stringStream st;
3873           st.print("barrier format=%d", reloc->format());
3874           return st.as_string();
3875         }
3876 
3877         case relocInfo::type_mask:             return "type_bit_mask";
3878 
3879         default: {
3880           stringStream st;
3881           st.print("unknown relocInfo=%d", (int) iter.type());
3882           return st.as_string();
3883         }
3884     }
3885   }
3886   return have_one ? "other" : nullptr;
3887 }
3888 
3889 // Return the last scope in (begin..end]
3890 ScopeDesc* nmethod::scope_desc_in(address begin, address end) {
3891   PcDesc* p = pc_desc_near(begin+1);
3892   if (p != nullptr && p->real_pc(this) <= end) {
3893     return new ScopeDesc(this, p);
3894   }
3895   return nullptr;
3896 }
3897 
3898 const char* nmethod::nmethod_section_label(address pos) const {
3899   const char* label = nullptr;
3900   if (pos == code_begin())                                              label = "[Instructions begin]";
3901   if (pos == entry_point())                                             label = "[Entry Point]";
3902   if (pos == verified_entry_point())                                    label = "[Verified Entry Point]";
3903   if (has_method_handle_invokes() && (pos == deopt_mh_handler_begin())) label = "[Deopt MH Handler Code]";
3904   if (pos == consts_begin() && pos != insts_begin())                    label = "[Constants]";
3905   // Check stub_code before checking exception_handler or deopt_handler.
3906   if (pos == this->stub_begin())                                        label = "[Stub Code]";
3907   if (JVMCI_ONLY(_exception_offset >= 0 &&) pos == exception_begin())          label = "[Exception Handler]";
3908   if (JVMCI_ONLY(_deopt_handler_offset != -1 &&) pos == deopt_handler_begin()) label = "[Deopt Handler Code]";
3909   return label;
3910 }
3911 
3912 void nmethod::print_nmethod_labels(outputStream* stream, address block_begin, bool print_section_labels) const {
3913   if (print_section_labels) {
3914     const char* label = nmethod_section_label(block_begin);
3915     if (label != nullptr) {
3916       stream->bol();
3917       stream->print_cr("%s", label);
3918     }
3919   }
3920 
3921   if (block_begin == entry_point()) {
3922     Method* m = method();
3923     if (m != nullptr) {
3924       stream->print("  # ");
3925       m->print_value_on(stream);
3926       stream->cr();
3927     }
3928     if (m != nullptr && !is_osr_method()) {
3929       ResourceMark rm;
3930       int sizeargs = m->size_of_parameters();
3931       BasicType* sig_bt = NEW_RESOURCE_ARRAY(BasicType, sizeargs);
3932       VMRegPair* regs   = NEW_RESOURCE_ARRAY(VMRegPair, sizeargs);
3933       {
3934         int sig_index = 0;
3935         if (!m->is_static())
3936           sig_bt[sig_index++] = T_OBJECT; // 'this'
3937         for (SignatureStream ss(m->signature()); !ss.at_return_type(); ss.next()) {
3938           BasicType t = ss.type();
3939           sig_bt[sig_index++] = t;
3940           if (type2size[t] == 2) {
3941             sig_bt[sig_index++] = T_VOID;
3942           } else {
3943             assert(type2size[t] == 1, "size is 1 or 2");
3944           }
3945         }
3946         assert(sig_index == sizeargs, "");
3947       }
3948       const char* spname = "sp"; // make arch-specific?
3949       SharedRuntime::java_calling_convention(sig_bt, regs, sizeargs);
3950       int stack_slot_offset = this->frame_size() * wordSize;
3951       int tab1 = 14, tab2 = 24;
3952       int sig_index = 0;
3953       int arg_index = (m->is_static() ? 0 : -1);
3954       bool did_old_sp = false;
3955       for (SignatureStream ss(m->signature()); !ss.at_return_type(); ) {
3956         bool at_this = (arg_index == -1);
3957         bool at_old_sp = false;
3958         BasicType t = (at_this ? T_OBJECT : ss.type());
3959         assert(t == sig_bt[sig_index], "sigs in sync");
3960         if (at_this)
3961           stream->print("  # this: ");
3962         else
3963           stream->print("  # parm%d: ", arg_index);
3964         stream->move_to(tab1);
3965         VMReg fst = regs[sig_index].first();
3966         VMReg snd = regs[sig_index].second();
3967         if (fst->is_reg()) {
3968           stream->print("%s", fst->name());
3969           if (snd->is_valid())  {
3970             stream->print(":%s", snd->name());
3971           }
3972         } else if (fst->is_stack()) {
3973           int offset = fst->reg2stack() * VMRegImpl::stack_slot_size + stack_slot_offset;
3974           if (offset == stack_slot_offset)  at_old_sp = true;
3975           stream->print("[%s+0x%x]", spname, offset);
3976         } else {
3977           stream->print("reg%d:%d??", (int)(intptr_t)fst, (int)(intptr_t)snd);
3978         }
3979         stream->print(" ");
3980         stream->move_to(tab2);
3981         stream->print("= ");
3982         if (at_this) {
3983           m->method_holder()->print_value_on(stream);
3984         } else {
3985           bool did_name = false;
3986           if (!at_this && ss.is_reference()) {
3987             Symbol* name = ss.as_symbol();
3988             name->print_value_on(stream);
3989             did_name = true;
3990           }
3991           if (!did_name)
3992             stream->print("%s", type2name(t));
3993         }
3994         if (at_old_sp) {
3995           stream->print("  (%s of caller)", spname);
3996           did_old_sp = true;
3997         }
3998         stream->cr();
3999         sig_index += type2size[t];
4000         arg_index += 1;
4001         if (!at_this)  ss.next();
4002       }
4003       if (!did_old_sp) {
4004         stream->print("  # ");
4005         stream->move_to(tab1);
4006         stream->print("[%s+0x%x]", spname, stack_slot_offset);
4007         stream->print("  (%s of caller)", spname);
4008         stream->cr();
4009       }
4010     }
4011   }
4012 }
4013 
4014 // Returns whether this nmethod has code comments.
4015 bool nmethod::has_code_comment(address begin, address end) {
4016   // scopes?
4017   ScopeDesc* sd  = scope_desc_in(begin, end);
4018   if (sd != nullptr) return true;
4019 
4020   // relocations?
4021   const char* str = reloc_string_for(begin, end);
4022   if (str != nullptr) return true;
4023 
4024   // implicit exceptions?
4025   int cont_offset = ImplicitExceptionTable(this).continuation_offset((uint)(begin - code_begin()));
4026   if (cont_offset != 0) return true;
4027 
4028   return false;
4029 }
4030 
4031 void nmethod::print_code_comment_on(outputStream* st, int column, address begin, address end) {
4032   ImplicitExceptionTable implicit_table(this);
4033   int pc_offset = (int)(begin - code_begin());
4034   int cont_offset = implicit_table.continuation_offset(pc_offset);
4035   bool oop_map_required = false;
4036   if (cont_offset != 0) {
4037     st->move_to(column, 6, 0);
4038     if (pc_offset == cont_offset) {
4039       st->print("; implicit exception: deoptimizes");
4040       oop_map_required = true;
4041     } else {
4042       st->print("; implicit exception: dispatches to " INTPTR_FORMAT, p2i(code_begin() + cont_offset));
4043     }
4044   }
4045 
4046   // Find an oopmap in (begin, end].  We use the odd half-closed
4047   // interval so that oop maps and scope descs which are tied to the
4048   // byte after a call are printed with the call itself.  OopMaps
4049   // associated with implicit exceptions are printed with the implicit
4050   // instruction.
4051   address base = code_begin();
4052   ImmutableOopMapSet* oms = oop_maps();
4053   if (oms != nullptr) {
4054     for (int i = 0, imax = oms->count(); i < imax; i++) {
4055       const ImmutableOopMapPair* pair = oms->pair_at(i);
4056       const ImmutableOopMap* om = pair->get_from(oms);
4057       address pc = base + pair->pc_offset();
4058       if (pc >= begin) {
4059 #if INCLUDE_JVMCI
4060         bool is_implicit_deopt = implicit_table.continuation_offset(pair->pc_offset()) == (uint) pair->pc_offset();
4061 #else
4062         bool is_implicit_deopt = false;
4063 #endif
4064         if (is_implicit_deopt ? pc == begin : pc > begin && pc <= end) {
4065           st->move_to(column, 6, 0);
4066           st->print("; ");
4067           om->print_on(st);
4068           oop_map_required = false;
4069         }
4070       }
4071       if (pc > end) {
4072         break;
4073       }
4074     }
4075   }
4076   assert(!oop_map_required, "missed oopmap");
4077 
4078   Thread* thread = Thread::current();
4079 
4080   // Print any debug info present at this pc.
4081   ScopeDesc* sd  = scope_desc_in(begin, end);
4082   if (sd != nullptr) {
4083     st->move_to(column, 6, 0);
4084     if (sd->bci() == SynchronizationEntryBCI) {
4085       st->print(";*synchronization entry");
4086     } else if (sd->bci() == AfterBci) {
4087       st->print(";* method exit (unlocked if synchronized)");
4088     } else if (sd->bci() == UnwindBci) {
4089       st->print(";* unwind (locked if synchronized)");
4090     } else if (sd->bci() == AfterExceptionBci) {
4091       st->print(";* unwind (unlocked if synchronized)");
4092     } else if (sd->bci() == UnknownBci) {
4093       st->print(";* unknown");
4094     } else if (sd->bci() == InvalidFrameStateBci) {
4095       st->print(";* invalid frame state");
4096     } else {
4097       if (sd->method() == nullptr) {
4098         st->print("method is nullptr");
4099       } else if (sd->method()->is_native()) {
4100         st->print("method is native");
4101       } else {
4102         Bytecodes::Code bc = sd->method()->java_code_at(sd->bci());
4103         st->print(";*%s", Bytecodes::name(bc));
4104         switch (bc) {
4105         case Bytecodes::_invokevirtual:
4106         case Bytecodes::_invokespecial:
4107         case Bytecodes::_invokestatic:
4108         case Bytecodes::_invokeinterface:
4109           {
4110             Bytecode_invoke invoke(methodHandle(thread, sd->method()), sd->bci());
4111             st->print(" ");
4112             if (invoke.name() != nullptr)
4113               invoke.name()->print_symbol_on(st);
4114             else
4115               st->print("<UNKNOWN>");
4116             break;
4117           }
4118         case Bytecodes::_getfield:
4119         case Bytecodes::_putfield:
4120         case Bytecodes::_getstatic:
4121         case Bytecodes::_putstatic:
4122           {
4123             Bytecode_field field(methodHandle(thread, sd->method()), sd->bci());
4124             st->print(" ");
4125             if (field.name() != nullptr)
4126               field.name()->print_symbol_on(st);
4127             else
4128               st->print("<UNKNOWN>");
4129           }
4130         default:
4131           break;
4132         }
4133       }
4134       st->print(" {reexecute=%d rethrow=%d return_oop=%d}", sd->should_reexecute(), sd->rethrow_exception(), sd->return_oop());
4135     }
4136 
4137     // Print all scopes
4138     for (;sd != nullptr; sd = sd->sender()) {
4139       st->move_to(column, 6, 0);
4140       st->print("; -");
4141       if (sd->should_reexecute()) {
4142         st->print(" (reexecute)");
4143       }
4144       if (sd->method() == nullptr) {
4145         st->print("method is nullptr");
4146       } else {
4147         sd->method()->print_short_name(st);
4148       }
4149       int lineno = sd->method()->line_number_from_bci(sd->bci());
4150       if (lineno != -1) {
4151         st->print("@%d (line %d)", sd->bci(), lineno);
4152       } else {
4153         st->print("@%d", sd->bci());
4154       }
4155       st->cr();
4156     }
4157   }
4158 
4159   // Print relocation information
4160   // Prevent memory leak: allocating without ResourceMark.
4161   ResourceMark rm;
4162   const char* str = reloc_string_for(begin, end);
4163   if (str != nullptr) {
4164     if (sd != nullptr) st->cr();
4165     st->move_to(column, 6, 0);
4166     st->print(";   {%s}", str);
4167   }
4168 }
4169 
4170 #endif
4171 
4172 address nmethod::call_instruction_address(address pc) const {
4173   if (NativeCall::is_call_before(pc)) {
4174     NativeCall *ncall = nativeCall_before(pc);
4175     return ncall->instruction_address();
4176   }
4177   return nullptr;
4178 }
4179 
4180 void nmethod::print_value_on_impl(outputStream* st) const {
4181   st->print_cr("nmethod");
4182 #if defined(SUPPORT_DATA_STRUCTS)
4183   print_on_with_msg(st, nullptr);
4184 #endif
4185 }
4186 
4187 #ifndef PRODUCT
4188 
4189 void nmethod::print_calls(outputStream* st) {
4190   RelocIterator iter(this);
4191   while (iter.next()) {
4192     switch (iter.type()) {
4193     case relocInfo::virtual_call_type: {
4194       CompiledICLocker ml_verify(this);
4195       CompiledIC_at(&iter)->print();
4196       break;
4197     }
4198     case relocInfo::static_call_type:
4199     case relocInfo::opt_virtual_call_type:
4200       st->print_cr("Direct call at " INTPTR_FORMAT, p2i(iter.reloc()->addr()));
4201       CompiledDirectCall::at(iter.reloc())->print();
4202       break;
4203     default:
4204       break;
4205     }
4206   }
4207 }
4208 
4209 void nmethod::print_statistics() {
4210   ttyLocker ttyl;
4211   if (xtty != nullptr)  xtty->head("statistics type='nmethod'");
4212   native_nmethod_stats.print_native_nmethod_stats();
4213 #ifdef COMPILER1
4214   c1_java_nmethod_stats.print_nmethod_stats("C1");
4215 #endif
4216 #ifdef COMPILER2
4217   c2_java_nmethod_stats.print_nmethod_stats("C2");
4218 #endif
4219 #if INCLUDE_JVMCI
4220   jvmci_java_nmethod_stats.print_nmethod_stats("JVMCI");
4221 #endif
4222   unknown_java_nmethod_stats.print_nmethod_stats("Unknown");
4223   DebugInformationRecorder::print_statistics();
4224   pc_nmethod_stats.print_pc_stats();
4225   Dependencies::print_statistics();
4226   ExternalsRecorder::print_statistics();
4227   if (xtty != nullptr)  xtty->tail("statistics");
4228 }
4229 
4230 #endif // !PRODUCT
4231 
4232 #if INCLUDE_JVMCI
4233 void nmethod::update_speculation(JavaThread* thread) {
4234   jlong speculation = thread->pending_failed_speculation();
4235   if (speculation != 0) {
4236     guarantee(jvmci_nmethod_data() != nullptr, "failed speculation in nmethod without failed speculation list");
4237     jvmci_nmethod_data()->add_failed_speculation(this, speculation);
4238     thread->set_pending_failed_speculation(0);
4239   }
4240 }
4241 
4242 const char* nmethod::jvmci_name() {
4243   if (jvmci_nmethod_data() != nullptr) {
4244     return jvmci_nmethod_data()->name();
4245   }
4246   return nullptr;
4247 }
4248 
4249 bool nmethod::jvmci_skip_profile_deopt() const {
4250   return jvmci_nmethod_data() != nullptr && !jvmci_nmethod_data()->profile_deopt();
4251 }
4252 #endif
4253 
4254 void nmethod::prepare_for_archiving_impl() {
4255   CodeBlob::prepare_for_archiving_impl();
4256   _deoptimization_generation = 0;
4257   _gc_epoch = 0;
4258   _method_profiling_count = 0;
4259   _osr_link = nullptr;
4260   _method = nullptr;
4261   _immutable_data = nullptr;
4262   _pc_desc_container = nullptr;
4263   _exception_cache = nullptr;
4264   _gc_data = nullptr;
4265   _oops_do_mark_link = nullptr;
4266   _compiled_ic_data = nullptr;
4267   _osr_entry_point = nullptr;
4268   _compile_id = -1;
4269   _deoptimization_status = not_marked;
4270   _is_unloading_state = 0;
4271   _state = not_installed;
4272 }