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