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