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