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