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