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