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