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