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