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