rev 11647 : 8161258: Simplify including platform files.
Summary: Include patform files with macros cpu_header() etc. Do various cleanups of macro usages. Remove _64/_32 from adlc generated files and platform .hpp files. Merge stubRoutines_x86*.hpp. Remove empty mutex_<os>* files.
Reviewed-by: dholmes, coleenp, kbarrett

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