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