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