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