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