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