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