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     log_identity(xtty);
 927     xtty->stamp();
 928     xtty->end_head();
 929   }
 930   // Print the header part, then print the requested information.
 931   // This is both handled in decode2().
 932   if (printmethod) {
 933     HandleMark hm;
 934     ResourceMark m;
 935     if (is_compiled_by_c1()) {
 936       tty->cr();
 937       tty->print_cr("============================= C1-compiled nmethod ==============================");
 938     }
 939     if (is_compiled_by_jvmci()) {
 940       tty->cr();
 941       tty->print_cr("=========================== JVMCI-compiled nmethod =============================");
 942     }
 943     tty->print_cr("----------------------------------- Assembly -----------------------------------");
 944     decode2(tty);
 945 #if defined(SUPPORT_DATA_STRUCTS)
 946     if (AbstractDisassembler::show_structs()) {
 947       // Print the oops from the underlying CodeBlob as well.
 948       tty->print_cr("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ");
 949       print_oops(tty);
 950       tty->print_cr("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ");
 951       print_metadata(tty);
 952       tty->print_cr("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ");
 953       print_pcs();
 954       tty->print_cr("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ");
 955       if (oop_maps() != NULL) {
 956         tty->print("oop maps:"); // oop_maps()->print_on(tty) outputs a cr() at the beginning
 957         oop_maps()->print_on(tty);
 958         tty->print_cr("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ");
 959       }
 960     }
 961 #endif
 962   } else {
 963     print(); // print the header part only.
 964   }
 965 
 966 #if defined(SUPPORT_DATA_STRUCTS)
 967   if (AbstractDisassembler::show_structs()) {
 968     if (printmethod || PrintDebugInfo || CompilerOracle::has_option_string(_method, "PrintDebugInfo")) {
 969       print_scopes();
 970       tty->print_cr("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ");
 971     }
 972     if (printmethod || PrintRelocations || CompilerOracle::has_option_string(_method, "PrintRelocations")) {
 973       print_relocations();
 974       tty->print_cr("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ");
 975     }
 976     if (printmethod || PrintDependencies || CompilerOracle::has_option_string(_method, "PrintDependencies")) {
 977       print_dependencies();
 978       tty->print_cr("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ");
 979     }
 980     if (printmethod || PrintExceptionHandlers) {
 981       print_handler_table();
 982       tty->print_cr("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ");
 983       print_nul_chk_table();
 984       tty->print_cr("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ");
 985     }
 986 
 987     if (printmethod) {
 988       print_recorded_oops();
 989       tty->print_cr("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ");
 990       print_recorded_metadata();
 991       tty->print_cr("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ");
 992     }
 993   }
 994 #endif
 995 
 996   if (xtty != NULL) {
 997     xtty->tail("print_nmethod");
 998   }
 999 }
