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