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