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