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