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