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