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