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