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