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