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