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