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