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