1000 
1001 
1002 // Promote one word from an assembly-time handle to a live embedded oop.
1003 inline void nmethod::initialize_immediate_oop(oop* dest, jobject handle) {
1004   if (handle == NULL ||
1005       // As a special case, IC oops are initialized to 1 or -1.
1006       handle == (jobject) Universe::non_oop_word()) {
1007     (*dest) = (oop) handle;
1008   } else {
1009     (*dest) = JNIHandles::resolve_non_null(handle);
1010   }
1011 }
1012 
1013 
1014 // Have to have the same name because it's called by a template
1015 void nmethod::copy_values(GrowableArray<jobject>* array) {
1016   int length = array->length();
1017   assert((address)(oops_begin() + length) <= (address)oops_end(), "oops big enough");
1018   oop* dest = oops_begin();
1019   for (int index = 0 ; index < length; index++) {
1020     initialize_immediate_oop(&dest[index], array->at(index));
1021   }
1022 
1023   // Now we can fix up all the oops in the code.  We need to do this
1024   // in the code because the assembler uses jobjects as placeholders.
1025   // The code and relocations have already been initialized by the
1026   // CodeBlob constructor, so it is valid even at this early point to
1027   // iterate over relocations and patch the code.
1028   fix_oop_relocations(NULL, NULL, /*initialize_immediates=*/ true);
1029 }
1030 
1031 void nmethod::copy_values(GrowableArray<Metadata*>* array) {
1032   int length = array->length();
1033   assert((address)(metadata_begin() + length) <= (address)metadata_end(), "big enough");
1034   Metadata** dest = metadata_begin();
1035   for (int index = 0 ; index < length; index++) {
1036     dest[index] = array->at(index);
1037   }
1038 }
1039 
1040 void nmethod::fix_oop_relocations(address begin, address end, bool initialize_immediates) {
1041   // re-patch all oop-bearing instructions, just in case some oops moved
1042   RelocIterator iter(this, begin, end);
1043   while (iter.next()) {
1044     if (iter.type() == relocInfo::oop_type) {
1045       oop_Relocation* reloc = iter.oop_reloc();
1046       if (initialize_immediates && reloc->oop_is_immediate()) {
1047         oop* dest = reloc->oop_addr();
1048         initialize_immediate_oop(dest, (jobject) *dest);
1049       }
1050       // Refresh the oop-related bits of this instruction.
1051       reloc->fix_oop_relocation();
1052     } else if (iter.type() == relocInfo::metadata_type) {
1053       metadata_Relocation* reloc = iter.metadata_reloc();
1054       reloc->fix_metadata_relocation();
1055     }
1056   }
1057 }
1058 
1059 
1060 void nmethod::verify_clean_inline_caches() {
1061   assert(CompiledICLocker::is_safe(this), "mt unsafe call");
1062 
1063   ResourceMark rm;
1064   RelocIterator iter(this, oops_reloc_begin());
1065   while(iter.next()) {
1066     switch(iter.type()) {
1067       case relocInfo::virtual_call_type:
1068       case relocInfo::opt_virtual_call_type: {
1069         CompiledIC *ic = CompiledIC_at(&iter);
1070         // Ok, to lookup references to zombies here
1071         CodeBlob *cb = CodeCache::find_blob_unsafe(ic->ic_destination());
1072         assert(cb != NULL, "destination not in CodeBlob?");
1073         nmethod* nm = cb->as_nmethod_or_null();
1074         if( nm != NULL ) {
1075           // Verify that inline caches pointing to both zombie and not_entrant methods are clean
1076           if (!nm->is_in_use() || (nm->method()->code() != nm)) {
1077             assert(ic->is_clean(), "IC should be clean");
1078           }
1079         }
1080         break;
1081       }
1082       case relocInfo::static_call_type: {
1083         CompiledStaticCall *csc = compiledStaticCall_at(iter.reloc());
1084         CodeBlob *cb = CodeCache::find_blob_unsafe(csc->destination());
1085         assert(cb != NULL, "destination not in CodeBlob?");
1086         nmethod* nm = cb->as_nmethod_or_null();
1087         if( nm != NULL ) {
1088           // Verify that inline caches pointing to both zombie and not_entrant methods are clean
1089           if (!nm->is_in_use() || (nm->method()->code() != nm)) {
1090             assert(csc->is_clean(), "IC should be clean");
1091           }
1092         }
1093         break;
1094       }
1095       default:
1096         break;
1097     }
1098   }
1099 }
1100 
1101 // This is a private interface with the sweeper.
1102 void nmethod::mark_as_seen_on_stack() {
1103   assert(is_alive(), "Must be an alive method");
1104   // Set the traversal mark to ensure that the sweeper does 2
1105   // cleaning passes before moving to zombie.
1106   set_stack_traversal_mark(NMethodSweeper::traversal_count());
1107 }
1108 
1109 // Tell if a non-entrant method can be converted to a zombie (i.e.,
1110 // there are no activations on the stack, not in use by the VM,
1111 // and not in use by the ServiceThread)
1112 bool nmethod::can_convert_to_zombie() {
1113   // Note that this is called when the sweeper has observed the nmethod to be
1114   // not_entrant. However, with concurrent code cache unloading, the state
1115   // might have moved on to unloaded if it is_unloading(), due to racing
1116   // concurrent GC threads.
1117   assert(is_not_entrant() || is_unloading(), "must be a non-entrant method");
1118 
1119   // Since the nmethod sweeper only does partial sweep the sweeper's traversal
1120   // count can be greater than the stack traversal count before it hits the
1121   // nmethod for the second time.
1122   // If an is_unloading() nmethod is still not_entrant, then it is not safe to
1123   // convert it to zombie due to GC unloading interactions. However, if it
1124   // has become unloaded, then it is okay to convert such nmethods to zombie.
1125   return stack_traversal_mark() + 1 < NMethodSweeper::traversal_count() &&
1126          !is_locked_by_vm() && (!is_unloading() || is_unloaded());
1127 }
1128 
1129 void nmethod::inc_decompile_count() {
1130   if (!is_compiled_by_c2() && !is_compiled_by_jvmci()) return;
1131   // Could be gated by ProfileTraps, but do not bother...
1132   Method* m = method();
1133   if (m == NULL)  return;
1134   MethodData* mdo = m->method_data();
1135   if (mdo == NULL)  return;
1136   // There is a benign race here.  See comments in methodData.hpp.
1137   mdo->inc_decompile_count();
1138 }
1139 
1140 void nmethod::make_unloaded() {
1141   post_compiled_method_unload();
1142 
1143   // This nmethod is being unloaded, make sure that dependencies
1144   // recorded in instanceKlasses get flushed.
1145   // Since this work is being done during a GC, defer deleting dependencies from the
1146   // InstanceKlass.
1147   assert(Universe::heap()->is_gc_active() || Thread::current()->is_ConcurrentGC_thread(),
1148          "should only be called during gc");
1149   flush_dependencies(/*delete_immediately*/false);
1150 
1151   // Break cycle between nmethod & method
1152   LogTarget(Trace, class, unload, nmethod) lt;
1153   if (lt.is_enabled()) {
1154     LogStream ls(lt);
1155     ls.print("making nmethod " INTPTR_FORMAT
1156              " unloadable, Method*(" INTPTR_FORMAT
1157              ") ",
1158              p2i(this), p2i(_method));
1159      ls.cr();
1160   }
1161   // Unlink the osr method, so we do not look this up again
1162   if (is_osr_method()) {
1163     // Invalidate the osr nmethod only once
1164     if (is_in_use()) {
1165       invalidate_osr_method();
1166     }
1167 #ifdef ASSERT
1168     if (method() != NULL) {
1169       // Make sure osr nmethod is invalidated, i.e. not on the list
1170       bool found = method()->method_holder()->remove_osr_nmethod(this);
1171       assert(!found, "osr nmethod should have been invalidated");
1172     }
1173 #endif
1174   }
1175 
1176   // If _method is already NULL the Method* is about to be unloaded,
1177   // so we don't have to break the cycle. Note that it is possible to
1178   // have the Method* live here, in case we unload the nmethod because
1179   // it is pointing to some oop (other than the Method*) being unloaded.
1180   if (_method != NULL) {
1181     _method->unlink_code(this);
1182   }
1183 
1184   // Make the class unloaded - i.e., change state and notify sweeper
1185   assert(SafepointSynchronize::is_at_safepoint() || Thread::current()->is_ConcurrentGC_thread(),
1186          "must be at safepoint");
1187 
1188   {
1189     // Clear ICStubs and release any CompiledICHolders.
1190     CompiledICLocker ml(this);
1191     clear_ic_callsites();
1192   }
1193 
1194   // Unregister must be done before the state change
1195   {
1196     MutexLocker ml(SafepointSynchronize::is_at_safepoint() ? NULL : CodeCache_lock,
1197                      Mutex::_no_safepoint_check_flag);
1198     Universe::heap()->unregister_nmethod(this);
1199   }
1200 
1201   // Clear the method of this dead nmethod
1202   set_method(NULL);
1203 
1204   // Log the unloading.
1205   log_state_change();
1206 
1207   // The Method* is gone at this point
1208   assert(_method == NULL, "Tautology");
1209 
1210   set_osr_link(NULL);
1211   NMethodSweeper::report_state_change(this);
1212 
1213   // The release is only needed for compile-time ordering, as accesses
1214   // into the nmethod after the store are not safe due to the sweeper
1215   // being allowed to free it when the store is observed, during
1216   // concurrent nmethod unloading. Therefore, there is no need for
1217   // acquire on the loader side.
1218   OrderAccess::release_store(&_state, (signed char)unloaded);
1219 
1220 #if INCLUDE_JVMCI
1221   // Clear the link between this nmethod and a HotSpotNmethod mirror
1222   JVMCINMethodData* nmethod_data = jvmci_nmethod_data();
1223   if (nmethod_data != NULL) {
1224     nmethod_data->invalidate_nmethod_mirror(this);
1225     nmethod_data->clear_nmethod_mirror(this);
1226   }
1227 #endif
1228 }
1229 
1230 void nmethod::invalidate_osr_method() {
1231   assert(_entry_bci != InvocationEntryBci, "wrong kind of nmethod");
1232   // Remove from list of active nmethods
1233   if (method() != NULL) {
1234     method()->method_holder()->remove_osr_nmethod(this);
1235   }
1236 }
1237 
1238 void nmethod::log_state_change() const {
1239   if (LogCompilation) {
1240     if (xtty != NULL) {
1241       ttyLocker ttyl;  // keep the following output all in one block
1242       if (_state == unloaded) {
1243         xtty->begin_elem("make_unloaded thread='" UINTX_FORMAT "'",
1244                          os::current_thread_id());
1245       } else {
1246         xtty->begin_elem("make_not_entrant thread='" UINTX_FORMAT "'%s",
1247                          os::current_thread_id(),
1248                          (_state == zombie ? " zombie='1'" : ""));
1249       }
1250       log_identity(xtty);
1251       xtty->stamp();
1252       xtty->end_elem();
1253     }
1254   }
1255 
1256   const char *state_msg = _state == zombie ? "made zombie" : "made not entrant";
1257   CompileTask::print_ul(this, state_msg);
1258   if (PrintCompilation && _state != unloaded) {
1259     print_on(tty, state_msg);
1260   }
1261 }
1262 
1263 void nmethod::unlink_from_method() {
1264   if (method() != NULL) {
1265     method()->unlink_code(this);
1266   }
1267 }
1268 
1269 /**
1270  * Common functionality for both make_not_entrant and make_zombie
1271  */
1272 bool nmethod::make_not_entrant_or_zombie(int state) {
1273   assert(state == zombie || state == not_entrant, "must be zombie or not_entrant");
1274   assert(!is_zombie(), "should not already be a zombie");
1275 
1276   if (_state == state) {
1277     // Avoid taking the lock if already in required state.
1278     // This is safe from races because the state is an end-state,
1279     // which the nmethod cannot back out of once entered.
1280     // No need for fencing either.
1281     return false;
1282   }
1283 
1284   // Make sure neither the nmethod nor the method is flushed in case of a safepoint in code below.
1285   nmethodLocker nml(this);
1286   methodHandle the_method(method());
1287   // This can be called while the system is already at a safepoint which is ok
1288   NoSafepointVerifier nsv(true, !SafepointSynchronize::is_at_safepoint());
1289 
1290   // during patching, depending on the nmethod state we must notify the GC that
1291   // code has been unloaded, unregistering it. We cannot do this right while
1292   // holding the CompiledMethod_lock because we need to use the CodeCache_lock. This
1293   // would be prone to deadlocks.
1294   // This flag is used to remember whether we need to later lock and unregister.
1295   bool nmethod_needs_unregister = false;
1296 
1297   // invalidate osr nmethod before acquiring the patching lock since
1298   // they both acquire leaf locks and we don't want a deadlock.
1299   // This logic is equivalent to the logic below for patching the
1300   // verified entry point of regular methods. We check that the
1301   // nmethod is in use to ensure that it is invalidated only once.
1302   if (is_osr_method() && is_in_use()) {
1303     // this effectively makes the osr nmethod not entrant
1304     invalidate_osr_method();
1305   }
1306 
1307   {
1308     // Enter critical section.  Does not block for safepoint.
1309     MutexLocker pl(CompiledMethod_lock, Mutex::_no_safepoint_check_flag);
1310 
1311     if (_state == state) {
1312       // another thread already performed this transition so nothing
1313       // to do, but return false to indicate this.
1314       return false;
1315     }
1316 
1317     // The caller can be calling the method statically or through an inline
1318     // cache call.
1319     if (!is_osr_method() && !is_not_entrant()) {
1320       NativeJump::patch_verified_entry(entry_point(), verified_entry_point(),
1321                   SharedRuntime::get_handle_wrong_method_stub());
1322     }
1323 
1324     if (is_in_use() && update_recompile_counts()) {
1325       // It's a true state change, so mark the method as decompiled.
1326       // Do it only for transition from alive.
1327       inc_decompile_count();
1328     }
1329 
1330     // If the state is becoming a zombie, signal to unregister the nmethod with
1331     // the heap.
1332     // This nmethod may have already been unloaded during a full GC.
1333     if ((state == zombie) && !is_unloaded()) {
1334       nmethod_needs_unregister = true;
1335     }
1336 
1337     // Must happen before state change. Otherwise we have a race condition in
1338     // nmethod::can_not_entrant_be_converted(). I.e., a method can immediately
1339     // transition its state from 'not_entrant' to 'zombie' without having to wait
1340     // for stack scanning.
1341     if (state == not_entrant) {
1342       mark_as_seen_on_stack();
1343       OrderAccess::storestore(); // _stack_traversal_mark and _state
1344     }
1345 
1346     // Change state
1347     _state = state;
1348 
1349     // Log the transition once
1350     log_state_change();
1351 
1352     // Remove nmethod from method.
1353     unlink_from_method();
1354 
1355   } // leave critical region under CompiledMethod_lock
1356 
1357 #if INCLUDE_JVMCI
1358   // Invalidate can't occur while holding the Patching lock
1359   JVMCINMethodData* nmethod_data = jvmci_nmethod_data();
1360   if (nmethod_data != NULL) {
1361     nmethod_data->invalidate_nmethod_mirror(this);
1362   }
1363 #endif
1364 
1365 #ifdef ASSERT
1366   if (is_osr_method() && method() != NULL) {
1367     // Make sure osr nmethod is invalidated, i.e. not on the list
1368     bool found = method()->method_holder()->remove_osr_nmethod(this);
1369     assert(!found, "osr nmethod should have been invalidated");
1370   }
1371 #endif
1372 
1373   // When the nmethod becomes zombie it is no longer alive so the
1374   // dependencies must be flushed.  nmethods in the not_entrant
1375   // state will be flushed later when the transition to zombie
1376   // happens or they get unloaded.
1377   if (state == zombie) {
1378     {
1379       // Flushing dependencies must be done before any possible
1380       // safepoint can sneak in, otherwise the oops used by the
1381       // dependency logic could have become stale.
1382       MutexLocker mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
1383       if (nmethod_needs_unregister) {
1384         Universe::heap()->unregister_nmethod(this);
1385       }
1386       flush_dependencies(/*delete_immediately*/true);
1387     }
1388 
1389 #if INCLUDE_JVMCI
1390     // Now that the nmethod has been unregistered, it's
1391     // safe to clear the HotSpotNmethod mirror oop.
1392     if (nmethod_data != NULL) {
1393       nmethod_data->clear_nmethod_mirror(this);
1394     }
1395 #endif
1396 
1397     // Clear ICStubs to prevent back patching stubs of zombie or flushed
1398     // nmethods during the next safepoint (see ICStub::finalize), as well
1399     // as to free up CompiledICHolder resources.
1400     {
1401       CompiledICLocker ml(this);
1402       clear_ic_callsites();
1403     }
1404 
1405     // zombie only - if a JVMTI agent has enabled the CompiledMethodUnload
1406     // event and it hasn't already been reported for this nmethod then
1407     // report it now. The event may have been reported earlier if the GC
1408     // marked it for unloading). JvmtiDeferredEventQueue support means
1409     // we no longer go to a safepoint here.
1410     post_compiled_method_unload();
1411 
1412 #ifdef ASSERT
1413     // It's no longer safe to access the oops section since zombie
1414     // nmethods aren't scanned for GC.
1415     _oops_are_stale = true;
1416 #endif
1417      // the Method may be reclaimed by class unloading now that the
1418      // nmethod is in zombie state
1419     set_method(NULL);
1420   } else {
1421     assert(state == not_entrant, "other cases may need to be handled differently");
1422   }
1423 
1424   if (TraceCreateZombies && state == zombie) {
1425     ResourceMark m;
1426     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");
1427   }
1428 
1429   NMethodSweeper::report_state_change(this);
1430   return true;
1431 }
1432 
1433 void nmethod::flush() {
1434   MutexLocker mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
1435   // Note that there are no valid oops in the nmethod anymore.
1436   assert(!is_osr_method() || is_unloaded() || is_zombie(),
1437          "osr nmethod must be unloaded or zombie before flushing");
1438   assert(is_zombie() || is_osr_method(), "must be a zombie method");
1439   assert (!is_locked_by_vm(), "locked methods shouldn't be flushed");
1440   assert_locked_or_safepoint(CodeCache_lock);
1441 
1442   // completely deallocate this method
1443   Events::log(JavaThread::current(), "flushing nmethod " INTPTR_FORMAT, p2i(this));
1444   if (PrintMethodFlushing) {
1445     tty->print_cr("*flushing %s nmethod %3d/" INTPTR_FORMAT ". Live blobs:" UINT32_FORMAT
1446                   "/Free CodeCache:" SIZE_FORMAT "Kb",
1447                   is_osr_method() ? "osr" : "",_compile_id, p2i(this), CodeCache::blob_count(),
1448                   CodeCache::unallocated_capacity(CodeCache::get_code_blob_type(this))/1024);
1449   }
1450 
1451   // We need to deallocate any ExceptionCache data.
1452   // Note that we do not need to grab the nmethod lock for this, it
1453   // better be thread safe if we're disposing of it!
1454   ExceptionCache* ec = exception_cache();
1455   set_exception_cache(NULL);
1456   while(ec != NULL) {
1457     ExceptionCache* next = ec->next();
1458     delete ec;
1459     ec = next;
1460   }
1461 
1462   Universe::heap()->flush_nmethod(this);
1463   CodeCache::unregister_old_nmethod(this);
1464 
1465   CodeBlob::flush();
1466   CodeCache::free(this);
1467 }
1468 
1469 oop nmethod::oop_at(int index) const {
1470   if (index == 0) {
1471     return NULL;
1472   }
1473   return NativeAccess<AS_NO_KEEPALIVE>::oop_load(oop_addr_at(index));
1474 }
1475 
1476 //
1477 // Notify all classes this nmethod is dependent on that it is no
1478 // longer dependent. This should only be called in two situations.
1479 // First, when a nmethod transitions to a zombie all dependents need
1480 // to be clear.  Since zombification happens at a safepoint there's no
1481 // synchronization issues.  The second place is a little more tricky.
1482 // During phase 1 of mark sweep class unloading may happen and as a
1483 // result some nmethods may get unloaded.  In this case the flushing
1484 // of dependencies must happen during phase 1 since after GC any
1485 // dependencies in the unloaded nmethod won't be updated, so
1486 // traversing the dependency information in unsafe.  In that case this
1487 // function is called with a boolean argument and this function only
1488 // notifies instanceKlasses that are reachable
1489 
1490 void nmethod::flush_dependencies(bool delete_immediately) {
1491   DEBUG_ONLY(bool called_by_gc = Universe::heap()->is_gc_active() || Thread::current()->is_ConcurrentGC_thread();)
1492   assert(called_by_gc != delete_immediately,
1493   "delete_immediately is false if and only if we are called during GC");
1494   if (!has_flushed_dependencies()) {
1495     set_has_flushed_dependencies();
1496     for (Dependencies::DepStream deps(this); deps.next(); ) {
1497       if (deps.type() == Dependencies::call_site_target_value) {
1498         // CallSite dependencies are managed on per-CallSite instance basis.
1499         oop call_site = deps.argument_oop(0);
1500         if (delete_immediately) {
1501           assert_locked_or_safepoint(CodeCache_lock);
1502           MethodHandles::remove_dependent_nmethod(call_site, this);
1503         } else {
1504           MethodHandles::clean_dependency_context(call_site);
1505         }
1506       } else {
1507         Klass* klass = deps.context_type();
1508         if (klass == NULL) {
1509           continue;  // ignore things like evol_method
1510         }
1511         // During GC delete_immediately is false, and liveness
1512         // of dependee determines class that needs to be updated.
1513         if (delete_immediately) {
1514           assert_locked_or_safepoint(CodeCache_lock);
1515           InstanceKlass::cast(klass)->remove_dependent_nmethod(this);
1516         } else if (klass->is_loader_alive()) {
1517           // The GC may clean dependency contexts concurrently and in parallel.
1518           InstanceKlass::cast(klass)->clean_dependency_context();
1519         }
1520       }
1521     }
1522   }
1523 }
1524 
1525 // ------------------------------------------------------------------
1526 // post_compiled_method_load_event
1527 // new method for install_code() path
1528 // Transfer information from compilation to jvmti
1529 void nmethod::post_compiled_method_load_event() {
1530 
1531   Method* moop = method();
1532   HOTSPOT_COMPILED_METHOD_LOAD(
1533       (char *) moop->klass_name()->bytes(),
1534       moop->klass_name()->utf8_length(),
1535       (char *) moop->name()->bytes(),
1536       moop->name()->utf8_length(),
1537       (char *) moop->signature()->bytes(),
1538       moop->signature()->utf8_length(),
1539       insts_begin(), insts_size());
1540 
1541   if (JvmtiExport::should_post_compiled_method_load() ||
1542       JvmtiExport::should_post_compiled_method_unload()) {
1543     get_and_cache_jmethod_id();
1544   }
1545 
1546   if (JvmtiExport::should_post_compiled_method_load()) {
1547     // Let the Service thread (which is a real Java thread) post the event
1548     MutexLocker ml(Service_lock, Mutex::_no_safepoint_check_flag);
1549     JvmtiDeferredEventQueue::enqueue(
1550       JvmtiDeferredEvent::compiled_method_load_event(this));
1551   }
1552 }
1553 
1554 jmethodID nmethod::get_and_cache_jmethod_id() {
1555   if (_jmethod_id == NULL) {
1556     // Cache the jmethod_id since it can no longer be looked up once the
1557     // method itself has been marked for unloading.
1558     _jmethod_id = method()->jmethod_id();
1559   }
1560   return _jmethod_id;
1561 }
1562 
1563 void nmethod::post_compiled_method_unload() {
1564   if (unload_reported()) {
1565     // During unloading we transition to unloaded and then to zombie
1566     // and the unloading is reported during the first transition.
1567     return;
1568   }
1569 
1570   assert(_method != NULL && !is_unloaded(), "just checking");
1571   DTRACE_METHOD_UNLOAD_PROBE(method());
1572 
1573   // If a JVMTI agent has enabled the CompiledMethodUnload event then
1574   // post the event. Sometime later this nmethod will be made a zombie
1575   // by the sweeper but the Method* will not be valid at that point.
1576   // If the _jmethod_id is null then no load event was ever requested
1577   // so don't bother posting the unload.  The main reason for this is
1578   // that the jmethodID is a weak reference to the Method* so if
1579   // it's being unloaded there's no way to look it up since the weak
1580   // ref will have been cleared.
1581   if (_jmethod_id != NULL && JvmtiExport::should_post_compiled_method_unload()) {
1582     assert(!unload_reported(), "already unloaded");
1583     JvmtiDeferredEvent event =
1584       JvmtiDeferredEvent::compiled_method_unload_event(this,
1585           _jmethod_id, insts_begin());
1586     MutexLocker ml(Service_lock, Mutex::_no_safepoint_check_flag);
1587     JvmtiDeferredEventQueue::enqueue(event);
1588   }
1589 
1590   // The JVMTI CompiledMethodUnload event can be enabled or disabled at
1591   // any time. As the nmethod is being unloaded now we mark it has
1592   // having the unload event reported - this will ensure that we don't
1593   // attempt to report the event in the unlikely scenario where the
1594   // event is enabled at the time the nmethod is made a zombie.
1595   set_unload_reported();
1596 }
1597 
1598 // Iterate over metadata calling this function.   Used by RedefineClasses
1599 void nmethod::metadata_do(MetadataClosure* f) {
1600   {
1601     // Visit all immediate references that are embedded in the instruction stream.
1602     RelocIterator iter(this, oops_reloc_begin());
1603     while (iter.next()) {
1604       if (iter.type() == relocInfo::metadata_type) {
1605         metadata_Relocation* r = iter.metadata_reloc();
1606         // In this metadata, we must only follow those metadatas directly embedded in
1607         // the code.  Other metadatas (oop_index>0) are seen as part of
1608         // the metadata section below.
1609         assert(1 == (r->metadata_is_immediate()) +
1610                (r->metadata_addr() >= metadata_begin() && r->metadata_addr() < metadata_end()),
1611                "metadata must be found in exactly one place");
1612         if (r->metadata_is_immediate() && r->metadata_value() != NULL) {
1613           Metadata* md = r->metadata_value();
1614           if (md != _method) f->do_metadata(md);
1615         }
1616       } else if (iter.type() == relocInfo::virtual_call_type) {
1617         // Check compiledIC holders associated with this nmethod
1618         ResourceMark rm;
1619         CompiledIC *ic = CompiledIC_at(&iter);
1620         if (ic->is_icholder_call()) {
1621           CompiledICHolder* cichk = ic->cached_icholder();
1622           f->do_metadata(cichk->holder_metadata());
1623           f->do_metadata(cichk->holder_klass());
1624         } else {
1625           Metadata* ic_oop = ic->cached_metadata();
1626           if (ic_oop != NULL) {
1627             f->do_metadata(ic_oop);
1628           }
1629         }
1630       }
1631     }
1632   }
1633 
1634   // Visit the metadata section
1635   for (Metadata** p = metadata_begin(); p < metadata_end(); p++) {
1636     if (*p == Universe::non_oop_word() || *p == NULL)  continue;  // skip non-oops
1637     Metadata* md = *p;
1638     f->do_metadata(md);
1639   }
1640 
1641   // Visit metadata not embedded in the other places.
1642   if (_method != NULL) f->do_metadata(_method);
1643 }
1644 
1645 // The _is_unloading_state encodes a tuple comprising the unloading cycle
1646 // and the result of IsUnloadingBehaviour::is_unloading() fpr that cycle.
1647 // This is the bit layout of the _is_unloading_state byte: 00000CCU
1648 // CC refers to the cycle, which has 2 bits, and U refers to the result of
1649 // IsUnloadingBehaviour::is_unloading() for that unloading cycle.
1650 
1651 class IsUnloadingState: public AllStatic {
1652   static const uint8_t _is_unloading_mask = 1;
1653   static const uint8_t _is_unloading_shift = 0;
1654   static const uint8_t _unloading_cycle_mask = 6;
1655   static const uint8_t _unloading_cycle_shift = 1;
1656 
1657   static uint8_t set_is_unloading(uint8_t state, bool value) {
1658     state &= ~_is_unloading_mask;
1659     if (value) {
1660       state |= 1 << _is_unloading_shift;
1661     }
1662     assert(is_unloading(state) == value, "unexpected unloading cycle overflow");
1663     return state;
1664   }
1665 
1666   static uint8_t set_unloading_cycle(uint8_t state, uint8_t value) {
1667     state &= ~_unloading_cycle_mask;
1668     state |= value << _unloading_cycle_shift;
1669     assert(unloading_cycle(state) == value, "unexpected unloading cycle overflow");
1670     return state;
1671   }
1672 
1673 public:
1674   static bool is_unloading(uint8_t state) { return (state & _is_unloading_mask) >> _is_unloading_shift == 1; }
1675   static uint8_t unloading_cycle(uint8_t state) { return (state & _unloading_cycle_mask) >> _unloading_cycle_shift; }
1676 
1677   static uint8_t create(bool is_unloading, uint8_t unloading_cycle) {
1678     uint8_t state = 0;
1679     state = set_is_unloading(state, is_unloading);
1680     state = set_unloading_cycle(state, unloading_cycle);
1681     return state;
1682   }
1683 };
1684 
1685 bool nmethod::is_unloading() {
1686   uint8_t state = RawAccess<MO_RELAXED>::load(&_is_unloading_state);
1687   bool state_is_unloading = IsUnloadingState::is_unloading(state);
1688   uint8_t state_unloading_cycle = IsUnloadingState::unloading_cycle(state);
1689   if (state_is_unloading) {
1690     return true;
1691   }
1692   uint8_t current_cycle = CodeCache::unloading_cycle();
1693   if (state_unloading_cycle == current_cycle) {
1694     return false;
1695   }
1696 
1697   // The IsUnloadingBehaviour is responsible for checking if there are any dead
1698   // oops in the CompiledMethod, by calling oops_do on it.
1699   state_unloading_cycle = current_cycle;
1700 
1701   if (is_zombie()) {
1702     // Zombies without calculated unloading epoch are never unloading due to GC.
1703 
1704     // There are no races where a previously observed is_unloading() nmethod
1705     // suddenly becomes not is_unloading() due to here being observed as zombie.
1706 
1707     // With STW unloading, all is_alive() && is_unloading() nmethods are unlinked
1708     // and unloaded in the safepoint. That makes races where an nmethod is first
1709     // observed as is_alive() && is_unloading() and subsequently observed as
1710     // is_zombie() impossible.
1711 
1712     // With concurrent unloading, all references to is_unloading() nmethods are
1713     // first unlinked (e.g. IC caches and dependency contexts). Then a global
1714     // handshake operation is performed with all JavaThreads before finally
1715     // unloading the nmethods. The sweeper never converts is_alive() && is_unloading()
1716     // nmethods to zombies; it waits for them to become is_unloaded(). So before
1717     // the global handshake, it is impossible for is_unloading() nmethods to
1718     // racingly become is_zombie(). And is_unloading() is calculated for all is_alive()
1719     // nmethods before taking that global handshake, meaning that it will never
1720     // be recalculated after the handshake.
1721 
1722     // After that global handshake, is_unloading() nmethods are only observable
1723     // to the iterators, and they will never trigger recomputation of the cached
1724     // is_unloading_state, and hence may not suffer from such races.
1725 
1726     state_is_unloading = false;
1727   } else {
1728     state_is_unloading = IsUnloadingBehaviour::current()->is_unloading(this);
1729   }
1730 
1731   state = IsUnloadingState::create(state_is_unloading, state_unloading_cycle);
1732 
1733   RawAccess<MO_RELAXED>::store(&_is_unloading_state, state);
1734 
1735   return state_is_unloading;
1736 }
1737 
1738 void nmethod::clear_unloading_state() {
1739   uint8_t state = IsUnloadingState::create(false, CodeCache::unloading_cycle());
1740   RawAccess<MO_RELAXED>::store(&_is_unloading_state, state);
1741 }
1742 
1743 
1744 // This is called at the end of the strong tracing/marking phase of a
1745 // GC to unload an nmethod if it contains otherwise unreachable
1746 // oops.
1747 
1748 void nmethod::do_unloading(bool unloading_occurred) {
1749   // Make sure the oop's ready to receive visitors
1750   assert(!is_zombie() && !is_unloaded(),
1751          "should not call follow on zombie or unloaded nmethod");
1752 
1753   if (is_unloading()) {
1754     make_unloaded();
1755   } else {
1756     guarantee(unload_nmethod_caches(unloading_occurred),
1757               "Should not need transition stubs");
1758   }
1759 }
1760 
1761 void nmethod::oops_do(OopClosure* f, bool allow_zombie) {
1762   // make sure the oops ready to receive visitors
1763   assert(allow_zombie || !is_zombie(), "should not call follow on zombie nmethod");
1764   assert(!is_unloaded(), "should not call follow on unloaded nmethod");
1765 
1766   // Prevent extra code cache walk for platforms that don't have immediate oops.
1767   if (relocInfo::mustIterateImmediateOopsInCode()) {
1768     RelocIterator iter(this, oops_reloc_begin());
1769 
1770     while (iter.next()) {
1771       if (iter.type() == relocInfo::oop_type ) {
1772         oop_Relocation* r = iter.oop_reloc();
1773         // In this loop, we must only follow those oops directly embedded in
1774         // the code.  Other oops (oop_index>0) are seen as part of scopes_oops.
1775         assert(1 == (r->oop_is_immediate()) +
1776                (r->oop_addr() >= oops_begin() && r->oop_addr() < oops_end()),
1777                "oop must be found in exactly one place");
1778         if (r->oop_is_immediate() && r->oop_value() != NULL) {
1779           f->do_oop(r->oop_addr());
1780         }
1781       }
1782     }
1783   }
1784 
1785   // Scopes
1786   // This includes oop constants not inlined in the code stream.
1787   for (oop* p = oops_begin(); p < oops_end(); p++) {
1788     if (*p == Universe::non_oop_word())  continue;  // skip non-oops
1789     f->do_oop(p);
1790   }
1791 }
1792 
1793 #define NMETHOD_SENTINEL ((nmethod*)badAddress)
1794 
1795 nmethod* volatile nmethod::_oops_do_mark_nmethods;
1796 
1797 // An nmethod is "marked" if its _mark_link is set non-null.
1798 // Even if it is the end of the linked list, it will have a non-null link value,
1799 // as long as it is on the list.
1800 // This code must be MP safe, because it is used from parallel GC passes.
1801 bool nmethod::test_set_oops_do_mark() {
1802   assert(nmethod::oops_do_marking_is_active(), "oops_do_marking_prologue must be called");
1803   if (_oops_do_mark_link == NULL) {
1804     // Claim this nmethod for this thread to mark.
1805     if (Atomic::replace_if_null(NMETHOD_SENTINEL, &_oops_do_mark_link)) {
1806       // Atomically append this nmethod (now claimed) to the head of the list:
1807       nmethod* observed_mark_nmethods = _oops_do_mark_nmethods;
1808       for (;;) {
1809         nmethod* required_mark_nmethods = observed_mark_nmethods;
1810         _oops_do_mark_link = required_mark_nmethods;
1811         observed_mark_nmethods =
1812           Atomic::cmpxchg(this, &_oops_do_mark_nmethods, required_mark_nmethods);
1813         if (observed_mark_nmethods == required_mark_nmethods)
1814           break;
1815       }
1816       // Mark was clear when we first saw this guy.
1817       LogTarget(Trace, gc, nmethod) lt;
1818       if (lt.is_enabled()) {
1819         LogStream ls(lt);
1820         CompileTask::print(&ls, this, "oops_do, mark", /*short_form:*/ true);
1821       }
1822       return false;
1823     }
1824   }
1825   // On fall through, another racing thread marked this nmethod before we did.
1826   return true;
1827 }
1828 
1829 void nmethod::oops_do_marking_prologue() {
1830   log_trace(gc, nmethod)("oops_do_marking_prologue");
1831   assert(_oops_do_mark_nmethods == NULL, "must not call oops_do_marking_prologue twice in a row");
1832   // We use cmpxchg instead of regular assignment here because the user
1833   // may fork a bunch of threads, and we need them all to see the same state.
1834   nmethod* observed = Atomic::cmpxchg(NMETHOD_SENTINEL, &_oops_do_mark_nmethods, (nmethod*)NULL);
1835   guarantee(observed == NULL, "no races in this sequential code");
1836 }
1837 
1838 void nmethod::oops_do_marking_epilogue() {
1839   assert(_oops_do_mark_nmethods != NULL, "must not call oops_do_marking_epilogue twice in a row");
1840   nmethod* cur = _oops_do_mark_nmethods;
1841   while (cur != NMETHOD_SENTINEL) {
1842     assert(cur != NULL, "not NULL-terminated");
1843     nmethod* next = cur->_oops_do_mark_link;
1844     cur->_oops_do_mark_link = NULL;
1845     DEBUG_ONLY(cur->verify_oop_relocations());
1846 
1847     LogTarget(Trace, gc, nmethod) lt;
1848     if (lt.is_enabled()) {
1849       LogStream ls(lt);
1850       CompileTask::print(&ls, cur, "oops_do, unmark", /*short_form:*/ true);
1851     }
1852     cur = next;
1853   }
1854   nmethod* required = _oops_do_mark_nmethods;
1855   nmethod* observed = Atomic::cmpxchg((nmethod*)NULL, &_oops_do_mark_nmethods, required);
1856   guarantee(observed == required, "no races in this sequential code");
1857   log_trace(gc, nmethod)("oops_do_marking_epilogue");
1858 }
1859 
1860 inline bool includes(void* p, void* from, void* to) {
1861   return from <= p && p < to;
1862 }
1863 
1864 
1865 void nmethod::copy_scopes_pcs(PcDesc* pcs, int count) {
1866   assert(count >= 2, "must be sentinel values, at least");
1867 
1868 #ifdef ASSERT
1869   // must be sorted and unique; we do a binary search in find_pc_desc()
1870   int prev_offset = pcs[0].pc_offset();
1871   assert(prev_offset == PcDesc::lower_offset_limit,
1872          "must start with a sentinel");
1873   for (int i = 1; i < count; i++) {
1874     int this_offset = pcs[i].pc_offset();
1875     assert(this_offset > prev_offset, "offsets must be sorted");
1876     prev_offset = this_offset;
1877   }
1878   assert(prev_offset == PcDesc::upper_offset_limit,
1879          "must end with a sentinel");
1880 #endif //ASSERT
1881 
1882   // Search for MethodHandle invokes and tag the nmethod.
1883   for (int i = 0; i < count; i++) {
1884     if (pcs[i].is_method_handle_invoke()) {
1885       set_has_method_handle_invokes(true);
1886       break;
1887     }
1888   }
1889   assert(has_method_handle_invokes() == (_deopt_mh_handler_begin != NULL), "must have deopt mh handler");
1890 
1891   int size = count * sizeof(PcDesc);
1892   assert(scopes_pcs_size() >= size, "oob");
1893   memcpy(scopes_pcs_begin(), pcs, size);
1894 
1895   // Adjust the final sentinel downward.
1896   PcDesc* last_pc = &scopes_pcs_begin()[count-1];
1897   assert(last_pc->pc_offset() == PcDesc::upper_offset_limit, "sanity");
1898   last_pc->set_pc_offset(content_size() + 1);
1899   for (; last_pc + 1 < scopes_pcs_end(); last_pc += 1) {
1900     // Fill any rounding gaps with copies of the last record.
1901     last_pc[1] = last_pc[0];
1902   }
1903   // The following assert could fail if sizeof(PcDesc) is not
1904   // an integral multiple of oopSize (the rounding term).
1905   // If it fails, change the logic to always allocate a multiple
1906   // of sizeof(PcDesc), and fill unused words with copies of *last_pc.
1907   assert(last_pc + 1 == scopes_pcs_end(), "must match exactly");
1908 }
1909 
1910 void nmethod::copy_scopes_data(u_char* buffer, int size) {
1911   assert(scopes_data_size() >= size, "oob");
1912   memcpy(scopes_data_begin(), buffer, size);
1913 }
1914 
1915 #ifdef ASSERT
1916 static PcDesc* linear_search(const PcDescSearch& search, int pc_offset, bool approximate) {
1917   PcDesc* lower = search.scopes_pcs_begin();
1918   PcDesc* upper = search.scopes_pcs_end();
1919   lower += 1; // exclude initial sentinel
1920   PcDesc* res = NULL;
1921   for (PcDesc* p = lower; p < upper; p++) {
1922     NOT_PRODUCT(--pc_nmethod_stats.pc_desc_tests);  // don't count this call to match_desc
1923     if (match_desc(p, pc_offset, approximate)) {
1924       if (res == NULL)
1925         res = p;
1926       else
1927         res = (PcDesc*) badAddress;
1928     }
1929   }
1930   return res;
1931 }
1932 #endif
1933 
1934 
1935 // Finds a PcDesc with real-pc equal to "pc"
1936 PcDesc* PcDescContainer::find_pc_desc_internal(address pc, bool approximate, const PcDescSearch& search) {
1937   address base_address = search.code_begin();
1938   if ((pc < base_address) ||
1939       (pc - base_address) >= (ptrdiff_t) PcDesc::upper_offset_limit) {
1940     return NULL;  // PC is wildly out of range
1941   }
1942   int pc_offset = (int) (pc - base_address);
1943 
1944   // Check the PcDesc cache if it contains the desired PcDesc
1945   // (This as an almost 100% hit rate.)
1946   PcDesc* res = _pc_desc_cache.find_pc_desc(pc_offset, approximate);
1947   if (res != NULL) {
1948     assert(res == linear_search(search, pc_offset, approximate), "cache ok");
1949     return res;
1950   }
1951 
1952   // Fallback algorithm: quasi-linear search for the PcDesc
1953   // Find the last pc_offset less than the given offset.
1954   // The successor must be the required match, if there is a match at all.
1955   // (Use a fixed radix to avoid expensive affine pointer arithmetic.)
1956   PcDesc* lower = search.scopes_pcs_begin();
1957   PcDesc* upper = search.scopes_pcs_end();
1958   upper -= 1; // exclude final sentinel
1959   if (lower >= upper)  return NULL;  // native method; no PcDescs at all
1960 
1961 #define assert_LU_OK \
1962   /* invariant on lower..upper during the following search: */ \
1963   assert(lower->pc_offset() <  pc_offset, "sanity"); \
1964   assert(upper->pc_offset() >= pc_offset, "sanity")
1965   assert_LU_OK;
1966 
1967   // Use the last successful return as a split point.
1968   PcDesc* mid = _pc_desc_cache.last_pc_desc();
1969   NOT_PRODUCT(++pc_nmethod_stats.pc_desc_searches);
1970   if (mid->pc_offset() < pc_offset) {
1971     lower = mid;
1972   } else {
1973     upper = mid;
1974   }
1975 
1976   // Take giant steps at first (4096, then 256, then 16, then 1)
1977   const int LOG2_RADIX = 4 /*smaller steps in debug mode:*/ debug_only(-1);
1978   const int RADIX = (1 << LOG2_RADIX);
1979   for (int step = (1 << (LOG2_RADIX*3)); step > 1; step >>= LOG2_RADIX) {
1980     while ((mid = lower + step) < upper) {
1981       assert_LU_OK;
1982       NOT_PRODUCT(++pc_nmethod_stats.pc_desc_searches);
1983       if (mid->pc_offset() < pc_offset) {
1984         lower = mid;
1985       } else {
1986         upper = mid;
1987         break;
1988       }
1989     }
1990     assert_LU_OK;
1991   }
1992 
1993   // Sneak up on the value with a linear search of length ~16.
1994   while (true) {
1995     assert_LU_OK;
1996     mid = lower + 1;
1997     NOT_PRODUCT(++pc_nmethod_stats.pc_desc_searches);
1998     if (mid->pc_offset() < pc_offset) {
1999       lower = mid;
2000     } else {
2001       upper = mid;
2002       break;
2003     }
2004   }
2005 #undef assert_LU_OK
2006 
2007   if (match_desc(upper, pc_offset, approximate)) {
2008     assert(upper == linear_search(search, pc_offset, approximate), "search ok");
2009     _pc_desc_cache.add_pc_desc(upper);
2010     return upper;
2011   } else {
2012     assert(NULL == linear_search(search, pc_offset, approximate), "search ok");
2013     return NULL;
2014   }
2015 }
2016 
2017 
2018 void nmethod::check_all_dependencies(DepChange& changes) {
2019   // Checked dependencies are allocated into this ResourceMark
2020   ResourceMark rm;
2021 
2022   // Turn off dependency tracing while actually testing dependencies.
2023   NOT_PRODUCT( FlagSetting fs(TraceDependencies, false) );
2024 
2025   typedef ResourceHashtable<DependencySignature, int, &DependencySignature::hash,
2026                             &DependencySignature::equals, 11027> DepTable;
2027 
2028   DepTable* table = new DepTable();
2029 
2030   // Iterate over live nmethods and check dependencies of all nmethods that are not
2031   // marked for deoptimization. A particular dependency is only checked once.
2032   NMethodIterator iter(NMethodIterator::only_alive_and_not_unloading);
2033   while(iter.next()) {
2034     nmethod* nm = iter.method();
2035     // Only notify for live nmethods
2036     if (!nm->is_marked_for_deoptimization()) {
2037       for (Dependencies::DepStream deps(nm); deps.next(); ) {
2038         // Construct abstraction of a dependency.
2039         DependencySignature* current_sig = new DependencySignature(deps);
2040 
2041         // Determine if dependency is already checked. table->put(...) returns
2042         // 'true' if the dependency is added (i.e., was not in the hashtable).
2043         if (table->put(*current_sig, 1)) {
2044           if (deps.check_dependency() != NULL) {
2045             // Dependency checking failed. Print out information about the failed
2046             // dependency and finally fail with an assert. We can fail here, since
2047             // dependency checking is never done in a product build.
2048             tty->print_cr("Failed dependency:");
2049             changes.print();
2050             nm->print();
2051             nm->print_dependencies();
2052             assert(false, "Should have been marked for deoptimization");
2053           }
2054         }
2055       }
2056     }
2057   }
2058 }
2059 
2060 bool nmethod::check_dependency_on(DepChange& changes) {
2061   // What has happened:
2062   // 1) a new class dependee has been added
2063   // 2) dependee and all its super classes have been marked
2064   bool found_check = false;  // set true if we are upset
2065   for (Dependencies::DepStream deps(this); deps.next(); ) {
2066     // Evaluate only relevant dependencies.
2067     if (deps.spot_check_dependency_at(changes) != NULL) {
2068       found_check = true;
2069       NOT_DEBUG(break);
2070     }
2071   }
2072   return found_check;
2073 }
2074 
2075 // Called from mark_for_deoptimization, when dependee is invalidated.
2076 bool nmethod::is_dependent_on_method(Method* dependee) {
2077   for (Dependencies::DepStream deps(this); deps.next(); ) {
2078     if (deps.type() != Dependencies::evol_method)
2079       continue;
2080     Method* method = deps.method_argument(0);
2081     if (method == dependee) return true;
2082   }
2083   return false;
2084 }
2085 
2086 
2087 bool nmethod::is_patchable_at(address instr_addr) {
2088   assert(insts_contains(instr_addr), "wrong nmethod used");
2089   if (is_zombie()) {
2090     // a zombie may never be patched
2091     return false;
2092   }
2093   return true;
2094 }
2095 
2096 
2097 void nmethod_init() {
2098   // make sure you didn't forget to adjust the filler fields
2099   assert(sizeof(nmethod) % oopSize == 0, "nmethod size must be multiple of a word");
2100 }
2101 
2102 
2103 //-------------------------------------------------------------------------------------------
2104 
2105 
2106 // QQQ might we make this work from a frame??
2107 nmethodLocker::nmethodLocker(address pc) {
2108   CodeBlob* cb = CodeCache::find_blob(pc);
2109   guarantee(cb != NULL && cb->is_compiled(), "bad pc for a nmethod found");
2110   _nm = cb->as_compiled_method();
2111   lock_nmethod(_nm);
2112 }
2113 
2114 // Only JvmtiDeferredEvent::compiled_method_unload_event()
2115 // should pass zombie_ok == true.
2116 void nmethodLocker::lock_nmethod(CompiledMethod* cm, bool zombie_ok) {
2117   if (cm == NULL)  return;
2118   if (cm->is_aot()) return;  // FIXME: Revisit once _lock_count is added to aot_method
2119   nmethod* nm = cm->as_nmethod();
2120   Atomic::inc(&nm->_lock_count);
2121   assert(zombie_ok || !nm->is_zombie(), "cannot lock a zombie method: %p", nm);
2122 }
2123 
2124 void nmethodLocker::unlock_nmethod(CompiledMethod* cm) {
2125   if (cm == NULL)  return;
2126   if (cm->is_aot()) return;  // FIXME: Revisit once _lock_count is added to aot_method
2127   nmethod* nm = cm->as_nmethod();
2128   Atomic::dec(&nm->_lock_count);
2129   assert(nm->_lock_count >= 0, "unmatched nmethod lock/unlock");
2130 }
2131 
2132 
2133 // -----------------------------------------------------------------------------
2134 // Verification
2135 
2136 class VerifyOopsClosure: public OopClosure {
2137   nmethod* _nm;
2138   bool     _ok;
2139 public:
2140   VerifyOopsClosure(nmethod* nm) : _nm(nm), _ok(true) { }
2141   bool ok() { return _ok; }
2142   virtual void do_oop(oop* p) {
2143     if (oopDesc::is_oop_or_null(*p)) return;
2144     // Print diagnostic information before calling print_nmethod().
2145     // Assertions therein might prevent call from returning.
2146     tty->print_cr("*** non-oop " PTR_FORMAT " found at " PTR_FORMAT " (offset %d)",
2147                   p2i(*p), p2i(p), (int)((intptr_t)p - (intptr_t)_nm));
2148     if (_ok) {
2149       _nm->print_nmethod(true);
2150       _ok = false;
2151     }
2152   }
2153   virtual void do_oop(narrowOop* p) { ShouldNotReachHere(); }
2154 };
2155 
2156 void nmethod::verify() {
2157 
2158   // Hmm. OSR methods can be deopted but not marked as zombie or not_entrant
2159   // seems odd.
2160 
2161   if (is_zombie() || is_not_entrant() || is_unloaded())
2162     return;
2163 
2164   // Make sure all the entry points are correctly aligned for patching.
2165   NativeJump::check_verified_entry_alignment(entry_point(), verified_entry_point());
2166 
2167   // assert(oopDesc::is_oop(method()), "must be valid");
2168 
2169   ResourceMark rm;
2170 
2171   if (!CodeCache::contains(this)) {
2172     fatal("nmethod at " INTPTR_FORMAT " not in zone", p2i(this));
2173   }
2174 
2175   if(is_native_method() )
2176     return;
2177 
2178   nmethod* nm = CodeCache::find_nmethod(verified_entry_point());
2179   if (nm != this) {
2180     fatal("findNMethod did not find this nmethod (" INTPTR_FORMAT ")", p2i(this));
2181   }
2182 
2183   for (PcDesc* p = scopes_pcs_begin(); p < scopes_pcs_end(); p++) {
2184     if (! p->verify(this)) {
2185       tty->print_cr("\t\tin nmethod at " INTPTR_FORMAT " (pcs)", p2i(this));
2186     }
2187   }
2188 
2189 #ifdef ASSERT
2190 #if INCLUDE_JVMCI
2191   {
2192     // Verify that implicit exceptions that deoptimize have a PcDesc and OopMap
2193     ImmutableOopMapSet* oms = oop_maps();
2194     ImplicitExceptionTable implicit_table(this);
2195     for (uint i = 0; i < implicit_table.len(); i++) {
2196       int exec_offset = (int) implicit_table.get_exec_offset(i);
2197       if (implicit_table.get_exec_offset(i) == implicit_table.get_cont_offset(i)) {
2198         assert(pc_desc_at(code_begin() + exec_offset) != NULL, "missing PcDesc");
2199         bool found = false;
2200         for (int i = 0, imax = oms->count(); i < imax; i++) {
2201           if (oms->pair_at(i)->pc_offset() == exec_offset) {
2202             found = true;
2203             break;
2204           }
2205         }
2206         assert(found, "missing oopmap");
2207       }
2208     }
2209   }
2210 #endif
2211 #endif
2212 
2213   VerifyOopsClosure voc(this);
2214   oops_do(&voc);
2215   assert(voc.ok(), "embedded oops must be OK");
2216   Universe::heap()->verify_nmethod(this);
2217 
2218   verify_scopes();
2219 }
2220 
2221 
2222 void nmethod::verify_interrupt_point(address call_site) {
2223   // Verify IC only when nmethod installation is finished.
2224   if (!is_not_installed()) {
2225     if (CompiledICLocker::is_safe(this)) {
2226       CompiledIC_at(this, call_site);
2227       CHECK_UNHANDLED_OOPS_ONLY(Thread::current()->clear_unhandled_oops());
2228     } else {
2229       CompiledICLocker ml_verify(this);
2230       CompiledIC_at(this, call_site);
2231     }
2232   }
2233 
2234   PcDesc* pd = pc_desc_at(nativeCall_at(call_site)->return_address());
2235   assert(pd != NULL, "PcDesc must exist");
2236   for (ScopeDesc* sd = new ScopeDesc(this, pd->scope_decode_offset(),
2237                                      pd->obj_decode_offset(), pd->should_reexecute(), pd->rethrow_exception(),
2238                                      pd->return_oop());
2239        !sd->is_top(); sd = sd->sender()) {
2240     sd->verify();
2241   }
2242 }
2243 
2244 void nmethod::verify_scopes() {
2245   if( !method() ) return;       // Runtime stubs have no scope
2246   if (method()->is_native()) return; // Ignore stub methods.
2247   // iterate through all interrupt point
2248   // and verify the debug information is valid.
2249   RelocIterator iter((nmethod*)this);
2250   while (iter.next()) {
2251     address stub = NULL;
2252     switch (iter.type()) {
2253       case relocInfo::virtual_call_type:
2254         verify_interrupt_point(iter.addr());
2255         break;
2256       case relocInfo::opt_virtual_call_type:
2257         stub = iter.opt_virtual_call_reloc()->static_stub(false);
2258         verify_interrupt_point(iter.addr());
2259         break;
2260       case relocInfo::static_call_type:
2261         stub = iter.static_call_reloc()->static_stub(false);
2262         //verify_interrupt_point(iter.addr());
2263         break;
2264       case relocInfo::runtime_call_type:
2265       case relocInfo::runtime_call_w_cp_type: {
2266         address destination = iter.reloc()->value();
2267         // Right now there is no way to find out which entries support
2268         // an interrupt point.  It would be nice if we had this
2269         // information in a table.
2270         break;
2271       }
2272       default:
2273         break;
2274     }
2275     assert(stub == NULL || stub_contains(stub), "static call stub outside stub section");
2276   }
2277 }
2278 
2279 
2280 // -----------------------------------------------------------------------------
2281 // Printing operations
2282 
2283 void nmethod::print() const {
2284   ttyLocker ttyl;   // keep the following output all in one block
2285   print(tty);
2286 }
2287 
2288 void nmethod::print(outputStream* st) const {
2289   ResourceMark rm;
2290 
2291   st->print("Compiled method ");
2292 
2293   if (is_compiled_by_c1()) {
2294     st->print("(c1) ");
2295   } else if (is_compiled_by_c2()) {
2296     st->print("(c2) ");
2297   } else if (is_compiled_by_jvmci()) {
2298     st->print("(JVMCI) ");
2299   } else {
2300     st->print("(n/a) ");
2301   }
2302 
2303   print_on(tty, NULL);
2304 
2305   if (WizardMode) {
2306     st->print("((nmethod*) " INTPTR_FORMAT ") ", p2i(this));
2307     st->print(" for method " INTPTR_FORMAT , p2i(method()));
2308     st->print(" { ");
2309     st->print_cr("%s ", state());
2310     st->print_cr("}:");
2311   }
2312   if (size              () > 0) st->print_cr(" total in heap  [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
2313                                              p2i(this),
2314                                              p2i(this) + size(),
2315                                              size());
2316   if (relocation_size   () > 0) st->print_cr(" relocation     [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
2317                                              p2i(relocation_begin()),
2318                                              p2i(relocation_end()),
2319                                              relocation_size());
2320   if (consts_size       () > 0) st->print_cr(" constants      [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
2321                                              p2i(consts_begin()),
2322                                              p2i(consts_end()),
2323                                              consts_size());
2324   if (insts_size        () > 0) st->print_cr(" main code      [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
2325                                              p2i(insts_begin()),
2326                                              p2i(insts_end()),
2327                                              insts_size());
2328   if (stub_size         () > 0) st->print_cr(" stub code      [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
2329                                              p2i(stub_begin()),
2330                                              p2i(stub_end()),
2331                                              stub_size());
2332   if (oops_size         () > 0) st->print_cr(" oops           [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
2333                                              p2i(oops_begin()),
2334                                              p2i(oops_end()),
2335                                              oops_size());
2336   if (metadata_size     () > 0) st->print_cr(" metadata       [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
2337                                              p2i(metadata_begin()),
2338                                              p2i(metadata_end()),
2339                                              metadata_size());
2340   if (scopes_data_size  () > 0) st->print_cr(" scopes data    [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
2341                                              p2i(scopes_data_begin()),
2342                                              p2i(scopes_data_end()),
2343                                              scopes_data_size());
2344   if (scopes_pcs_size   () > 0) st->print_cr(" scopes pcs     [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
2345                                              p2i(scopes_pcs_begin()),
2346                                              p2i(scopes_pcs_end()),
2347                                              scopes_pcs_size());
2348   if (dependencies_size () > 0) st->print_cr(" dependencies   [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
2349                                              p2i(dependencies_begin()),
2350                                              p2i(dependencies_end()),
2351                                              dependencies_size());
2352   if (handler_table_size() > 0) st->print_cr(" handler table  [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
2353                                              p2i(handler_table_begin()),
2354                                              p2i(handler_table_end()),
2355                                              handler_table_size());
2356   if (nul_chk_table_size() > 0) st->print_cr(" nul chk table  [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
2357                                              p2i(nul_chk_table_begin()),
2358                                              p2i(nul_chk_table_end()),
2359                                              nul_chk_table_size());
2360 #if INCLUDE_JVMCI
2361   if (speculations_size () > 0) st->print_cr(" speculations   [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
2362                                              p2i(speculations_begin()),
2363                                              p2i(speculations_end()),
2364                                              speculations_size());
2365   if (jvmci_data_size   () > 0) st->print_cr(" JVMCI data     [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
2366                                              p2i(jvmci_data_begin()),
2367                                              p2i(jvmci_data_end()),
2368                                              jvmci_data_size());
2369 #endif
2370 }
2371 
2372 void nmethod::print_code() {
2373   HandleMark hm;
2374   ResourceMark m;
2375   ttyLocker ttyl;
2376   // Call the specialized decode method of this class.
2377   decode(tty);
2378 }
2379 
2380 #ifndef PRODUCT  // called InstanceKlass methods are available only then. Declared as PRODUCT_RETURN
2381 
2382 void nmethod::print_dependencies() {
2383   ResourceMark rm;
2384   ttyLocker ttyl;   // keep the following output all in one block
2385   tty->print_cr("Dependencies:");
2386   for (Dependencies::DepStream deps(this); deps.next(); ) {
2387     deps.print_dependency();
2388     Klass* ctxk = deps.context_type();
2389     if (ctxk != NULL) {
2390       if (ctxk->is_instance_klass() && InstanceKlass::cast(ctxk)->is_dependent_nmethod(this)) {
2391         tty->print_cr("   [nmethod<=klass]%s", ctxk->external_name());
2392       }
2393     }
2394     deps.log_dependency();  // put it into the xml log also
2395   }
2396 }
2397 #endif
2398 
2399 #if defined(SUPPORT_DATA_STRUCTS)
2400 
2401 // Print the oops from the underlying CodeBlob.
2402 void nmethod::print_oops(outputStream* st) {
2403   HandleMark hm;
2404   ResourceMark m;
2405   st->print("Oops:");
2406   if (oops_begin() < oops_end()) {
2407     st->cr();
2408     for (oop* p = oops_begin(); p < oops_end(); p++) {
2409       Disassembler::print_location((unsigned char*)p, (unsigned char*)oops_begin(), (unsigned char*)oops_end(), st, true, false);
2410       st->print(PTR_FORMAT " ", *((uintptr_t*)p));
2411       if (*p == Universe::non_oop_word()) {
2412         st->print_cr("NON_OOP");
2413         continue;  // skip non-oops
2414       }
2415       if (*p == NULL) {
2416         st->print_cr("NULL-oop");
2417         continue;  // skip non-oops
2418       }
2419       (*p)->print_value_on(st);
2420       st->cr();
2421     }
2422   } else {
2423     st->print_cr(" <list empty>");
2424   }
2425 }
2426 
2427 // Print metadata pool.
2428 void nmethod::print_metadata(outputStream* st) {
2429   HandleMark hm;
2430   ResourceMark m;
2431   st->print("Metadata:");
2432   if (metadata_begin() < metadata_end()) {
2433     st->cr();
2434     for (Metadata** p = metadata_begin(); p < metadata_end(); p++) {
2435       Disassembler::print_location((unsigned char*)p, (unsigned char*)metadata_begin(), (unsigned char*)metadata_end(), st, true, false);
2436       st->print(PTR_FORMAT " ", *((uintptr_t*)p));
2437       if (*p && *p != Universe::non_oop_word()) {
2438         (*p)->print_value_on(st);
2439       }
2440       st->cr();
2441     }
2442   } else {
2443     st->print_cr(" <list empty>");
2444   }
2445 }
2446 
2447 #ifndef PRODUCT  // ScopeDesc::print_on() is available only then. Declared as PRODUCT_RETURN
2448 void nmethod::print_scopes_on(outputStream* st) {
2449   // Find the first pc desc for all scopes in the code and print it.
2450   ResourceMark rm;
2451   st->print("scopes:");
2452   if (scopes_pcs_begin() < scopes_pcs_end()) {
2453     st->cr();
2454     for (PcDesc* p = scopes_pcs_begin(); p < scopes_pcs_end(); p++) {
2455       if (p->scope_decode_offset() == DebugInformationRecorder::serialized_null)
2456         continue;
2457 
2458       ScopeDesc* sd = scope_desc_at(p->real_pc(this));
2459       while (sd != NULL) {
2460         sd->print_on(st, p);  // print output ends with a newline
2461         sd = sd->sender();
2462       }
2463     }
2464   } else {
2465     st->print_cr(" <list empty>");
2466   }
2467 }
2468 #endif
2469 
2470 #ifndef PRODUCT  // RelocIterator does support printing only then.
2471 void nmethod::print_relocations() {
2472   ResourceMark m;       // in case methods get printed via the debugger
2473   tty->print_cr("relocations:");
2474   RelocIterator iter(this);
2475   iter.print();
2476 }
2477 #endif
2478 
2479 void nmethod::print_pcs_on(outputStream* st) {
2480   ResourceMark m;       // in case methods get printed via debugger
2481   st->print("pc-bytecode offsets:");
2482   if (scopes_pcs_begin() < scopes_pcs_end()) {
2483     st->cr();
2484     for (PcDesc* p = scopes_pcs_begin(); p < scopes_pcs_end(); p++) {
2485       p->print_on(st, this);  // print output ends with a newline
2486     }
2487   } else {
2488     st->print_cr(" <list empty>");
2489   }
2490 }
2491 
2492 void nmethod::print_handler_table() {
2493   ExceptionHandlerTable(this).print();
2494 }
2495 
2496 void nmethod::print_nul_chk_table() {
2497   ImplicitExceptionTable(this).print(code_begin());
2498 }
2499 
2500 void nmethod::print_recorded_oops() {
2501   const int n = oops_count();
2502   const int log_n = (n<10) ? 1 : (n<100) ? 2 : (n<1000) ? 3 : (n<10000) ? 4 : 6;
2503   tty->print("Recorded oops:");
2504   if (n > 0) {
2505     tty->cr();
2506     for (int i = 0; i < n; i++) {
2507       oop o = oop_at(i);
2508       tty->print("#%*d: " INTPTR_FORMAT " ", log_n, i, p2i(o));
2509       if (o == (oop)Universe::non_oop_word()) {
2510         tty->print("non-oop word");
2511       } else if (o == NULL) {
2512         tty->print("NULL-oop");
2513       } else {
2514         o->print_value_on(tty);
2515       }
2516       tty->cr();
2517     }
2518   } else {
2519     tty->print_cr(" <list empty>");
2520   }
2521 }
2522 
2523 void nmethod::print_recorded_metadata() {
2524   const int n = metadata_count();
2525   const int log_n = (n<10) ? 1 : (n<100) ? 2 : (n<1000) ? 3 : (n<10000) ? 4 : 6;
2526   tty->print("Recorded metadata:");
2527   if (n > 0) {
2528     tty->cr();
2529     for (int i = 0; i < n; i++) {
2530       Metadata* m = metadata_at(i);
2531       tty->print("#%*d: " INTPTR_FORMAT " ", log_n, i, p2i(m));
2532       if (m == (Metadata*)Universe::non_oop_word()) {
2533         tty->print("non-metadata word");
2534       } else if (m == NULL) {
2535         tty->print("NULL-oop");
2536       } else {
2537         Metadata::print_value_on_maybe_null(tty, m);
2538       }
2539       tty->cr();
2540     }
2541   } else {
2542     tty->print_cr(" <list empty>");
2543   }
2544 }
2545 #endif
2546 
2547 #if defined(SUPPORT_ASSEMBLY) || defined(SUPPORT_ABSTRACT_ASSEMBLY)
2548 
2549 void nmethod::print_constant_pool(outputStream* st) {
2550   //-----------------------------------
2551   //---<  Print the constant pool  >---
2552   //-----------------------------------
2553   int consts_size = this->consts_size();
2554   if ( consts_size > 0 ) {
2555     unsigned char* cstart = this->consts_begin();
2556     unsigned char* cp     = cstart;
2557     unsigned char* cend   = cp + consts_size;
2558     unsigned int   bytes_per_line = 4;
2559     unsigned int   CP_alignment   = 8;
2560     unsigned int   n;
2561 
2562     st->cr();
2563 
2564     //---<  print CP header to make clear what's printed  >---
2565     if( ((uintptr_t)cp&(CP_alignment-1)) == 0 ) {
2566       n = bytes_per_line;
2567       st->print_cr("[Constant Pool]");
2568       Disassembler::print_location(cp, cstart, cend, st, true, true);
2569       Disassembler::print_hexdata(cp, n, st, true);
2570       st->cr();
2571     } else {
2572       n = (uintptr_t)cp&(bytes_per_line-1);
2573       st->print_cr("[Constant Pool (unaligned)]");
2574     }
2575 
2576     //---<  print CP contents, bytes_per_line at a time  >---
2577     while (cp < cend) {
2578       Disassembler::print_location(cp, cstart, cend, st, true, false);
2579       Disassembler::print_hexdata(cp, n, st, false);
2580       cp += n;
2581       n   = bytes_per_line;
2582       st->cr();
2583     }
2584 
2585     //---<  Show potential alignment gap between constant pool and code  >---
2586     cend = code_begin();
2587     if( cp < cend ) {
2588       n = 4;
2589       st->print_cr("[Code entry alignment]");
2590       while (cp < cend) {
2591         Disassembler::print_location(cp, cstart, cend, st, false, false);
2592         cp += n;
2593         st->cr();
2594       }
2595     }
2596   } else {
2597     st->print_cr("[Constant Pool (empty)]");
2598   }
2599   st->cr();
2600 }
2601 
2602 #endif
2603 
2604 // Disassemble this nmethod.
2605 // Print additional debug information, if requested. This could be code
2606 // comments, block comments, profiling counters, etc.
2607 // The undisassembled format is useful no disassembler library is available.
2608 // The resulting hex dump (with markers) can be disassembled later, or on
2609 // another system, when/where a disassembler library is available.
2610 void nmethod::decode2(outputStream* ost) const {
2611 
2612   // Called from frame::back_trace_with_decode without ResourceMark.
2613   ResourceMark rm;
2614 
2615   // Make sure we have a valid stream to print on.
2616   outputStream* st = ost ? ost : tty;
2617 
2618 #if defined(SUPPORT_ABSTRACT_ASSEMBLY) && ! defined(SUPPORT_ASSEMBLY)
2619   const bool use_compressed_format    = true;
2620   const bool compressed_with_comments = use_compressed_format && (AbstractDisassembler::show_comment() ||
2621                                                                   AbstractDisassembler::show_block_comment());
2622 #else
2623   const bool use_compressed_format    = Disassembler::is_abstract();
2624   const bool compressed_with_comments = use_compressed_format && (AbstractDisassembler::show_comment() ||
2625                                                                   AbstractDisassembler::show_block_comment());
2626 #endif
2627 
2628   st->cr();
2629   this->print(st);
2630   st->cr();
2631 
2632 #if defined(SUPPORT_ASSEMBLY)
2633   //----------------------------------
2634   //---<  Print real disassembly  >---
2635   //----------------------------------
2636   if (! use_compressed_format) {
2637     Disassembler::decode(const_cast<nmethod*>(this), st);
2638     return;
2639   }
2640 #endif
2641 
2642 #if defined(SUPPORT_ABSTRACT_ASSEMBLY)
2643 
2644   // Compressed undisassembled disassembly format.
2645   // The following stati are defined/supported:
2646   //   = 0 - currently at bol() position, nothing printed yet on current line.
2647   //   = 1 - currently at position after print_location().
2648   //   > 1 - in the midst of printing instruction stream bytes.
2649   int        compressed_format_idx    = 0;
2650   int        code_comment_column      = 0;
2651   const int  instr_maxlen             = Assembler::instr_maxlen();
2652   const uint tabspacing               = 8;
2653   unsigned char* start = this->code_begin();
2654   unsigned char* p     = this->code_begin();
2655   unsigned char* end   = this->code_end();
2656   unsigned char* pss   = p; // start of a code section (used for offsets)
2657 
2658   if ((start == NULL) || (end == NULL)) {
2659     st->print_cr("PrintAssembly not possible due to uninitialized section pointers");
2660     return;
2661   }
2662 #endif
2663 
2664 #if defined(SUPPORT_ABSTRACT_ASSEMBLY)
2665   //---<  plain abstract disassembly, no comments or anything, just section headers  >---
2666   if (use_compressed_format && ! compressed_with_comments) {
2667     const_cast<nmethod*>(this)->print_constant_pool(st);
2668 
2669     //---<  Open the output (Marker for post-mortem disassembler)  >---
2670     st->print_cr("[MachCode]");
2671     const char* header = NULL;
2672     address p0 = p;
2673     while (p < end) {
2674       address pp = p;
2675       while ((p < end) && (header == NULL)) {
2676         header = nmethod_section_label(p);
2677         pp  = p;
2678         p  += Assembler::instr_len(p);
2679       }
2680       if (pp > p0) {
2681         AbstractDisassembler::decode_range_abstract(p0, pp, start, end, st, Assembler::instr_maxlen());
2682         p0 = pp;
2683         p  = pp;
2684         header = NULL;
2685       } else if (header != NULL) {
2686         st->bol();
2687         st->print_cr("%s", header);
2688         header = NULL;
2689       }
2690     }
2691     //---<  Close the output (Marker for post-mortem disassembler)  >---
2692     st->bol();
2693     st->print_cr("[/MachCode]");
2694     return;
2695   }
2696 #endif
2697 
2698 #if defined(SUPPORT_ABSTRACT_ASSEMBLY)
2699   //---<  abstract disassembly with comments and section headers merged in  >---
2700   if (compressed_with_comments) {
2701     const_cast<nmethod*>(this)->print_constant_pool(st);
2702 
2703     //---<  Open the output (Marker for post-mortem disassembler)  >---
2704     st->print_cr("[MachCode]");
2705     while ((p < end) && (p != NULL)) {
2706       const int instruction_size_in_bytes = Assembler::instr_len(p);
2707 
2708       //---<  Block comments for nmethod. Interrupts instruction stream, if any.  >---
2709       // Outputs a bol() before and a cr() after, but only if a comment is printed.
2710       // Prints nmethod_section_label as well.
2711       if (AbstractDisassembler::show_block_comment()) {
2712         print_block_comment(st, p);
2713         if (st->position() == 0) {
2714           compressed_format_idx = 0;
2715         }
2716       }
2717 
2718       //---<  New location information after line break  >---
2719       if (compressed_format_idx == 0) {
2720         code_comment_column   = Disassembler::print_location(p, pss, end, st, false, false);
2721         compressed_format_idx = 1;
2722       }
2723 
2724       //---<  Code comment for current instruction. Address range [p..(p+len))  >---
2725       unsigned char* p_end = p + (ssize_t)instruction_size_in_bytes;
2726       S390_ONLY(if (p_end > end) p_end = end;) // avoid getting past the end
2727 
2728       if (AbstractDisassembler::show_comment() && const_cast<nmethod*>(this)->has_code_comment(p, p_end)) {
2729         //---<  interrupt instruction byte stream for code comment  >---
2730         if (compressed_format_idx > 1) {
2731           st->cr();  // interrupt byte stream
2732           st->cr();  // add an empty line
2733           code_comment_column = Disassembler::print_location(p, pss, end, st, false, false);
2734         }
2735         const_cast<nmethod*>(this)->print_code_comment_on(st, code_comment_column, p, p_end );
2736         st->bol();
2737         compressed_format_idx = 0;
2738       }
2739 
2740       //---<  New location information after line break  >---
2741       if (compressed_format_idx == 0) {
2742         code_comment_column   = Disassembler::print_location(p, pss, end, st, false, false);
2743         compressed_format_idx = 1;
2744       }
2745 
2746       //---<  Nicely align instructions for readability  >---
2747       if (compressed_format_idx > 1) {
2748         Disassembler::print_delimiter(st);
2749       }
2750 
2751       //---<  Now, finally, print the actual instruction bytes  >---
2752       unsigned char* p0 = p;
2753       p = Disassembler::decode_instruction_abstract(p, st, instruction_size_in_bytes, instr_maxlen);
2754       compressed_format_idx += p - p0;
2755 
2756       if (Disassembler::start_newline(compressed_format_idx-1)) {
2757         st->cr();
2758         compressed_format_idx = 0;
2759       }
2760     }
2761     //---<  Close the output (Marker for post-mortem disassembler)  >---
2762     st->bol();
2763     st->print_cr("[/MachCode]");
2764     return;
2765   }
2766 #endif
2767 }
2768 
2769 #if defined(SUPPORT_ASSEMBLY) || defined(SUPPORT_ABSTRACT_ASSEMBLY)
2770 
2771 const char* nmethod::reloc_string_for(u_char* begin, u_char* end) {
2772   RelocIterator iter(this, begin, end);
2773   bool have_one = false;
2774   while (iter.next()) {
2775     have_one = true;
2776     switch (iter.type()) {
2777         case relocInfo::none:                  return "no_reloc";
2778         case relocInfo::oop_type: {
2779           // Get a non-resizable resource-allocated stringStream.
2780           // Our callees make use of (nested) ResourceMarks.
2781           stringStream st(NEW_RESOURCE_ARRAY(char, 1024), 1024);
2782           oop_Relocation* r = iter.oop_reloc();
2783           oop obj = r->oop_value();
2784           st.print("oop(");
2785           if (obj == NULL) st.print("NULL");
2786           else obj->print_value_on(&st);
2787           st.print(")");
2788           return st.as_string();
2789         }
2790         case relocInfo::metadata_type: {
2791           stringStream st;
2792           metadata_Relocation* r = iter.metadata_reloc();
2793           Metadata* obj = r->metadata_value();
2794           st.print("metadata(");
2795           if (obj == NULL) st.print("NULL");
2796           else obj->print_value_on(&st);
2797           st.print(")");
2798           return st.as_string();
2799         }
2800         case relocInfo::runtime_call_type:
2801         case relocInfo::runtime_call_w_cp_type: {
2802           stringStream st;
2803           st.print("runtime_call");
2804           CallRelocation* r = (CallRelocation*)iter.reloc();
2805           address dest = r->destination();
2806           CodeBlob* cb = CodeCache::find_blob(dest);
2807           if (cb != NULL) {
2808             st.print(" %s", cb->name());
2809           } else {
2810             ResourceMark rm;
2811             const int buflen = 1024;
2812             char* buf = NEW_RESOURCE_ARRAY(char, buflen);
2813             int offset;
2814             if (os::dll_address_to_function_name(dest, buf, buflen, &offset)) {
2815               st.print(" %s", buf);
2816               if (offset != 0) {
2817                 st.print("+%d", offset);
2818               }
2819             }
2820           }
2821           return st.as_string();
2822         }
2823         case relocInfo::virtual_call_type: {
2824           stringStream st;
2825           st.print_raw("virtual_call");
2826           virtual_call_Relocation* r = iter.virtual_call_reloc();
2827           Method* m = r->method_value();
2828           if (m != NULL) {
2829             assert(m->is_method(), "");
2830             m->print_short_name(&st);
2831           }
2832           return st.as_string();
2833         }
2834         case relocInfo::opt_virtual_call_type: {
2835           stringStream st;
2836           st.print_raw("optimized virtual_call");
2837           opt_virtual_call_Relocation* r = iter.opt_virtual_call_reloc();
2838           Method* m = r->method_value();
2839           if (m != NULL) {
2840             assert(m->is_method(), "");
2841             m->print_short_name(&st);
2842           }
2843           return st.as_string();
2844         }
2845         case relocInfo::static_call_type: {
2846           stringStream st;
2847           st.print_raw("static_call");
2848           static_call_Relocation* r = iter.static_call_reloc();
2849           Method* m = r->method_value();
2850           if (m != NULL) {
2851             assert(m->is_method(), "");
2852             m->print_short_name(&st);
2853           }
2854           return st.as_string();
2855         }
2856         case relocInfo::static_stub_type:      return "static_stub";
2857         case relocInfo::external_word_type:    return "external_word";
2858         case relocInfo::internal_word_type:    return "internal_word";
2859         case relocInfo::section_word_type:     return "section_word";
2860         case relocInfo::poll_type:             return "poll";
2861         case relocInfo::poll_return_type:      return "poll_return";
2862         case relocInfo::trampoline_stub_type:  return "trampoline_stub";
2863         case relocInfo::type_mask:             return "type_bit_mask";
2864 
2865         default:
2866           break;
2867     }
2868   }
2869   return have_one ? "other" : NULL;
2870 }
2871 
2872 // Return a the last scope in (begin..end]
2873 ScopeDesc* nmethod::scope_desc_in(address begin, address end) {
2874   PcDesc* p = pc_desc_near(begin+1);
2875   if (p != NULL && p->real_pc(this) <= end) {
2876     return new ScopeDesc(this, p->scope_decode_offset(),
2877                          p->obj_decode_offset(), p->should_reexecute(), p->rethrow_exception(),
2878                          p->return_oop());
2879   }
2880   return NULL;
2881 }
2882 
2883 const char* nmethod::nmethod_section_label(address pos) const {
2884   const char* label = NULL;
2885   if (pos == code_begin())                                              label = "[Instructions begin]";
2886   if (pos == entry_point())                                             label = "[Entry Point]";
2887   if (pos == verified_entry_point())                                    label = "[Verified Entry Point]";
2888   if (has_method_handle_invokes() && (pos == deopt_mh_handler_begin())) label = "[Deopt MH Handler Code]";
2889   if (pos == consts_begin() && pos != insts_begin())                    label = "[Constants]";
2890   // Check stub_code before checking exception_handler or deopt_handler.
2891   if (pos == this->stub_begin())                                        label = "[Stub Code]";
2892   if (JVMCI_ONLY(_exception_offset >= 0 &&) pos == exception_begin())           label = "[Exception Handler]";
2893   if (JVMCI_ONLY(_deopt_handler_begin != NULL &&) pos == deopt_handler_begin()) label = "[Deopt Handler Code]";
2894   return label;
2895 }
2896 
2897 void nmethod::print_nmethod_labels(outputStream* stream, address block_begin, bool print_section_labels) const {
2898   if (print_section_labels) {
2899     const char* label = nmethod_section_label(block_begin);
2900     if (label != NULL) {
2901       stream->bol();
2902       stream->print_cr("%s", label);
2903     }
2904   }
2905 
2906   if (block_begin == entry_point()) {
2907     methodHandle m = method();
2908     if (m.not_null()) {
2909       stream->print("  # ");
2910       m->print_value_on(stream);
2911       stream->cr();
2912     }
2913     if (m.not_null() && !is_osr_method()) {
2914       ResourceMark rm;
2915       int sizeargs = m->size_of_parameters();
2916       BasicType* sig_bt = NEW_RESOURCE_ARRAY(BasicType, sizeargs);
2917       VMRegPair* regs   = NEW_RESOURCE_ARRAY(VMRegPair, sizeargs);
2918       {
2919         int sig_index = 0;
2920         if (!m->is_static())
2921           sig_bt[sig_index++] = T_OBJECT; // 'this'
2922         for (SignatureStream ss(m->signature()); !ss.at_return_type(); ss.next()) {
2923           BasicType t = ss.type();
2924           sig_bt[sig_index++] = t;
2925           if (type2size[t] == 2) {
2926             sig_bt[sig_index++] = T_VOID;
2927           } else {
2928             assert(type2size[t] == 1, "size is 1 or 2");
2929           }
2930         }
2931         assert(sig_index == sizeargs, "");
2932       }
2933       const char* spname = "sp"; // make arch-specific?
2934       intptr_t out_preserve = SharedRuntime::java_calling_convention(sig_bt, regs, sizeargs, false);
2935       int stack_slot_offset = this->frame_size() * wordSize;
2936       int tab1 = 14, tab2 = 24;
2937       int sig_index = 0;
2938       int arg_index = (m->is_static() ? 0 : -1);
2939       bool did_old_sp = false;
2940       for (SignatureStream ss(m->signature()); !ss.at_return_type(); ) {
2941         bool at_this = (arg_index == -1);
2942         bool at_old_sp = false;
2943         BasicType t = (at_this ? T_OBJECT : ss.type());
2944         assert(t == sig_bt[sig_index], "sigs in sync");
2945         if (at_this)
2946           stream->print("  # this: ");
2947         else
2948           stream->print("  # parm%d: ", arg_index);
2949         stream->move_to(tab1);
2950         VMReg fst = regs[sig_index].first();
2951         VMReg snd = regs[sig_index].second();
2952         if (fst->is_reg()) {
2953           stream->print("%s", fst->name());
2954           if (snd->is_valid())  {
2955             stream->print(":%s", snd->name());
2956           }
2957         } else if (fst->is_stack()) {
2958           int offset = fst->reg2stack() * VMRegImpl::stack_slot_size + stack_slot_offset;
2959           if (offset == stack_slot_offset)  at_old_sp = true;
2960           stream->print("[%s+0x%x]", spname, offset);
2961         } else {
2962           stream->print("reg%d:%d??", (int)(intptr_t)fst, (int)(intptr_t)snd);
2963         }
2964         stream->print(" ");
2965         stream->move_to(tab2);
2966         stream->print("= ");
2967         if (at_this) {
2968           m->method_holder()->print_value_on(stream);
2969         } else {
2970           bool did_name = false;
2971           if (!at_this && ss.is_object()) {
2972             Symbol* name = ss.as_symbol_or_null();
2973             if (name != NULL) {
2974               name->print_value_on(stream);
2975               did_name = true;
2976             }
2977           }
2978           if (!did_name)
2979             stream->print("%s", type2name(t));
2980         }
2981         if (at_old_sp) {
2982           stream->print("  (%s of caller)", spname);
2983           did_old_sp = true;
2984         }
2985         stream->cr();
2986         sig_index += type2size[t];
2987         arg_index += 1;
2988         if (!at_this)  ss.next();
2989       }
2990       if (!did_old_sp) {
2991         stream->print("  # ");
2992         stream->move_to(tab1);
2993         stream->print("[%s+0x%x]", spname, stack_slot_offset);
2994         stream->print("  (%s of caller)", spname);
2995         stream->cr();
2996       }
2997     }
2998   }
2999 }
3000 
3001 // Returns whether this nmethod has code comments.
3002 bool nmethod::has_code_comment(address begin, address end) {
3003   // scopes?
3004   ScopeDesc* sd  = scope_desc_in(begin, end);
3005   if (sd != NULL) return true;
3006 
3007   // relocations?
3008   const char* str = reloc_string_for(begin, end);
3009   if (str != NULL) return true;
3010 
3011   // implicit exceptions?
3012   int cont_offset = ImplicitExceptionTable(this).continuation_offset(begin - code_begin());
3013   if (cont_offset != 0) return true;
3014 
3015   return false;
3016 }
3017 
3018 void nmethod::print_code_comment_on(outputStream* st, int column, address begin, address end) {
3019   ImplicitExceptionTable implicit_table(this);
3020   int pc_offset = begin - code_begin();
3021   int cont_offset = implicit_table.continuation_offset(pc_offset);
3022   bool oop_map_required = false;
3023   if (cont_offset != 0) {
3024     st->move_to(column, 6, 0);
3025     if (pc_offset == cont_offset) {
3026       st->print("; implicit exception: deoptimizes");
3027       oop_map_required = true;
3028     } else {
3029       st->print("; implicit exception: dispatches to " INTPTR_FORMAT, p2i(code_begin() + cont_offset));
3030     }
3031   }
3032 
3033   // Find an oopmap in (begin, end].  We use the odd half-closed
3034   // interval so that oop maps and scope descs which are tied to the
3035   // byte after a call are printed with the call itself.  OopMaps
3036   // associated with implicit exceptions are printed with the implicit
3037   // instruction.
3038   address base = code_begin();
3039   ImmutableOopMapSet* oms = oop_maps();
3040   if (oms != NULL) {
3041     for (int i = 0, imax = oms->count(); i < imax; i++) {
3042       const ImmutableOopMapPair* pair = oms->pair_at(i);
3043       const ImmutableOopMap* om = pair->get_from(oms);
3044       address pc = base + pair->pc_offset();
3045       if (pc >= begin) {
3046 #if INCLUDE_JVMCI
3047         bool is_implicit_deopt = implicit_table.continuation_offset(pair->pc_offset()) == (uint) pair->pc_offset();
3048 #else
3049         bool is_implicit_deopt = false;
3050 #endif
3051         if (is_implicit_deopt ? pc == begin : pc > begin && pc <= end) {
3052           st->move_to(column, 6, 0);
3053           st->print("; ");
3054           om->print_on(st);
3055           oop_map_required = false;
3056         }
3057       }
3058       if (pc > end) {
3059         break;
3060       }
3061     }
3062   }
3063   assert(!oop_map_required, "missed oopmap");
3064 
3065   // Print any debug info present at this pc.
3066   ScopeDesc* sd  = scope_desc_in(begin, end);
3067   if (sd != NULL) {
3068     st->move_to(column, 6, 0);
3069     if (sd->bci() == SynchronizationEntryBCI) {
3070       st->print(";*synchronization entry");
3071     } else if (sd->bci() == AfterBci) {
3072       st->print(";* method exit (unlocked if synchronized)");
3073     } else if (sd->bci() == UnwindBci) {
3074       st->print(";* unwind (locked if synchronized)");
3075     } else if (sd->bci() == AfterExceptionBci) {
3076       st->print(";* unwind (unlocked if synchronized)");
3077     } else if (sd->bci() == UnknownBci) {
3078       st->print(";* unknown");
3079     } else if (sd->bci() == InvalidFrameStateBci) {
3080       st->print(";* invalid frame state");
3081     } else {
3082       if (sd->method() == NULL) {
3083         st->print("method is NULL");
3084       } else if (sd->method()->is_native()) {
3085         st->print("method is native");
3086       } else {
3087         Bytecodes::Code bc = sd->method()->java_code_at(sd->bci());
3088         st->print(";*%s", Bytecodes::name(bc));
3089         switch (bc) {
3090         case Bytecodes::_invokevirtual:
3091         case Bytecodes::_invokespecial:
3092         case Bytecodes::_invokestatic:
3093         case Bytecodes::_invokeinterface:
3094           {
3095             Bytecode_invoke invoke(sd->method(), sd->bci());
3096             st->print(" ");
3097             if (invoke.name() != NULL)
3098               invoke.name()->print_symbol_on(st);
3099             else
3100               st->print("<UNKNOWN>");
3101             break;
3102           }
3103         case Bytecodes::_getfield:
3104         case Bytecodes::_putfield:
3105         case Bytecodes::_getstatic:
3106         case Bytecodes::_putstatic:
3107           {
3108             Bytecode_field field(sd->method(), sd->bci());
3109             st->print(" ");
3110             if (field.name() != NULL)
3111               field.name()->print_symbol_on(st);
3112             else
3113               st->print("<UNKNOWN>");
3114           }
3115         default:
3116           break;
3117         }
3118       }
3119       st->print(" {reexecute=%d rethrow=%d return_oop=%d}", sd->should_reexecute(), sd->rethrow_exception(), sd->return_oop());
3120     }
3121 
3122     // Print all scopes
3123     for (;sd != NULL; sd = sd->sender()) {
3124       st->move_to(column, 6, 0);
3125       st->print("; -");
3126       if (sd->should_reexecute()) {
3127         st->print(" (reexecute)");
3128       }
3129       if (sd->method() == NULL) {
3130         st->print("method is NULL");
3131       } else {
3132         sd->method()->print_short_name(st);
3133       }
3134       int lineno = sd->method()->line_number_from_bci(sd->bci());
3135       if (lineno != -1) {
3136         st->print("@%d (line %d)", sd->bci(), lineno);
3137       } else {
3138         st->print("@%d", sd->bci());
3139       }
3140       st->cr();
3141     }
3142   }
3143 
3144   // Print relocation information
3145   // Prevent memory leak: allocating without ResourceMark.
3146   ResourceMark rm;
3147   const char* str = reloc_string_for(begin, end);
3148   if (str != NULL) {
3149     if (sd != NULL) st->cr();
3150     st->move_to(column, 6, 0);
3151     st->print(";   {%s}", str);
3152   }
3153 }
3154 
3155 #endif
3156 
3157 class DirectNativeCallWrapper: public NativeCallWrapper {
3158 private:
3159   NativeCall* _call;
3160 
3161 public:
3162   DirectNativeCallWrapper(NativeCall* call) : _call(call) {}
3163 
3164   virtual address destination() const { return _call->destination(); }
3165   virtual address instruction_address() const { return _call->instruction_address(); }
3166   virtual address next_instruction_address() const { return _call->next_instruction_address(); }
3167   virtual address return_address() const { return _call->return_address(); }
3168 
3169   virtual address get_resolve_call_stub(bool is_optimized) const {
3170     if (is_optimized) {
3171       return SharedRuntime::get_resolve_opt_virtual_call_stub();
3172     }
3173     return SharedRuntime::get_resolve_virtual_call_stub();
3174   }
3175 
3176   virtual void set_destination_mt_safe(address dest) {
3177 #if INCLUDE_AOT
3178     if (UseAOT) {
3179       CodeBlob* callee = CodeCache::find_blob(dest);
3180       CompiledMethod* cm = callee->as_compiled_method_or_null();
3181       if (cm != NULL && cm->is_far_code()) {
3182         // Temporary fix, see JDK-8143106
3183         CompiledDirectStaticCall* csc = CompiledDirectStaticCall::at(instruction_address());
3184         csc->set_to_far(methodHandle(cm->method()), dest);
3185         return;
3186       }
3187     }
3188 #endif
3189     _call->set_destination_mt_safe(dest);
3190   }
3191 
3192   virtual void set_to_interpreted(const methodHandle& method, CompiledICInfo& info) {
3193     CompiledDirectStaticCall* csc = CompiledDirectStaticCall::at(instruction_address());
3194 #if INCLUDE_AOT
3195     if (info.to_aot()) {
3196       csc->set_to_far(method, info.entry());
3197     } else
3198 #endif
3199     {
3200       csc->set_to_interpreted(method, info.entry());
3201     }
3202   }
3203 
3204   virtual void verify() const {
3205     // make sure code pattern is actually a call imm32 instruction
3206     _call->verify();
3207     _call->verify_alignment();
3208   }
3209 
3210   virtual void verify_resolve_call(address dest) const {
3211     CodeBlob* db = CodeCache::find_blob_unsafe(dest);
3212     assert(db != NULL && !db->is_adapter_blob(), "must use stub!");
3213   }
3214 
3215   virtual bool is_call_to_interpreted(address dest) const {
3216     CodeBlob* cb = CodeCache::find_blob(_call->instruction_address());
3217     return cb->contains(dest);
3218   }
3219 
3220   virtual bool is_safe_for_patching() const { return false; }
3221 
3222   virtual NativeInstruction* get_load_instruction(virtual_call_Relocation* r) const {
3223     return nativeMovConstReg_at(r->cached_value());
3224   }
3225 
3226   virtual void *get_data(NativeInstruction* instruction) const {
3227     return (void*)((NativeMovConstReg*) instruction)->data();
3228   }
3229 
3230   virtual void set_data(NativeInstruction* instruction, intptr_t data) {
3231     ((NativeMovConstReg*) instruction)->set_data(data);
3232   }
3233 };
3234 
3235 NativeCallWrapper* nmethod::call_wrapper_at(address call) const {
3236   return new DirectNativeCallWrapper((NativeCall*) call);
3237 }
3238 
3239 NativeCallWrapper* nmethod::call_wrapper_before(address return_pc) const {
3240   return new DirectNativeCallWrapper(nativeCall_before(return_pc));
3241 }
3242 
3243 address nmethod::call_instruction_address(address pc) const {
3244   if (NativeCall::is_call_before(pc)) {
3245     NativeCall *ncall = nativeCall_before(pc);
3246     return ncall->instruction_address();
3247   }
3248   return NULL;
3249 }
3250 
3251 CompiledStaticCall* nmethod::compiledStaticCall_at(Relocation* call_site) const {
3252   return CompiledDirectStaticCall::at(call_site);
3253 }
3254 
3255 CompiledStaticCall* nmethod::compiledStaticCall_at(address call_site) const {
3256   return CompiledDirectStaticCall::at(call_site);
3257 }
3258 
3259 CompiledStaticCall* nmethod::compiledStaticCall_before(address return_addr) const {
3260   return CompiledDirectStaticCall::before(return_addr);
3261 }
3262 
3263 #if defined(SUPPORT_DATA_STRUCTS)
3264 void nmethod::print_value_on(outputStream* st) const {
3265   st->print("nmethod");
3266   print_on(st, NULL);
3267 }
3268 #endif
3269 
3270 #ifndef PRODUCT
3271 
3272 void nmethod::print_calls(outputStream* st) {
3273   RelocIterator iter(this);
3274   while (iter.next()) {
3275     switch (iter.type()) {
3276     case relocInfo::virtual_call_type:
3277     case relocInfo::opt_virtual_call_type: {
3278       CompiledICLocker ml_verify(this);
3279       CompiledIC_at(&iter)->print();
3280       break;
3281     }
3282     case relocInfo::static_call_type:
3283       st->print_cr("Static call at " INTPTR_FORMAT, p2i(iter.reloc()->addr()));
3284       CompiledDirectStaticCall::at(iter.reloc())->print();
3285       break;
3286     default:
3287       break;
3288     }
3289   }
3290 }
3291 
3292 void nmethod::print_statistics() {
3293   ttyLocker ttyl;
3294   if (xtty != NULL)  xtty->head("statistics type='nmethod'");
3295   native_nmethod_stats.print_native_nmethod_stats();
3296 #ifdef COMPILER1
3297   c1_java_nmethod_stats.print_nmethod_stats("C1");
3298 #endif
3299 #ifdef COMPILER2
3300   c2_java_nmethod_stats.print_nmethod_stats("C2");
3301 #endif
3302 #if INCLUDE_JVMCI
3303   jvmci_java_nmethod_stats.print_nmethod_stats("JVMCI");
3304 #endif
3305   unknown_java_nmethod_stats.print_nmethod_stats("Unknown");
3306   DebugInformationRecorder::print_statistics();
3307 #ifndef PRODUCT
3308   pc_nmethod_stats.print_pc_stats();
3309 #endif
3310   Dependencies::print_statistics();
3311   if (xtty != NULL)  xtty->tail("statistics");
3312 }
3313 
3314 #endif // !PRODUCT
3315 
3316 #if INCLUDE_JVMCI
3317 void nmethod::update_speculation(JavaThread* thread) {
3318   jlong speculation = thread->pending_failed_speculation();
3319   if (speculation != 0) {
3320     guarantee(jvmci_nmethod_data() != NULL, "failed speculation in nmethod without failed speculation list");
3321     jvmci_nmethod_data()->add_failed_speculation(this, speculation);
3322     thread->set_pending_failed_speculation(0);
3323   }
3324 }
3325 
3326 const char* nmethod::jvmci_name() {
3327   if (jvmci_nmethod_data() != NULL) {
3328     return jvmci_nmethod_data()->name();
3329   }
3330   return NULL;
3331 }
3332 #endif