src/share/vm/code/nmethod.cpp
Index Unified diffs Context diffs Sdiffs Wdiffs Patch New Old Previous File Next File hotspot Sdiff src/share/vm/code

src/share/vm/code/nmethod.cpp

Print this page




   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #include "precompiled.hpp"
  26 #include "code/codeCache.hpp"
  27 #include "code/compiledIC.hpp"
  28 #include "code/dependencies.hpp"

  29 #include "code/nmethod.hpp"
  30 #include "code/scopeDesc.hpp"
  31 #include "compiler/abstractCompiler.hpp"
  32 #include "compiler/compileBroker.hpp"
  33 #include "compiler/compileLog.hpp"
  34 #include "compiler/compilerOracle.hpp"
  35 #include "compiler/disassembler.hpp"
  36 #include "interpreter/bytecode.hpp"
  37 #include "oops/methodData.hpp"
  38 #include "oops/oop.inline.hpp"
  39 #include "prims/jvmtiRedefineClassesTrace.hpp"
  40 #include "prims/jvmtiImpl.hpp"
  41 #include "runtime/atomic.inline.hpp"
  42 #include "runtime/orderAccess.inline.hpp"
  43 #include "runtime/sharedRuntime.hpp"
  44 #include "runtime/sweeper.hpp"
  45 #include "utilities/resourceHash.hpp"
  46 #include "utilities/dtrace.hpp"
  47 #include "utilities/events.hpp"
  48 #include "utilities/xmlstream.hpp"















  49 #ifdef SHARK
  50 #include "shark/sharkCompiler.hpp"
  51 #endif



  52 
  53 PRAGMA_FORMAT_MUTE_WARNINGS_FOR_GCC
  54 
  55 unsigned char nmethod::_global_unloading_clock = 0;
  56 
  57 #ifdef DTRACE_ENABLED
  58 
  59 // Only bother with this argument setup if dtrace is available
  60 
  61 #define DTRACE_METHOD_UNLOAD_PROBE(method)                                \
  62   {                                                                       \
  63     Method* m = (method);                                                 \
  64     if (m != NULL) {                                                      \
  65       Symbol* klass_name = m->klass_name();                               \
  66       Symbol* name = m->name();                                           \
  67       Symbol* signature = m->signature();                                 \
  68       HOTSPOT_COMPILED_METHOD_UNLOAD(                                     \
  69         (char *) klass_name->bytes(), klass_name->utf8_length(),                   \
  70         (char *) name->bytes(), name->utf8_length(),                               \
  71         (char *) signature->bytes(), signature->utf8_length());                    \
  72     }                                                                     \
  73   }
  74 
  75 #else //  ndef DTRACE_ENABLED
  76 
  77 #define DTRACE_METHOD_UNLOAD_PROBE(method)
  78 
  79 #endif
  80 
  81 bool nmethod::is_compiled_by_c1() const {
  82   if (compiler() == NULL) {
  83     return false;
  84   }
  85   return compiler()->is_c1();
  86 }





  87 bool nmethod::is_compiled_by_c2() const {
  88   if (compiler() == NULL) {
  89     return false;
  90   }
  91   return compiler()->is_c2();
  92 }
  93 bool nmethod::is_compiled_by_shark() const {
  94   if (compiler() == NULL) {
  95     return false;
  96   }
  97   return compiler()->is_shark();
  98 }
  99 
 100 
 101 
 102 //---------------------------------------------------------------------------------
 103 // NMethod statistics
 104 // They are printed under various flags, including:
 105 //   PrintC1Statistics, PrintOptoStatistics, LogVMOutput, and LogCompilation.
 106 // (In the latter two cases, they like other stats are printed to the log only.)
 107 
 108 #ifndef PRODUCT
 109 // These variables are put into one block to reduce relocations
 110 // and make it simpler to print from the debugger.
 111 static
 112 struct nmethod_stats_struct {
 113   int nmethod_count;
 114   int total_size;
 115   int relocation_size;
 116   int consts_size;
 117   int insts_size;
 118   int stub_size;
 119   int scopes_data_size;
 120   int scopes_pcs_size;
 121   int dependencies_size;
 122   int handler_table_size;
 123   int nul_chk_table_size;
 124   int oops_size;

 125 
 126   void note_nmethod(nmethod* nm) {
 127     nmethod_count += 1;
 128     total_size          += nm->size();
 129     relocation_size     += nm->relocation_size();
 130     consts_size         += nm->consts_size();
 131     insts_size          += nm->insts_size();
 132     stub_size           += nm->stub_size();
 133     oops_size           += nm->oops_size();

 134     scopes_data_size    += nm->scopes_data_size();
 135     scopes_pcs_size     += nm->scopes_pcs_size();
 136     dependencies_size   += nm->dependencies_size();
 137     handler_table_size  += nm->handler_table_size();
 138     nul_chk_table_size  += nm->nul_chk_table_size();
 139   }
 140   void print_nmethod_stats() {
 141     if (nmethod_count == 0)  return;
 142     tty->print_cr("Statistics for %d bytecoded nmethods:", nmethod_count);
 143     if (total_size != 0)          tty->print_cr(" total in heap  = %d", total_size);

 144     if (relocation_size != 0)     tty->print_cr(" relocation     = %d", relocation_size);
 145     if (consts_size != 0)         tty->print_cr(" constants      = %d", consts_size);
 146     if (insts_size != 0)          tty->print_cr(" main code      = %d", insts_size);
 147     if (stub_size != 0)           tty->print_cr(" stub code      = %d", stub_size);
 148     if (oops_size != 0)           tty->print_cr(" oops           = %d", oops_size);

 149     if (scopes_data_size != 0)    tty->print_cr(" scopes data    = %d", scopes_data_size);
 150     if (scopes_pcs_size != 0)     tty->print_cr(" scopes pcs     = %d", scopes_pcs_size);
 151     if (dependencies_size != 0)   tty->print_cr(" dependencies   = %d", dependencies_size);
 152     if (handler_table_size != 0)  tty->print_cr(" handler table  = %d", handler_table_size);
 153     if (nul_chk_table_size != 0)  tty->print_cr(" nul chk table  = %d", nul_chk_table_size);
 154   }

 155 

 156   int native_nmethod_count;
 157   int native_total_size;
 158   int native_relocation_size;
 159   int native_insts_size;
 160   int native_oops_size;

 161   void note_native_nmethod(nmethod* nm) {
 162     native_nmethod_count += 1;
 163     native_total_size       += nm->size();
 164     native_relocation_size  += nm->relocation_size();
 165     native_insts_size       += nm->insts_size();
 166     native_oops_size        += nm->oops_size();

 167   }
 168   void print_native_nmethod_stats() {
 169     if (native_nmethod_count == 0)  return;
 170     tty->print_cr("Statistics for %d native nmethods:", native_nmethod_count);
 171     if (native_total_size != 0)       tty->print_cr(" N. total size  = %d", native_total_size);
 172     if (native_relocation_size != 0)  tty->print_cr(" N. relocation  = %d", native_relocation_size);
 173     if (native_insts_size != 0)       tty->print_cr(" N. main code   = %d", native_insts_size);
 174     if (native_oops_size != 0)        tty->print_cr(" N. oops        = %d", native_oops_size);

 175   }

 176 

 177   int pc_desc_resets;   // number of resets (= number of caches)
 178   int pc_desc_queries;  // queries to nmethod::find_pc_desc
 179   int pc_desc_approx;   // number of those which have approximate true
 180   int pc_desc_repeats;  // number of _pc_descs[0] hits
 181   int pc_desc_hits;     // number of LRU cache hits
 182   int pc_desc_tests;    // total number of PcDesc examinations
 183   int pc_desc_searches; // total number of quasi-binary search steps
 184   int pc_desc_adds;     // number of LUR cache insertions
 185 
 186   void print_pc_stats() {
 187     tty->print_cr("PcDesc Statistics:  %d queries, %.2f comparisons per query",
 188                   pc_desc_queries,
 189                   (double)(pc_desc_tests + pc_desc_searches)
 190                   / pc_desc_queries);
 191     tty->print_cr("  caches=%d queries=%d/%d, hits=%d+%d, tests=%d+%d, adds=%d",
 192                   pc_desc_resets,
 193                   pc_desc_queries, pc_desc_approx,
 194                   pc_desc_repeats, pc_desc_hits,
 195                   pc_desc_tests, pc_desc_searches, pc_desc_adds);
 196   }
 197 } nmethod_stats;
 198 #endif //PRODUCT
 199 











































 200 
 201 //---------------------------------------------------------------------------------
 202 
 203 
 204 ExceptionCache::ExceptionCache(Handle exception, address pc, address handler) {
 205   assert(pc != NULL, "Must be non null");
 206   assert(exception.not_null(), "Must be non null");
 207   assert(handler != NULL, "Must be non null");
 208 
 209   _count = 0;
 210   _exception_type = exception->klass();
 211   _next = NULL;
 212 
 213   add_address_and_handler(pc,handler);
 214 }
 215 
 216 
 217 address ExceptionCache::match(Handle exception, address pc) {
 218   assert(pc != NULL,"Must be non null");
 219   assert(exception.not_null(),"Must be non null");


 259 // private method for handling exception cache
 260 // These methods are private, and used to manipulate the exception cache
 261 // directly.
 262 ExceptionCache* nmethod::exception_cache_entry_for_exception(Handle exception) {
 263   ExceptionCache* ec = exception_cache();
 264   while (ec != NULL) {
 265     if (ec->match_exception_with_space(exception)) {
 266       return ec;
 267     }
 268     ec = ec->next();
 269   }
 270   return NULL;
 271 }
 272 
 273 
 274 //-----------------------------------------------------------------------------
 275 
 276 
 277 // Helper used by both find_pc_desc methods.
 278 static inline bool match_desc(PcDesc* pc, int pc_offset, bool approximate) {
 279   NOT_PRODUCT(++nmethod_stats.pc_desc_tests);
 280   if (!approximate)
 281     return pc->pc_offset() == pc_offset;
 282   else
 283     return (pc-1)->pc_offset() < pc_offset && pc_offset <= pc->pc_offset();
 284 }
 285 
 286 void PcDescCache::reset_to(PcDesc* initial_pc_desc) {
 287   if (initial_pc_desc == NULL) {
 288     _pc_descs[0] = NULL; // native method; no PcDescs at all
 289     return;
 290   }
 291   NOT_PRODUCT(++nmethod_stats.pc_desc_resets);
 292   // reset the cache by filling it with benign (non-null) values
 293   assert(initial_pc_desc->pc_offset() < 0, "must be sentinel");
 294   for (int i = 0; i < cache_size; i++)
 295     _pc_descs[i] = initial_pc_desc;
 296 }
 297 
 298 PcDesc* PcDescCache::find_pc_desc(int pc_offset, bool approximate) {
 299   NOT_PRODUCT(++nmethod_stats.pc_desc_queries);
 300   NOT_PRODUCT(if (approximate) ++nmethod_stats.pc_desc_approx);
 301 
 302   // Note: one might think that caching the most recently
 303   // read value separately would be a win, but one would be
 304   // wrong.  When many threads are updating it, the cache
 305   // line it's in would bounce between caches, negating
 306   // any benefit.
 307 
 308   // In order to prevent race conditions do not load cache elements
 309   // repeatedly, but use a local copy:
 310   PcDesc* res;
 311 
 312   // Step one:  Check the most recently added value.
 313   res = _pc_descs[0];
 314   if (res == NULL) return NULL;  // native method; no PcDescs at all
 315   if (match_desc(res, pc_offset, approximate)) {
 316     NOT_PRODUCT(++nmethod_stats.pc_desc_repeats);
 317     return res;
 318   }
 319 
 320   // Step two:  Check the rest of the LRU cache.
 321   for (int i = 1; i < cache_size; ++i) {
 322     res = _pc_descs[i];
 323     if (res->pc_offset() < 0) break;  // optimization: skip empty cache
 324     if (match_desc(res, pc_offset, approximate)) {
 325       NOT_PRODUCT(++nmethod_stats.pc_desc_hits);
 326       return res;
 327     }
 328   }
 329 
 330   // Report failure.
 331   return NULL;
 332 }
 333 
 334 void PcDescCache::add_pc_desc(PcDesc* pc_desc) {
 335   NOT_PRODUCT(++nmethod_stats.pc_desc_adds);
 336   // Update the LRU cache by shifting pc_desc forward.
 337   for (int i = 0; i < cache_size; i++)  {
 338     PcDesc* next = _pc_descs[i];
 339     _pc_descs[i] = pc_desc;
 340     pc_desc = next;
 341   }
 342 }
 343 
 344 // adjust pcs_size so that it is a multiple of both oopSize and
 345 // sizeof(PcDesc) (assumes that if sizeof(PcDesc) is not a multiple
 346 // of oopSize, then 2*sizeof(PcDesc) is)
 347 static int adjust_pcs_size(int pcs_size) {
 348   int nsize = round_to(pcs_size,   oopSize);
 349   if ((nsize % sizeof(PcDesc)) != 0) {
 350     nsize = pcs_size + sizeof(PcDesc);
 351   }
 352   assert((nsize % oopSize) == 0, "correct alignment");
 353   return nsize;
 354 }
 355 


 461   _stack_traversal_mark       = 0;
 462   _unload_reported            = false;           // jvmti state
 463 
 464 #ifdef ASSERT
 465   _oops_are_stale             = false;
 466 #endif
 467 
 468   _oops_do_mark_link       = NULL;
 469   _jmethod_id              = NULL;
 470   _osr_link                = NULL;
 471   if (UseG1GC) {
 472     _unloading_next        = NULL;
 473   } else {
 474     _scavenge_root_link    = NULL;
 475   }
 476   _scavenge_root_state     = 0;
 477   _compiler                = NULL;
 478 #if INCLUDE_RTM_OPT
 479   _rtm_state               = NoRTM;
 480 #endif




 481 }
 482 
 483 nmethod* nmethod::new_native_nmethod(methodHandle method,
 484   int compile_id,
 485   CodeBuffer *code_buffer,
 486   int vep_offset,
 487   int frame_complete,
 488   int frame_size,
 489   ByteSize basic_lock_owner_sp_offset,
 490   ByteSize basic_lock_sp_offset,
 491   OopMapSet* oop_maps) {
 492   code_buffer->finalize_oop_references(method);
 493   // create nmethod
 494   nmethod* nm = NULL;
 495   {
 496     MutexLockerEx mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
 497     int native_nmethod_size = allocation_size(code_buffer, sizeof(nmethod));
 498     CodeOffsets offsets;
 499     offsets.set_value(CodeOffsets::Verified_Entry, vep_offset);
 500     offsets.set_value(CodeOffsets::Frame_Complete, frame_complete);
 501     nm = new (native_nmethod_size, CompLevel_none) nmethod(method(), native_nmethod_size,
 502                                             compile_id, &offsets,
 503                                             code_buffer, frame_size,
 504                                             basic_lock_owner_sp_offset,
 505                                             basic_lock_sp_offset, oop_maps);
 506     NOT_PRODUCT(if (nm != NULL)  nmethod_stats.note_native_nmethod(nm));
 507     if ((PrintAssembly || CompilerOracle::should_print(method)) && nm != NULL) {
 508       Disassembler::decode(nm);
 509     }
 510   }
 511   // verify nmethod
 512   debug_only(if (nm) nm->verify();) // might block
 513 
 514   if (nm != NULL) {
 515     nm->log_new_nmethod();
 516   }
 517 
 518   return nm;
 519 }
 520 
 521 nmethod* nmethod::new_nmethod(methodHandle method,
 522   int compile_id,
 523   int entry_bci,
 524   CodeOffsets* offsets,
 525   int orig_pc_offset,
 526   DebugInformationRecorder* debug_info,
 527   Dependencies* dependencies,
 528   CodeBuffer* code_buffer, int frame_size,
 529   OopMapSet* oop_maps,
 530   ExceptionHandlerTable* handler_table,
 531   ImplicitExceptionTable* nul_chk_table,
 532   AbstractCompiler* compiler,
 533   int comp_level




 534 )
 535 {
 536   assert(debug_info->oop_recorder() == code_buffer->oop_recorder(), "shared OR");
 537   code_buffer->finalize_oop_references(method);
 538   // create nmethod
 539   nmethod* nm = NULL;
 540   { MutexLockerEx mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
 541     int nmethod_size =
 542       allocation_size(code_buffer, sizeof(nmethod))
 543       + adjust_pcs_size(debug_info->pcs_size())
 544       + round_to(dependencies->size_in_bytes() , oopSize)
 545       + round_to(handler_table->size_in_bytes(), oopSize)
 546       + round_to(nul_chk_table->size_in_bytes(), oopSize)
 547       + round_to(debug_info->data_size()       , oopSize);
 548 
 549     nm = new (nmethod_size, comp_level)
 550     nmethod(method(), nmethod_size, compile_id, entry_bci, offsets,
 551             orig_pc_offset, debug_info, dependencies, code_buffer, frame_size,
 552             oop_maps,
 553             handler_table,
 554             nul_chk_table,
 555             compiler,
 556             comp_level);





 557 
 558     if (nm != NULL) {
 559       // To make dependency checking during class loading fast, record
 560       // the nmethod dependencies in the classes it is dependent on.
 561       // This allows the dependency checking code to simply walk the
 562       // class hierarchy above the loaded class, checking only nmethods
 563       // which are dependent on those classes.  The slow way is to
 564       // check every nmethod for dependencies which makes it linear in
 565       // the number of methods compiled.  For applications with a lot
 566       // classes the slow way is too slow.
 567       for (Dependencies::DepStream deps(nm); deps.next(); ) {
 568         if (deps.type() == Dependencies::call_site_target_value) {
 569           // CallSite dependencies are managed on per-CallSite instance basis.
 570           oop call_site = deps.argument_oop(0);
 571           MethodHandles::add_dependent_nmethod(call_site, nm);
 572         } else {
 573           Klass* klass = deps.context_type();
 574           if (klass == NULL) {
 575             continue;  // ignore things like evol_method
 576           }
 577           // record this nmethod as dependent on this klass
 578           InstanceKlass::cast(klass)->add_dependent_nmethod(nm);
 579         }
 580       }
 581       NOT_PRODUCT(nmethod_stats.note_nmethod(nm));
 582       if (PrintAssembly || CompilerOracle::has_option_string(method, "PrintAssembly")) {
 583         Disassembler::decode(nm);
 584       }
 585     }
 586   }
 587   // Do verification and logging outside CodeCache_lock.
 588   if (nm != NULL) {
 589     // Safepoints in nmethod::verify aren't allowed because nm hasn't been installed yet.
 590     DEBUG_ONLY(nm->verify();)
 591     nm->log_new_nmethod();
 592   }
 593   return nm;
 594 }
 595 
 596 



 597 // For native wrappers
 598 nmethod::nmethod(
 599   Method* method,
 600   int nmethod_size,
 601   int compile_id,
 602   CodeOffsets* offsets,
 603   CodeBuffer* code_buffer,
 604   int frame_size,
 605   ByteSize basic_lock_owner_sp_offset,
 606   ByteSize basic_lock_sp_offset,
 607   OopMapSet* oop_maps )
 608   : CodeBlob("native nmethod", code_buffer, sizeof(nmethod),
 609              nmethod_size, offsets->value(CodeOffsets::Frame_Complete), frame_size, oop_maps),
 610   _native_receiver_sp_offset(basic_lock_owner_sp_offset),
 611   _native_basic_lock_sp_offset(basic_lock_sp_offset)
 612 {
 613   {
 614     debug_only(No_Safepoint_Verifier nsv;)
 615     assert_locked_or_safepoint(CodeCache_lock);
 616 


 666       xtty->end_head(" address='" INTPTR_FORMAT "'", (intptr_t) this);
 667     }
 668     // print the header part first
 669     print();
 670     // then print the requested information
 671     if (PrintNativeNMethods) {
 672       print_code();
 673       if (oop_maps != NULL) {
 674         oop_maps->print();
 675       }
 676     }
 677     if (PrintRelocations) {
 678       print_relocations();
 679     }
 680     if (xtty != NULL) {
 681       xtty->tail("print_native_nmethod");
 682     }
 683   }
 684 }
 685 




 686 void* nmethod::operator new(size_t size, int nmethod_size, int comp_level) throw () {
 687   return CodeCache::allocate(nmethod_size, CodeCache::get_code_blob_type(comp_level));
 688 }
 689 
 690 nmethod::nmethod(
 691   Method* method,
 692   int nmethod_size,
 693   int compile_id,
 694   int entry_bci,
 695   CodeOffsets* offsets,
 696   int orig_pc_offset,
 697   DebugInformationRecorder* debug_info,
 698   Dependencies* dependencies,
 699   CodeBuffer *code_buffer,
 700   int frame_size,
 701   OopMapSet* oop_maps,
 702   ExceptionHandlerTable* handler_table,
 703   ImplicitExceptionTable* nul_chk_table,
 704   AbstractCompiler* compiler,
 705   int comp_level




 706   )
 707   : CodeBlob("nmethod", code_buffer, sizeof(nmethod),
 708              nmethod_size, offsets->value(CodeOffsets::Frame_Complete), frame_size, oop_maps),
 709   _native_receiver_sp_offset(in_ByteSize(-1)),
 710   _native_basic_lock_sp_offset(in_ByteSize(-1))
 711 {
 712   assert(debug_info->oop_recorder() == code_buffer->oop_recorder(), "shared OR");
 713   {
 714     debug_only(No_Safepoint_Verifier nsv;)
 715     assert_locked_or_safepoint(CodeCache_lock);
 716 
 717     init_defaults();
 718     _method                  = method;
 719     _entry_bci               = entry_bci;
 720     _compile_id              = compile_id;
 721     _comp_level              = comp_level;
 722     _compiler                = compiler;
 723     _orig_pc_offset          = orig_pc_offset;
 724     _hotness_counter         = NMethodSweeper::hotness_counter_reset_val();
 725 
 726     // Section offsets
 727     _consts_offset           = content_offset()      + code_buffer->total_offset_of(code_buffer->consts());
 728     _stub_offset             = content_offset()      + code_buffer->total_offset_of(code_buffer->stubs());
 729 























 730     // Exception handler and deopt handler are in the stub section
 731     assert(offsets->value(CodeOffsets::Exceptions) != -1, "must be set");
 732     assert(offsets->value(CodeOffsets::Deopt     ) != -1, "must be set");

 733     _exception_offset        = _stub_offset          + offsets->value(CodeOffsets::Exceptions);
 734     _deoptimize_offset       = _stub_offset          + offsets->value(CodeOffsets::Deopt);
 735     if (offsets->value(CodeOffsets::DeoptMH) != -1) {
 736       _deoptimize_mh_offset  = _stub_offset          + offsets->value(CodeOffsets::DeoptMH);
 737     } else {
 738       _deoptimize_mh_offset  = -1;



 739     }
 740     if (offsets->value(CodeOffsets::UnwindHandler) != -1) {
 741       _unwind_handler_offset = code_offset()         + offsets->value(CodeOffsets::UnwindHandler);
 742     } else {
 743       _unwind_handler_offset = -1;
 744     }
 745 
 746     _oops_offset             = data_offset();
 747     _metadata_offset         = _oops_offset          + round_to(code_buffer->total_oop_size(), oopSize);
 748     _scopes_data_offset      = _metadata_offset      + round_to(code_buffer->total_metadata_size(), wordSize);
 749 
 750     _scopes_pcs_offset       = _scopes_data_offset   + round_to(debug_info->data_size       (), oopSize);
 751     _dependencies_offset     = _scopes_pcs_offset    + adjust_pcs_size(debug_info->pcs_size());
 752     _handler_table_offset    = _dependencies_offset  + round_to(dependencies->size_in_bytes (), oopSize);
 753     _nul_chk_table_offset    = _handler_table_offset + round_to(handler_table->size_in_bytes(), oopSize);
 754     _nmethod_end_offset      = _nul_chk_table_offset + round_to(nul_chk_table->size_in_bytes(), oopSize);
 755 
 756     _entry_point             = code_begin()          + offsets->value(CodeOffsets::Entry);
 757     _verified_entry_point    = code_begin()          + offsets->value(CodeOffsets::Verified_Entry);
 758     _osr_entry_point         = code_begin()          + offsets->value(CodeOffsets::OSR_Entry);


 762     // Copy contents of ScopeDescRecorder to nmethod
 763     code_buffer->copy_values_to(this);
 764     debug_info->copy_to(this);
 765     dependencies->copy_to(this);
 766     if (ScavengeRootsInCode) {
 767       if (detect_scavenge_root_oops()) {
 768         CodeCache::add_scavenge_root_nmethod(this);
 769       }
 770       Universe::heap()->register_nmethod(this);
 771     }
 772     debug_only(verify_scavenge_root_oops());
 773 
 774     CodeCache::commit(this);
 775 
 776     // Copy contents of ExceptionHandlerTable to nmethod
 777     handler_table->copy_to(this);
 778     nul_chk_table->copy_to(this);
 779 
 780     // we use the information of entry points to find out if a method is
 781     // static or non static
 782     assert(compiler->is_c2() ||
 783            _method->is_static() == (entry_point() == _verified_entry_point),
 784            " entry points must be same for static methods and vice versa");
 785   }
 786 
 787   bool printnmethods = PrintNMethods
 788     || CompilerOracle::should_print(_method)
 789     || CompilerOracle::has_option_string(_method, "PrintNMethods");
 790   if (printnmethods || PrintDebugInfo || PrintRelocations || PrintDependencies || PrintExceptionHandlers) {
 791     print_nmethod(printnmethods);
 792   }
 793 }
 794 
 795 
 796 // Print a short set of xml attributes to identify this nmethod.  The
 797 // output should be embedded in some other element.
 798 void nmethod::log_identity(xmlStream* log) const {
 799   log->print(" compile_id='%d'", compile_id());
 800   const char* nm_kind = compile_kind();
 801   if (nm_kind != NULL)  log->print(" compile_kind='%s'", nm_kind);
 802   if (compiler() != NULL) {
 803     log->print(" compiler='%s'", compiler()->name());
 804   }
 805   if (TieredCompilation) {
 806     log->print(" level='%d'", comp_level());
 807   }
 808 }
 809 
 810 
 811 #define LOG_OFFSET(log, name)                    \
 812   if ((intptr_t)name##_end() - (intptr_t)name##_begin()) \
 813     log->print(" " XSTR(name) "_offset='%d'"    , \
 814                (intptr_t)name##_begin() - (intptr_t)this)
 815 
 816 
 817 void nmethod::log_new_nmethod() const {
 818   if (LogCompilation && xtty != NULL) {
 819     ttyLocker ttyl;
 820     HandleMark hm;
 821     xtty->begin_elem("nmethod");
 822     log_identity(xtty);
 823     xtty->print(" entry='" INTPTR_FORMAT "' size='%d'", code_begin(), size());
 824     xtty->print(" address='" INTPTR_FORMAT "'", (intptr_t) this);
 825 
 826     LOG_OFFSET(xtty, relocation);
 827     LOG_OFFSET(xtty, consts);
 828     LOG_OFFSET(xtty, insts);
 829     LOG_OFFSET(xtty, stub);
 830     LOG_OFFSET(xtty, scopes_data);
 831     LOG_OFFSET(xtty, scopes_pcs);
 832     LOG_OFFSET(xtty, dependencies);
 833     LOG_OFFSET(xtty, handler_table);
 834     LOG_OFFSET(xtty, nul_chk_table);
 835     LOG_OFFSET(xtty, oops);

 836 
 837     xtty->method(method());
 838     xtty->stamp();
 839     xtty->end_elem();
 840   }
 841 }
 842 
 843 #undef LOG_OFFSET
 844 
 845 
 846 // Print out more verbose output usually for a newly created nmethod.
 847 void nmethod::print_on(outputStream* st, const char* msg) const {
 848   if (st != NULL) {
 849     ttyLocker ttyl;
 850     if (WizardMode) {
 851       CompileTask::print_compilation(st, this, msg, /*short_form:*/ true);
 852       st->print_cr(" (" INTPTR_FORMAT ")", this);
 853     } else {
 854       CompileTask::print_compilation(st, this, msg, /*short_form:*/ false);
 855     }


 857 }
 858 
 859 
 860 void nmethod::print_nmethod(bool printmethod) {
 861   ttyLocker ttyl;  // keep the following output all in one block
 862   if (xtty != NULL) {
 863     xtty->begin_head("print_nmethod");
 864     xtty->stamp();
 865     xtty->end_head();
 866   }
 867   // print the header part first
 868   print();
 869   // then print the requested information
 870   if (printmethod) {
 871     print_code();
 872     print_pcs();
 873     if (oop_maps()) {
 874       oop_maps()->print();
 875     }
 876   }
 877   if (PrintDebugInfo) {
 878     print_scopes();
 879   }
 880   if (PrintRelocations) {
 881     print_relocations();
 882   }
 883   if (PrintDependencies) {
 884     print_dependencies();
 885   }
 886   if (PrintExceptionHandlers) {
 887     print_handler_table();
 888     print_nul_chk_table();
 889   }
 890   if (xtty != NULL) {
 891     xtty->tail("print_nmethod");
 892   }
 893 }
 894 
 895 
 896 // Promote one word from an assembly-time handle to a live embedded oop.
 897 inline void nmethod::initialize_immediate_oop(oop* dest, jobject handle) {
 898   if (handle == NULL ||
 899       // As a special case, IC oops are initialized to 1 or -1.
 900       handle == (jobject) Universe::non_oop_word()) {
 901     (*dest) = (oop) handle;
 902   } else {
 903     (*dest) = JNIHandles::resolve_non_null(handle);


 973 
 974 
 975 void nmethod::verify_oop_relocations() {
 976   // Ensure sure that the code matches the current oop values
 977   RelocIterator iter(this, NULL, NULL);
 978   while (iter.next()) {
 979     if (iter.type() == relocInfo::oop_type) {
 980       oop_Relocation* reloc = iter.oop_reloc();
 981       if (!reloc->oop_is_immediate()) {
 982         reloc->verify_oop_relocation();
 983       }
 984     }
 985   }
 986 }
 987 
 988 
 989 ScopeDesc* nmethod::scope_desc_at(address pc) {
 990   PcDesc* pd = pc_desc_at(pc);
 991   guarantee(pd != NULL, "scope must be present");
 992   return new ScopeDesc(this, pd->scope_decode_offset(),
 993                        pd->obj_decode_offset(), pd->should_reexecute(),
 994                        pd->return_oop());
 995 }
 996 
 997 
 998 void nmethod::clear_inline_caches() {
 999   assert(SafepointSynchronize::is_at_safepoint(), "cleaning of IC's only allowed at safepoint");
1000   if (is_zombie()) {
1001     return;
1002   }
1003 
1004   RelocIterator iter(this);
1005   while (iter.next()) {
1006     iter.reloc()->clear_inline_cache();
1007   }
1008 }
1009 
1010 // Clear ICStubs of all compiled ICs
1011 void nmethod::clear_ic_stubs() {
1012   assert_locked_or_safepoint(CompiledIC_lock);
1013   RelocIterator iter(this);


1144   assert(is_alive(), "Must be an alive method");
1145   // Set the traversal mark to ensure that the sweeper does 2
1146   // cleaning passes before moving to zombie.
1147   set_stack_traversal_mark(NMethodSweeper::traversal_count());
1148 }
1149 
1150 // Tell if a non-entrant method can be converted to a zombie (i.e.,
1151 // there are no activations on the stack, not in use by the VM,
1152 // and not in use by the ServiceThread)
1153 bool nmethod::can_not_entrant_be_converted() {
1154   assert(is_not_entrant(), "must be a non-entrant method");
1155 
1156   // Since the nmethod sweeper only does partial sweep the sweeper's traversal
1157   // count can be greater than the stack traversal count before it hits the
1158   // nmethod for the second time.
1159   return stack_traversal_mark()+1 < NMethodSweeper::traversal_count() &&
1160          !is_locked_by_vm();
1161 }
1162 
1163 void nmethod::inc_decompile_count() {
1164   if (!is_compiled_by_c2()) return;
1165   // Could be gated by ProfileTraps, but do not bother...
1166   Method* m = method();
1167   if (m == NULL)  return;
1168   MethodData* mdo = m->method_data();
1169   if (mdo == NULL)  return;
1170   // There is a benign race here.  See comments in methodData.hpp.
1171   mdo->inc_decompile_count();
1172 }
1173 
1174 void nmethod::increase_unloading_clock() {
1175   _global_unloading_clock++;
1176   if (_global_unloading_clock == 0) {
1177     // _nmethods are allocated with _unloading_clock == 0,
1178     // so 0 is never used as a clock value.
1179     _global_unloading_clock = 1;
1180   }
1181 }
1182 
1183 void nmethod::set_unloading_clock(unsigned char unloading_clock) {
1184   OrderAccess::release_store((volatile jubyte*)&_unloading_clock, unloading_clock);


1208                   this, (address)_method, (address)cause);
1209     if (!Universe::heap()->is_gc_active())
1210       cause->klass()->print();
1211   }
1212   // Unlink the osr method, so we do not look this up again
1213   if (is_osr_method()) {
1214     invalidate_osr_method();
1215   }
1216   // If _method is already NULL the Method* is about to be unloaded,
1217   // so we don't have to break the cycle. Note that it is possible to
1218   // have the Method* live here, in case we unload the nmethod because
1219   // it is pointing to some oop (other than the Method*) being unloaded.
1220   if (_method != NULL) {
1221     // OSR methods point to the Method*, but the Method* does not
1222     // point back!
1223     if (_method->code() == this) {
1224       _method->clear_code(); // Break a cycle
1225     }
1226     _method = NULL;            // Clear the method of this dead nmethod
1227   }

1228   // Make the class unloaded - i.e., change state and notify sweeper
1229   assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint");
1230   if (is_in_use()) {
1231     // Transitioning directly from live to unloaded -- so
1232     // we need to force a cache clean-up; remember this
1233     // for later on.
1234     CodeCache::set_needs_cache_clean(true);
1235   }
1236 
1237   // Unregister must be done before the state change
1238   Universe::heap()->unregister_nmethod(this);
1239 












1240   _state = unloaded;
1241 
1242   // Log the unloading.
1243   log_state_change();
1244 
1245   // The Method* is gone at this point
1246   assert(_method == NULL, "Tautology");
1247 
1248   set_osr_link(NULL);
1249   //set_scavenge_root_link(NULL); // done by prune_scavenge_root_nmethods
1250   NMethodSweeper::report_state_change(this);
1251 }
1252 
1253 void nmethod::invalidate_osr_method() {
1254   assert(_entry_bci != InvocationEntryBci, "wrong kind of nmethod");
1255   // Remove from list of active nmethods
1256   if (method() != NULL)
1257     method()->method_holder()->remove_osr_nmethod(this);
1258 }
1259 


1383     }
1384 
1385     // zombie only - if a JVMTI agent has enabled the CompiledMethodUnload
1386     // event and it hasn't already been reported for this nmethod then
1387     // report it now. The event may have been reported earilier if the GC
1388     // marked it for unloading). JvmtiDeferredEventQueue support means
1389     // we no longer go to a safepoint here.
1390     post_compiled_method_unload();
1391 
1392 #ifdef ASSERT
1393     // It's no longer safe to access the oops section since zombie
1394     // nmethods aren't scanned for GC.
1395     _oops_are_stale = true;
1396 #endif
1397      // the Method may be reclaimed by class unloading now that the
1398      // nmethod is in zombie state
1399     set_method(NULL);
1400   } else {
1401     assert(state == not_entrant, "other cases may need to be handled differently");
1402   }






1403 
1404   if (TraceCreateZombies) {
1405     tty->print_cr("nmethod <" INTPTR_FORMAT "> code made %s", this, (state == not_entrant) ? "not entrant" : "zombie");

1406   }
1407 
1408   NMethodSweeper::report_state_change(this);
1409   return true;
1410 }
1411 
1412 void nmethod::flush() {
1413   // Note that there are no valid oops in the nmethod anymore.
1414   assert(is_zombie() || (is_osr_method() && is_unloaded()), "must be a zombie method");
1415   assert(is_marked_for_reclamation() || (is_osr_method() && is_unloaded()), "must be marked for reclamation");
1416 
1417   assert (!is_locked_by_vm(), "locked methods shouldn't be flushed");
1418   assert_locked_or_safepoint(CodeCache_lock);
1419 
1420   // completely deallocate this method
1421   Events::log(JavaThread::current(), "flushing nmethod " INTPTR_FORMAT, this);
1422   if (PrintMethodFlushing) {
1423     tty->print_cr("*flushing nmethod %3d/" INTPTR_FORMAT ". Live blobs:" UINT32_FORMAT "/Free CodeCache:" SIZE_FORMAT "Kb",
1424         _compile_id, this, CodeCache::nof_blobs(), CodeCache::unallocated_capacity(CodeCache::get_code_blob_type(this))/1024);
1425   }


1673                   (r->oop_addr() >= oops_begin() && r->oop_addr() < oops_end()),
1674              "oop must be found in exactly one place");
1675       if (r->oop_is_immediate() && r->oop_value() != NULL) {
1676         if (can_unload(is_alive, r->oop_addr(), unloading_occurred)) {
1677           return;
1678         }
1679       }
1680     }
1681   }
1682   }
1683 
1684 
1685   // Scopes
1686   for (oop* p = oops_begin(); p < oops_end(); p++) {
1687     if (*p == Universe::non_oop_word())  continue;  // skip non-oops
1688     if (can_unload(is_alive, p, unloading_occurred)) {
1689       return;
1690     }
1691   }
1692 



























1693   // Ensure that all metadata is still alive
1694   verify_metadata_loaders(low_boundary, is_alive);
1695 }
1696 
1697 template <class CompiledICorStaticCall>
1698 static bool clean_if_nmethod_is_unloaded(CompiledICorStaticCall *ic, address addr, BoolObjectClosure *is_alive, nmethod* from) {
1699   // Ok, to lookup references to zombies here
1700   CodeBlob *cb = CodeCache::find_blob_unsafe(addr);
1701   if (cb != NULL && cb->is_nmethod()) {
1702     nmethod* nm = (nmethod*)cb;
1703 
1704     if (nm->unloading_clock() != nmethod::global_unloading_clock()) {
1705       // The nmethod has not been processed yet.
1706       return true;
1707     }
1708 
1709     // Clean inline caches pointing to both zombie and not_entrant methods
1710     if (!nm->is_in_use() || (nm->method()->code() != nm)) {
1711       ic->set_to_clean();
1712       assert(ic->is_clean(), err_msg("nmethod " PTR_FORMAT "not clean %s", from, from->method()->name_and_sig_as_C_string()));


1755   // first few bytes.  If an oop in the old code was there, that oop
1756   // should not get GC'd.  Skip the first few bytes of oops on
1757   // not-entrant methods.
1758   address low_boundary = verified_entry_point();
1759   if (is_not_entrant()) {
1760     low_boundary += NativeJump::instruction_size;
1761     // %%% Note:  On SPARC we patch only a 4-byte trap, not a full NativeJump.
1762     // (See comment above.)
1763   }
1764 
1765   // The RedefineClasses() API can cause the class unloading invariant
1766   // to no longer be true. See jvmtiExport.hpp for details.
1767   // Also, leave a debugging breadcrumb in local flag.
1768   if (JvmtiExport::has_redefined_a_class()) {
1769     // This set of the unloading_occurred flag is done before the
1770     // call to post_compiled_method_unload() so that the unloading
1771     // of this nmethod is reported.
1772     unloading_occurred = true;
1773   }
1774 





















1775   // Exception cache
1776   clean_exception_cache(is_alive);
1777 
1778   bool is_unloaded = false;
1779   bool postponed = false;
1780 
1781   RelocIterator iter(this, low_boundary);
1782   while(iter.next()) {
1783 
1784     switch (iter.type()) {
1785 
1786     case relocInfo::virtual_call_type:
1787       if (unloading_occurred) {
1788         // If class unloading occurred we first iterate over all inline caches and
1789         // clear ICs where the cached oop is referring to an unloaded klass or method.
1790         clean_ic_if_metadata_is_dead(CompiledIC_at(&iter), is_alive);
1791       }
1792 
1793       postponed |= clean_if_nmethod_is_unloaded(CompiledIC_at(&iter), is_alive, this);
1794       break;


1812     }
1813   }
1814 
1815   if (is_unloaded) {
1816     return postponed;
1817   }
1818 
1819   // Scopes
1820   for (oop* p = oops_begin(); p < oops_end(); p++) {
1821     if (*p == Universe::non_oop_word())  continue;  // skip non-oops
1822     if (can_unload(is_alive, p, unloading_occurred)) {
1823       is_unloaded = true;
1824       break;
1825     }
1826   }
1827 
1828   if (is_unloaded) {
1829     return postponed;
1830   }
1831 


























1832   // Ensure that all metadata is still alive
1833   verify_metadata_loaders(low_boundary, is_alive);
1834 
1835   return postponed;
1836 }
1837 
1838 void nmethod::do_unloading_parallel_postponed(BoolObjectClosure* is_alive, bool unloading_occurred) {
1839   ResourceMark rm;
1840 
1841   // Make sure the oop's ready to receive visitors
1842   assert(!is_zombie(),
1843          "should not call follow on zombie nmethod");
1844 
1845   // If the method is not entrant then a JMP is plastered over the
1846   // first few bytes.  If an oop in the old code was there, that oop
1847   // should not get GC'd.  Skip the first few bytes of oops on
1848   // not-entrant methods.
1849   address low_boundary = verified_entry_point();
1850   if (is_not_entrant()) {
1851     low_boundary += NativeJump::instruction_size;


1996   // Visit metadata not embedded in the other places.
1997   if (_method != NULL) f(_method);
1998 }
1999 
2000 void nmethod::oops_do(OopClosure* f, bool allow_zombie) {
2001   // make sure the oops ready to receive visitors
2002   assert(allow_zombie || !is_zombie(), "should not call follow on zombie nmethod");
2003   assert(!is_unloaded(), "should not call follow on unloaded nmethod");
2004 
2005   // If the method is not entrant or zombie then a JMP is plastered over the
2006   // first few bytes.  If an oop in the old code was there, that oop
2007   // should not get GC'd.  Skip the first few bytes of oops on
2008   // not-entrant methods.
2009   address low_boundary = verified_entry_point();
2010   if (is_not_entrant()) {
2011     low_boundary += NativeJump::instruction_size;
2012     // %%% Note:  On SPARC we patch only a 4-byte trap, not a full NativeJump.
2013     // (See comment above.)
2014   }
2015 









2016   RelocIterator iter(this, low_boundary);
2017 
2018   while (iter.next()) {
2019     if (iter.type() == relocInfo::oop_type ) {
2020       oop_Relocation* r = iter.oop_reloc();
2021       // In this loop, we must only follow those oops directly embedded in
2022       // the code.  Other oops (oop_index>0) are seen as part of scopes_oops.
2023       assert(1 == (r->oop_is_immediate()) +
2024                    (r->oop_addr() >= oops_begin() && r->oop_addr() < oops_end()),
2025              "oop must be found in exactly one place");
2026       if (r->oop_is_immediate() && r->oop_value() != NULL) {
2027         f->do_oop(r->oop_addr());
2028       }
2029     }
2030   }
2031 
2032   // Scopes
2033   // This includes oop constants not inlined in the code stream.
2034   for (oop* p = oops_begin(); p < oops_end(); p++) {
2035     if (*p == Universe::non_oop_word())  continue;  // skip non-oops


2120     if (!_detected_scavenge_root)  _print_nm->print_on(tty, "new scavenge root");
2121     tty->print_cr("" PTR_FORMAT "[offset=%d] detected scavengable oop " PTR_FORMAT " (found at " PTR_FORMAT ")",
2122                   _print_nm, (int)((intptr_t)p - (intptr_t)_print_nm),
2123                   (void *)(*p), (intptr_t)p);
2124     (*p)->print();
2125   }
2126 #endif //PRODUCT
2127 };
2128 
2129 bool nmethod::detect_scavenge_root_oops() {
2130   DetectScavengeRoot detect_scavenge_root;
2131   NOT_PRODUCT(if (TraceScavenge)  detect_scavenge_root._print_nm = this);
2132   oops_do(&detect_scavenge_root);
2133   return detect_scavenge_root.detected_scavenge_root();
2134 }
2135 
2136 // Method that knows how to preserve outgoing arguments at call. This method must be
2137 // called with a frame corresponding to a Java invoke
2138 void nmethod::preserve_callee_argument_oops(frame fr, const RegisterMap *reg_map, OopClosure* f) {
2139 #ifndef SHARK
2140   if (!method()->is_native()) {
2141     SimpleScopeDesc ssd(this, fr.pc());
2142     Bytecode_invoke call(ssd.method(), ssd.bci());
2143     bool has_receiver = call.has_receiver();
2144     bool has_appendix = call.has_appendix();
2145     Symbol* signature = call.signature();
2146     fr.oops_compiled_arguments_do(signature, has_receiver, has_appendix, reg_map, f);
2147   }
2148 #endif // !SHARK
2149 }
2150 
2151 inline bool includes(void* p, void* from, void* to) {
2152   return from <= p && p < to;
2153 }
2154 
2155 
2156 void nmethod::copy_scopes_pcs(PcDesc* pcs, int count) {
2157   assert(count >= 2, "must be sentinel values, at least");
2158 
2159 #ifdef ASSERT
2160   // must be sorted and unique; we do a binary search in find_pc_desc()


2186   // Adjust the final sentinel downward.
2187   PcDesc* last_pc = &scopes_pcs_begin()[count-1];
2188   assert(last_pc->pc_offset() == PcDesc::upper_offset_limit, "sanity");
2189   last_pc->set_pc_offset(content_size() + 1);
2190   for (; last_pc + 1 < scopes_pcs_end(); last_pc += 1) {
2191     // Fill any rounding gaps with copies of the last record.
2192     last_pc[1] = last_pc[0];
2193   }
2194   // The following assert could fail if sizeof(PcDesc) is not
2195   // an integral multiple of oopSize (the rounding term).
2196   // If it fails, change the logic to always allocate a multiple
2197   // of sizeof(PcDesc), and fill unused words with copies of *last_pc.
2198   assert(last_pc + 1 == scopes_pcs_end(), "must match exactly");
2199 }
2200 
2201 void nmethod::copy_scopes_data(u_char* buffer, int size) {
2202   assert(scopes_data_size() >= size, "oob");
2203   memcpy(scopes_data_begin(), buffer, size);
2204 }
2205 








2206 
2207 #ifdef ASSERT
2208 static PcDesc* linear_search(nmethod* nm, int pc_offset, bool approximate) {
2209   PcDesc* lower = nm->scopes_pcs_begin();
2210   PcDesc* upper = nm->scopes_pcs_end();
2211   lower += 1; // exclude initial sentinel
2212   PcDesc* res = NULL;
2213   for (PcDesc* p = lower; p < upper; p++) {
2214     NOT_PRODUCT(--nmethod_stats.pc_desc_tests);  // don't count this call to match_desc
2215     if (match_desc(p, pc_offset, approximate)) {
2216       if (res == NULL)
2217         res = p;
2218       else
2219         res = (PcDesc*) badAddress;
2220     }
2221   }
2222   return res;
2223 }
2224 #endif
2225 
2226 
2227 // Finds a PcDesc with real-pc equal to "pc"
2228 PcDesc* nmethod::find_pc_desc_internal(address pc, bool approximate) {
2229   address base_address = code_begin();
2230   if ((pc < base_address) ||
2231       (pc - base_address) >= (ptrdiff_t) PcDesc::upper_offset_limit) {
2232     return NULL;  // PC is wildly out of range
2233   }
2234   int pc_offset = (int) (pc - base_address);


2241     return res;
2242   }
2243 
2244   // Fallback algorithm: quasi-linear search for the PcDesc
2245   // Find the last pc_offset less than the given offset.
2246   // The successor must be the required match, if there is a match at all.
2247   // (Use a fixed radix to avoid expensive affine pointer arithmetic.)
2248   PcDesc* lower = scopes_pcs_begin();
2249   PcDesc* upper = scopes_pcs_end();
2250   upper -= 1; // exclude final sentinel
2251   if (lower >= upper)  return NULL;  // native method; no PcDescs at all
2252 
2253 #define assert_LU_OK \
2254   /* invariant on lower..upper during the following search: */ \
2255   assert(lower->pc_offset() <  pc_offset, "sanity"); \
2256   assert(upper->pc_offset() >= pc_offset, "sanity")
2257   assert_LU_OK;
2258 
2259   // Use the last successful return as a split point.
2260   PcDesc* mid = _pc_desc_cache.last_pc_desc();
2261   NOT_PRODUCT(++nmethod_stats.pc_desc_searches);
2262   if (mid->pc_offset() < pc_offset) {
2263     lower = mid;
2264   } else {
2265     upper = mid;
2266   }
2267 
2268   // Take giant steps at first (4096, then 256, then 16, then 1)
2269   const int LOG2_RADIX = 4 /*smaller steps in debug mode:*/ debug_only(-1);
2270   const int RADIX = (1 << LOG2_RADIX);
2271   for (int step = (1 << (LOG2_RADIX*3)); step > 1; step >>= LOG2_RADIX) {
2272     while ((mid = lower + step) < upper) {
2273       assert_LU_OK;
2274       NOT_PRODUCT(++nmethod_stats.pc_desc_searches);
2275       if (mid->pc_offset() < pc_offset) {
2276         lower = mid;
2277       } else {
2278         upper = mid;
2279         break;
2280       }
2281     }
2282     assert_LU_OK;
2283   }
2284 
2285   // Sneak up on the value with a linear search of length ~16.
2286   while (true) {
2287     assert_LU_OK;
2288     mid = lower + 1;
2289     NOT_PRODUCT(++nmethod_stats.pc_desc_searches);
2290     if (mid->pc_offset() < pc_offset) {
2291       lower = mid;
2292     } else {
2293       upper = mid;
2294       break;
2295     }
2296   }
2297 #undef assert_LU_OK
2298 
2299   if (match_desc(upper, pc_offset, approximate)) {
2300     assert(upper == linear_search(this, pc_offset, approximate), "search ok");
2301     _pc_desc_cache.add_pc_desc(upper);
2302     return upper;
2303   } else {
2304     assert(NULL == linear_search(this, pc_offset, approximate), "search ok");
2305     return NULL;
2306   }
2307 }
2308 
2309 


2456   CodeBlob* cb = CodeCache::find_blob(pc);
2457   guarantee(cb != NULL && cb->is_nmethod(), "bad pc for a nmethod found");
2458   _nm = (nmethod*)cb;
2459   lock_nmethod(_nm);
2460 }
2461 
2462 // Only JvmtiDeferredEvent::compiled_method_unload_event()
2463 // should pass zombie_ok == true.
2464 void nmethodLocker::lock_nmethod(nmethod* nm, bool zombie_ok) {
2465   if (nm == NULL)  return;
2466   Atomic::inc(&nm->_lock_count);
2467   assert(zombie_ok || !nm->is_zombie(), "cannot lock a zombie method");
2468 }
2469 
2470 void nmethodLocker::unlock_nmethod(nmethod* nm) {
2471   if (nm == NULL)  return;
2472   Atomic::dec(&nm->_lock_count);
2473   assert(nm->_lock_count >= 0, "unmatched nmethod lock/unlock");
2474 }
2475 
2476 
2477 // -----------------------------------------------------------------------------
2478 // nmethod::get_deopt_original_pc
2479 //
2480 // Return the original PC for the given PC if:
2481 // (a) the given PC belongs to a nmethod and
2482 // (b) it is a deopt PC
2483 address nmethod::get_deopt_original_pc(const frame* fr) {
2484   if (fr->cb() == NULL)  return NULL;
2485 
2486   nmethod* nm = fr->cb()->as_nmethod_or_null();
2487   if (nm != NULL && nm->is_deopt_pc(fr->pc()))
2488     return nm->get_original_pc(fr);
2489 
2490   return NULL;
2491 }
2492 
2493 
2494 // -----------------------------------------------------------------------------
2495 // MethodHandle
2496 


2570 void nmethod::verify_interrupt_point(address call_site) {
2571   // Verify IC only when nmethod installation is finished.
2572   bool is_installed = (method()->code() == this) // nmethod is in state 'in_use' and installed
2573                       || !this->is_in_use();     // nmethod is installed, but not in 'in_use' state
2574   if (is_installed) {
2575     Thread *cur = Thread::current();
2576     if (CompiledIC_lock->owner() == cur ||
2577         ((cur->is_VM_thread() || cur->is_ConcurrentGC_thread()) &&
2578          SafepointSynchronize::is_at_safepoint())) {
2579       CompiledIC_at(this, call_site);
2580       CHECK_UNHANDLED_OOPS_ONLY(Thread::current()->clear_unhandled_oops());
2581     } else {
2582       MutexLocker ml_verify (CompiledIC_lock);
2583       CompiledIC_at(this, call_site);
2584     }
2585   }
2586 
2587   PcDesc* pd = pc_desc_at(nativeCall_at(call_site)->return_address());
2588   assert(pd != NULL, "PcDesc must exist");
2589   for (ScopeDesc* sd = new ScopeDesc(this, pd->scope_decode_offset(),
2590                                      pd->obj_decode_offset(), pd->should_reexecute(),
2591                                      pd->return_oop());
2592        !sd->is_top(); sd = sd->sender()) {
2593     sd->verify();
2594   }
2595 }
2596 
2597 void nmethod::verify_scopes() {
2598   if( !method() ) return;       // Runtime stubs have no scope
2599   if (method()->is_native()) return; // Ignore stub methods.
2600   // iterate through all interrupt point
2601   // and verify the debug information is valid.
2602   RelocIterator iter((nmethod*)this);
2603   while (iter.next()) {
2604     address stub = NULL;
2605     switch (iter.type()) {
2606       case relocInfo::virtual_call_type:
2607         verify_interrupt_point(iter.addr());
2608         break;
2609       case relocInfo::opt_virtual_call_type:
2610         stub = iter.opt_virtual_call_reloc()->static_stub();


2663   }
2664   assert(scavenge_root_not_marked(), "");
2665 }
2666 
2667 #endif // PRODUCT
2668 
2669 // Printing operations
2670 
2671 void nmethod::print() const {
2672   ResourceMark rm;
2673   ttyLocker ttyl;   // keep the following output all in one block
2674 
2675   tty->print("Compiled method ");
2676 
2677   if (is_compiled_by_c1()) {
2678     tty->print("(c1) ");
2679   } else if (is_compiled_by_c2()) {
2680     tty->print("(c2) ");
2681   } else if (is_compiled_by_shark()) {
2682     tty->print("(shark) ");


2683   } else {
2684     tty->print("(nm) ");
2685   }
2686 
2687   print_on(tty, NULL);
2688 
2689   if (WizardMode) {
2690     tty->print("((nmethod*) " INTPTR_FORMAT ") ", this);
2691     tty->print(" for method " INTPTR_FORMAT , (address)method());
2692     tty->print(" { ");
2693     if (is_in_use())      tty->print("in_use ");
2694     if (is_not_entrant()) tty->print("not_entrant ");
2695     if (is_zombie())      tty->print("zombie ");
2696     if (is_unloaded())    tty->print("unloaded ");
2697     if (on_scavenge_root_list())  tty->print("scavenge_root ");
2698     tty->print_cr("}:");
2699   }
2700   if (size              () > 0) tty->print_cr(" total in heap  [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
2701                                               (address)this,
2702                                               (address)this + size(),


2747                                               nul_chk_table_size());
2748 }
2749 
2750 void nmethod::print_code() {
2751   HandleMark hm;
2752   ResourceMark m;
2753   Disassembler::decode(this);
2754 }
2755 
2756 
2757 #ifndef PRODUCT
2758 
2759 void nmethod::print_scopes() {
2760   // Find the first pc desc for all scopes in the code and print it.
2761   ResourceMark rm;
2762   for (PcDesc* p = scopes_pcs_begin(); p < scopes_pcs_end(); p++) {
2763     if (p->scope_decode_offset() == DebugInformationRecorder::serialized_null)
2764       continue;
2765 
2766     ScopeDesc* sd = scope_desc_at(p->real_pc(this));

2767     sd->print_on(tty, p);


2768   }
2769 }
2770 
2771 void nmethod::print_dependencies() {
2772   ResourceMark rm;
2773   ttyLocker ttyl;   // keep the following output all in one block
2774   tty->print_cr("Dependencies:");
2775   for (Dependencies::DepStream deps(this); deps.next(); ) {
2776     deps.print_dependency();
2777     Klass* ctxk = deps.context_type();
2778     if (ctxk != NULL) {
2779       if (ctxk->oop_is_instance() && ((InstanceKlass*)ctxk)->is_dependent_nmethod(this)) {
2780         tty->print_cr("   [nmethod<=klass]%s", ctxk->external_name());
2781       }
2782     }
2783     deps.log_dependency();  // put it into the xml log also
2784   }
2785 }
2786 
2787 


2864         case relocInfo::virtual_call_type:     return "virtual_call";
2865         case relocInfo::opt_virtual_call_type: return "optimized virtual_call";
2866         case relocInfo::static_call_type:      return "static_call";
2867         case relocInfo::static_stub_type:      return "static_stub";
2868         case relocInfo::external_word_type:    return "external_word";
2869         case relocInfo::internal_word_type:    return "internal_word";
2870         case relocInfo::section_word_type:     return "section_word";
2871         case relocInfo::poll_type:             return "poll";
2872         case relocInfo::poll_return_type:      return "poll_return";
2873         case relocInfo::type_mask:             return "type_bit_mask";
2874     }
2875   }
2876   return have_one ? "other" : NULL;
2877 }
2878 
2879 // Return a the last scope in (begin..end]
2880 ScopeDesc* nmethod::scope_desc_in(address begin, address end) {
2881   PcDesc* p = pc_desc_near(begin+1);
2882   if (p != NULL && p->real_pc(this) <= end) {
2883     return new ScopeDesc(this, p->scope_decode_offset(),
2884                          p->obj_decode_offset(), p->should_reexecute(),
2885                          p->return_oop());
2886   }
2887   return NULL;
2888 }
2889 
2890 void nmethod::print_nmethod_labels(outputStream* stream, address block_begin) const {
2891   if (block_begin == entry_point())             stream->print_cr("[Entry Point]");
2892   if (block_begin == verified_entry_point())    stream->print_cr("[Verified Entry Point]");
2893   if (block_begin == exception_begin())         stream->print_cr("[Exception Handler]");
2894   if (block_begin == stub_begin())              stream->print_cr("[Stub Code]");
2895   if (block_begin == deopt_handler_begin())     stream->print_cr("[Deopt Handler Code]");
2896 
2897   if (has_method_handle_invokes())
2898     if (block_begin == deopt_mh_handler_begin())  stream->print_cr("[Deopt MH Handler Code]");
2899 
2900   if (block_begin == consts_begin())            stream->print_cr("[Constants]");
2901 
2902   if (block_begin == entry_point()) {
2903     methodHandle m = method();
2904     if (m.not_null()) {
2905       stream->print("  # ");
2906       m->print_value_on(stream);
2907       stream->cr();
2908     }
2909     if (m.not_null() && !is_osr_method()) {
2910       ResourceMark rm;
2911       int sizeargs = m->size_of_parameters();
2912       BasicType* sig_bt = NEW_RESOURCE_ARRAY(BasicType, sizeargs);
2913       VMRegPair* regs   = NEW_RESOURCE_ARRAY(VMRegPair, sizeargs);
2914       {
2915         int sig_index = 0;


3041             if (invoke.name() != NULL)
3042               invoke.name()->print_symbol_on(st);
3043             else
3044               st->print("<UNKNOWN>");
3045             break;
3046           }
3047         case Bytecodes::_getfield:
3048         case Bytecodes::_putfield:
3049         case Bytecodes::_getstatic:
3050         case Bytecodes::_putstatic:
3051           {
3052             Bytecode_field field(sd->method(), sd->bci());
3053             st->print(" ");
3054             if (field.name() != NULL)
3055               field.name()->print_symbol_on(st);
3056             else
3057               st->print("<UNKNOWN>");
3058           }
3059         }
3060       }

3061     }
3062 
3063     // Print all scopes
3064     for (;sd != NULL; sd = sd->sender()) {
3065       st->move_to(column);
3066       st->print("; -");
3067       if (sd->method() == NULL) {
3068         st->print("method is NULL");
3069       } else {
3070         sd->method()->print_short_name(st);
3071       }
3072       int lineno = sd->method()->line_number_from_bci(sd->bci());
3073       if (lineno != -1) {
3074         st->print("@%d (line %d)", sd->bci(), lineno);
3075       } else {
3076         st->print("@%d", sd->bci());
3077       }
3078       st->cr();
3079     }
3080   }


3113     }
3114     case relocInfo::static_call_type:
3115       st->print_cr("Static call at " INTPTR_FORMAT, iter.reloc()->addr());
3116       compiledStaticCall_at(iter.reloc())->print();
3117       break;
3118     }
3119   }
3120 }
3121 
3122 void nmethod::print_handler_table() {
3123   ExceptionHandlerTable(this).print();
3124 }
3125 
3126 void nmethod::print_nul_chk_table() {
3127   ImplicitExceptionTable(this).print(code_begin());
3128 }
3129 
3130 void nmethod::print_statistics() {
3131   ttyLocker ttyl;
3132   if (xtty != NULL)  xtty->head("statistics type='nmethod'");
3133   nmethod_stats.print_native_nmethod_stats();
3134   nmethod_stats.print_nmethod_stats();












3135   DebugInformationRecorder::print_statistics();
3136   nmethod_stats.print_pc_stats();


3137   Dependencies::print_statistics();
3138   if (xtty != NULL)  xtty->tail("statistics");
3139 }
3140 
3141 #endif // PRODUCT

























   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/nativeInst.hpp"
  30 #include "code/nmethod.hpp"
  31 #include "code/scopeDesc.hpp"
  32 #include "compiler/abstractCompiler.hpp"
  33 #include "compiler/compileBroker.hpp"
  34 #include "compiler/compileLog.hpp"
  35 #include "compiler/compilerOracle.hpp"
  36 #include "compiler/disassembler.hpp"
  37 #include "interpreter/bytecode.hpp"
  38 #include "oops/methodData.hpp"
  39 #include "oops/oop.inline.hpp"
  40 #include "prims/jvmtiRedefineClassesTrace.hpp"
  41 #include "prims/jvmtiImpl.hpp"
  42 #include "runtime/atomic.inline.hpp"
  43 #include "runtime/orderAccess.inline.hpp"
  44 #include "runtime/sharedRuntime.hpp"
  45 #include "runtime/sweeper.hpp"
  46 #include "utilities/resourceHash.hpp"
  47 #include "utilities/dtrace.hpp"
  48 #include "utilities/events.hpp"
  49 #include "utilities/xmlstream.hpp"
  50 #ifdef TARGET_ARCH_x86
  51 # include "nativeInst_x86.hpp"
  52 #endif
  53 #ifdef TARGET_ARCH_sparc
  54 # include "nativeInst_sparc.hpp"
  55 #endif
  56 #ifdef TARGET_ARCH_zero
  57 # include "nativeInst_zero.hpp"
  58 #endif
  59 #ifdef TARGET_ARCH_arm
  60 # include "nativeInst_arm.hpp"
  61 #endif
  62 #ifdef TARGET_ARCH_ppc
  63 # include "nativeInst_ppc.hpp"
  64 #endif
  65 #ifdef SHARK
  66 #include "shark/sharkCompiler.hpp"
  67 #endif
  68 #if INCLUDE_JVMCI
  69 #include "jvmci/jvmciJavaClasses.hpp"
  70 #endif
  71 
  72 PRAGMA_FORMAT_MUTE_WARNINGS_FOR_GCC
  73 
  74 unsigned char nmethod::_global_unloading_clock = 0;
  75 
  76 #ifdef DTRACE_ENABLED
  77 
  78 // Only bother with this argument setup if dtrace is available
  79 
  80 #define DTRACE_METHOD_UNLOAD_PROBE(method)                                \
  81   {                                                                       \
  82     Method* m = (method);                                                 \
  83     if (m != NULL) {                                                      \
  84       Symbol* klass_name = m->klass_name();                               \
  85       Symbol* name = m->name();                                           \
  86       Symbol* signature = m->signature();                                 \
  87       HOTSPOT_COMPILED_METHOD_UNLOAD(                                     \
  88         (char *) klass_name->bytes(), klass_name->utf8_length(),                   \
  89         (char *) name->bytes(), name->utf8_length(),                               \
  90         (char *) signature->bytes(), signature->utf8_length());                    \
  91     }                                                                     \
  92   }
  93 
  94 #else //  ndef DTRACE_ENABLED
  95 
  96 #define DTRACE_METHOD_UNLOAD_PROBE(method)
  97 
  98 #endif
  99 
 100 bool nmethod::is_compiled_by_c1() const {
 101   if (compiler() == NULL) {
 102     return false;
 103   }
 104   return compiler()->is_c1();
 105 }
 106 bool nmethod::is_compiled_by_jvmci() const {
 107   if (compiler() == NULL || method() == NULL)  return false;  // can happen during debug printing
 108   if (is_native_method()) return false;
 109   return compiler()->is_jvmci();
 110 }
 111 bool nmethod::is_compiled_by_c2() const {
 112   if (compiler() == NULL) {
 113     return false;
 114   }
 115   return compiler()->is_c2();
 116 }
 117 bool nmethod::is_compiled_by_shark() const {
 118   if (compiler() == NULL) {
 119     return false;
 120   }
 121   return compiler()->is_shark();
 122 }
 123 
 124 
 125 
 126 //---------------------------------------------------------------------------------
 127 // NMethod statistics
 128 // They are printed under various flags, including:
 129 //   PrintC1Statistics, PrintOptoStatistics, LogVMOutput, and LogCompilation.
 130 // (In the latter two cases, they like other stats are printed to the log only.)
 131 
 132 #ifndef PRODUCT
 133 // These variables are put into one block to reduce relocations
 134 // and make it simpler to print from the debugger.
 135 struct java_nmethod_stats_struct {

 136   int nmethod_count;
 137   int total_size;
 138   int relocation_size;
 139   int consts_size;
 140   int insts_size;
 141   int stub_size;
 142   int scopes_data_size;
 143   int scopes_pcs_size;
 144   int dependencies_size;
 145   int handler_table_size;
 146   int nul_chk_table_size;
 147   int oops_size;
 148   int metadata_size;
 149 
 150   void note_nmethod(nmethod* nm) {
 151     nmethod_count += 1;
 152     total_size          += nm->size();
 153     relocation_size     += nm->relocation_size();
 154     consts_size         += nm->consts_size();
 155     insts_size          += nm->insts_size();
 156     stub_size           += nm->stub_size();
 157     oops_size           += nm->oops_size();
 158     metadata_size       += nm->metadata_size();
 159     scopes_data_size    += nm->scopes_data_size();
 160     scopes_pcs_size     += nm->scopes_pcs_size();
 161     dependencies_size   += nm->dependencies_size();
 162     handler_table_size  += nm->handler_table_size();
 163     nul_chk_table_size  += nm->nul_chk_table_size();
 164   }
 165   void print_nmethod_stats(const char* name) {
 166     if (nmethod_count == 0)  return;
 167     tty->print_cr("Statistics for %d bytecoded nmethods for %s:", nmethod_count, name);
 168     if (total_size != 0)          tty->print_cr(" total in heap  = %d", total_size);
 169     if (nmethod_count != 0)       tty->print_cr(" header         = %d", nmethod_count * sizeof(nmethod));
 170     if (relocation_size != 0)     tty->print_cr(" relocation     = %d", relocation_size);
 171     if (consts_size != 0)         tty->print_cr(" constants      = %d", consts_size);
 172     if (insts_size != 0)          tty->print_cr(" main code      = %d", insts_size);
 173     if (stub_size != 0)           tty->print_cr(" stub code      = %d", stub_size);
 174     if (oops_size != 0)           tty->print_cr(" oops           = %d", oops_size);
 175     if (metadata_size != 0)       tty->print_cr(" metadata       = %d", metadata_size);
 176     if (scopes_data_size != 0)    tty->print_cr(" scopes data    = %d", scopes_data_size);
 177     if (scopes_pcs_size != 0)     tty->print_cr(" scopes pcs     = %d", scopes_pcs_size);
 178     if (dependencies_size != 0)   tty->print_cr(" dependencies   = %d", dependencies_size);
 179     if (handler_table_size != 0)  tty->print_cr(" handler table  = %d", handler_table_size);
 180     if (nul_chk_table_size != 0)  tty->print_cr(" nul chk table  = %d", nul_chk_table_size);
 181   }
 182 };
 183 
 184 struct native_nmethod_stats_struct {
 185   int native_nmethod_count;
 186   int native_total_size;
 187   int native_relocation_size;
 188   int native_insts_size;
 189   int native_oops_size;
 190   int native_metadata_size;
 191   void note_native_nmethod(nmethod* nm) {
 192     native_nmethod_count += 1;
 193     native_total_size       += nm->size();
 194     native_relocation_size  += nm->relocation_size();
 195     native_insts_size       += nm->insts_size();
 196     native_oops_size        += nm->oops_size();
 197     native_metadata_size    += nm->metadata_size();
 198   }
 199   void print_native_nmethod_stats() {
 200     if (native_nmethod_count == 0)  return;
 201     tty->print_cr("Statistics for %d native nmethods:", native_nmethod_count);
 202     if (native_total_size != 0)       tty->print_cr(" N. total size  = %d", native_total_size);
 203     if (native_relocation_size != 0)  tty->print_cr(" N. relocation  = %d", native_relocation_size);
 204     if (native_insts_size != 0)       tty->print_cr(" N. main code   = %d", native_insts_size);
 205     if (native_oops_size != 0)        tty->print_cr(" N. oops        = %d", native_oops_size);
 206     if (native_metadata_size != 0)    tty->print_cr(" N. metadata    = %d", native_metadata_size);
 207   }
 208 };
 209 
 210 struct pc_nmethod_stats_struct {
 211   int pc_desc_resets;   // number of resets (= number of caches)
 212   int pc_desc_queries;  // queries to nmethod::find_pc_desc
 213   int pc_desc_approx;   // number of those which have approximate true
 214   int pc_desc_repeats;  // number of _pc_descs[0] hits
 215   int pc_desc_hits;     // number of LRU cache hits
 216   int pc_desc_tests;    // total number of PcDesc examinations
 217   int pc_desc_searches; // total number of quasi-binary search steps
 218   int pc_desc_adds;     // number of LUR cache insertions
 219 
 220   void print_pc_stats() {
 221     tty->print_cr("PcDesc Statistics:  %d queries, %.2f comparisons per query",
 222                   pc_desc_queries,
 223                   (double)(pc_desc_tests + pc_desc_searches)
 224                   / pc_desc_queries);
 225     tty->print_cr("  caches=%d queries=%d/%d, hits=%d+%d, tests=%d+%d, adds=%d",
 226                   pc_desc_resets,
 227                   pc_desc_queries, pc_desc_approx,
 228                   pc_desc_repeats, pc_desc_hits,
 229                   pc_desc_tests, pc_desc_searches, pc_desc_adds);
 230   }
 231 };

 232 
 233 #ifdef COMPILER1
 234 static java_nmethod_stats_struct c1_java_nmethod_stats;
 235 #endif
 236 #ifdef COMPILER2
 237 static java_nmethod_stats_struct c2_java_nmethod_stats;
 238 #endif
 239 #if INCLUDE_JVMCI
 240 static java_nmethod_stats_struct jvmci_java_nmethod_stats;
 241 #endif
 242 #ifdef SHARK
 243 static java_nmethod_stats_struct shark_java_nmethod_stats;
 244 #endif
 245 static java_nmethod_stats_struct unknown_java_nmethod_stats;
 246 
 247 static native_nmethod_stats_struct native_nmethod_stats;
 248 static pc_nmethod_stats_struct pc_nmethod_stats;
 249 
 250 static void note_java_nmethod(nmethod* nm) {
 251 #ifdef COMPILER1
 252   if (nm->is_compiled_by_c1()) {
 253     c1_java_nmethod_stats.note_nmethod(nm);
 254   } else
 255 #endif
 256 #ifdef COMPILER2
 257   if (nm->is_compiled_by_c2()) {
 258     c2_java_nmethod_stats.note_nmethod(nm);
 259   } else
 260 #endif
 261 #if INCLUDE_JVMCI
 262   if (nm->is_compiled_by_jvmci()) {
 263     jvmci_java_nmethod_stats.note_nmethod(nm);
 264   } else
 265 #endif
 266 #ifdef SHARK
 267   if (nm->is_compiled_by_shark()) {
 268     shark_java_nmethod_stats.note_nmethod(nm);
 269   } else
 270 #endif
 271   {
 272     unknown_java_nmethod_stats.note_nmethod(nm);
 273   }
 274 }
 275 #endif // !PRODUCT
 276 
 277 //---------------------------------------------------------------------------------
 278 
 279 
 280 ExceptionCache::ExceptionCache(Handle exception, address pc, address handler) {
 281   assert(pc != NULL, "Must be non null");
 282   assert(exception.not_null(), "Must be non null");
 283   assert(handler != NULL, "Must be non null");
 284 
 285   _count = 0;
 286   _exception_type = exception->klass();
 287   _next = NULL;
 288 
 289   add_address_and_handler(pc,handler);
 290 }
 291 
 292 
 293 address ExceptionCache::match(Handle exception, address pc) {
 294   assert(pc != NULL,"Must be non null");
 295   assert(exception.not_null(),"Must be non null");


 335 // private method for handling exception cache
 336 // These methods are private, and used to manipulate the exception cache
 337 // directly.
 338 ExceptionCache* nmethod::exception_cache_entry_for_exception(Handle exception) {
 339   ExceptionCache* ec = exception_cache();
 340   while (ec != NULL) {
 341     if (ec->match_exception_with_space(exception)) {
 342       return ec;
 343     }
 344     ec = ec->next();
 345   }
 346   return NULL;
 347 }
 348 
 349 
 350 //-----------------------------------------------------------------------------
 351 
 352 
 353 // Helper used by both find_pc_desc methods.
 354 static inline bool match_desc(PcDesc* pc, int pc_offset, bool approximate) {
 355   NOT_PRODUCT(++pc_nmethod_stats.pc_desc_tests);
 356   if (!approximate)
 357     return pc->pc_offset() == pc_offset;
 358   else
 359     return (pc-1)->pc_offset() < pc_offset && pc_offset <= pc->pc_offset();
 360 }
 361 
 362 void PcDescCache::reset_to(PcDesc* initial_pc_desc) {
 363   if (initial_pc_desc == NULL) {
 364     _pc_descs[0] = NULL; // native method; no PcDescs at all
 365     return;
 366   }
 367   NOT_PRODUCT(++pc_nmethod_stats.pc_desc_resets);
 368   // reset the cache by filling it with benign (non-null) values
 369   assert(initial_pc_desc->pc_offset() < 0, "must be sentinel");
 370   for (int i = 0; i < cache_size; i++)
 371     _pc_descs[i] = initial_pc_desc;
 372 }
 373 
 374 PcDesc* PcDescCache::find_pc_desc(int pc_offset, bool approximate) {
 375   NOT_PRODUCT(++pc_nmethod_stats.pc_desc_queries);
 376   NOT_PRODUCT(if (approximate) ++pc_nmethod_stats.pc_desc_approx);
 377 
 378   // Note: one might think that caching the most recently
 379   // read value separately would be a win, but one would be
 380   // wrong.  When many threads are updating it, the cache
 381   // line it's in would bounce between caches, negating
 382   // any benefit.
 383 
 384   // In order to prevent race conditions do not load cache elements
 385   // repeatedly, but use a local copy:
 386   PcDesc* res;
 387 
 388   // Step one:  Check the most recently added value.
 389   res = _pc_descs[0];
 390   if (res == NULL) return NULL;  // native method; no PcDescs at all
 391   if (match_desc(res, pc_offset, approximate)) {
 392     NOT_PRODUCT(++pc_nmethod_stats.pc_desc_repeats);
 393     return res;
 394   }
 395 
 396   // Step two:  Check the rest of the LRU cache.
 397   for (int i = 1; i < cache_size; ++i) {
 398     res = _pc_descs[i];
 399     if (res->pc_offset() < 0) break;  // optimization: skip empty cache
 400     if (match_desc(res, pc_offset, approximate)) {
 401       NOT_PRODUCT(++pc_nmethod_stats.pc_desc_hits);
 402       return res;
 403     }
 404   }
 405 
 406   // Report failure.
 407   return NULL;
 408 }
 409 
 410 void PcDescCache::add_pc_desc(PcDesc* pc_desc) {
 411   NOT_PRODUCT(++pc_nmethod_stats.pc_desc_adds);
 412   // Update the LRU cache by shifting pc_desc forward.
 413   for (int i = 0; i < cache_size; i++)  {
 414     PcDesc* next = _pc_descs[i];
 415     _pc_descs[i] = pc_desc;
 416     pc_desc = next;
 417   }
 418 }
 419 
 420 // adjust pcs_size so that it is a multiple of both oopSize and
 421 // sizeof(PcDesc) (assumes that if sizeof(PcDesc) is not a multiple
 422 // of oopSize, then 2*sizeof(PcDesc) is)
 423 static int adjust_pcs_size(int pcs_size) {
 424   int nsize = round_to(pcs_size,   oopSize);
 425   if ((nsize % sizeof(PcDesc)) != 0) {
 426     nsize = pcs_size + sizeof(PcDesc);
 427   }
 428   assert((nsize % oopSize) == 0, "correct alignment");
 429   return nsize;
 430 }
 431 


 537   _stack_traversal_mark       = 0;
 538   _unload_reported            = false; // jvmti state
 539 
 540 #ifdef ASSERT
 541   _oops_are_stale             = false;
 542 #endif
 543 
 544   _oops_do_mark_link       = NULL;
 545   _jmethod_id              = NULL;
 546   _osr_link                = NULL;
 547   if (UseG1GC) {
 548     _unloading_next        = NULL;
 549   } else {
 550     _scavenge_root_link    = NULL;
 551   }
 552   _scavenge_root_state     = 0;
 553   _compiler                = NULL;
 554 #if INCLUDE_RTM_OPT
 555   _rtm_state               = NoRTM;
 556 #endif
 557 #if INCLUDE_JVMCI
 558   _jvmci_installed_code   = NULL;
 559   _speculation_log        = NULL;
 560 #endif
 561 }
 562 
 563 nmethod* nmethod::new_native_nmethod(methodHandle method,
 564   int compile_id,
 565   CodeBuffer *code_buffer,
 566   int vep_offset,
 567   int frame_complete,
 568   int frame_size,
 569   ByteSize basic_lock_owner_sp_offset,
 570   ByteSize basic_lock_sp_offset,
 571   OopMapSet* oop_maps) {
 572   code_buffer->finalize_oop_references(method);
 573   // create nmethod
 574   nmethod* nm = NULL;
 575   {
 576     MutexLockerEx mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
 577     int native_nmethod_size = allocation_size(code_buffer, sizeof(nmethod));
 578     CodeOffsets offsets;
 579     offsets.set_value(CodeOffsets::Verified_Entry, vep_offset);
 580     offsets.set_value(CodeOffsets::Frame_Complete, frame_complete);
 581     nm = new (native_nmethod_size, CompLevel_none) nmethod(method(), native_nmethod_size,
 582                                             compile_id, &offsets,
 583                                             code_buffer, frame_size,
 584                                             basic_lock_owner_sp_offset,
 585                                             basic_lock_sp_offset, oop_maps);
 586     NOT_PRODUCT(if (nm != NULL)  native_nmethod_stats.note_native_nmethod(nm));
 587     if ((PrintAssembly || CompilerOracle::should_print(method)) && nm != NULL) {
 588       Disassembler::decode(nm);
 589     }
 590   }
 591   // verify nmethod
 592   debug_only(if (nm) nm->verify();) // might block
 593 
 594   if (nm != NULL) {
 595     nm->log_new_nmethod();
 596   }
 597 
 598   return nm;
 599 }
 600 
 601 nmethod* nmethod::new_nmethod(methodHandle method,
 602   int compile_id,
 603   int entry_bci,
 604   CodeOffsets* offsets,
 605   int orig_pc_offset,
 606   DebugInformationRecorder* debug_info,
 607   Dependencies* dependencies,
 608   CodeBuffer* code_buffer, int frame_size,
 609   OopMapSet* oop_maps,
 610   ExceptionHandlerTable* handler_table,
 611   ImplicitExceptionTable* nul_chk_table,
 612   AbstractCompiler* compiler,
 613   int comp_level
 614 #if INCLUDE_JVMCI
 615   , Handle installed_code,
 616   Handle speculationLog
 617 #endif
 618 )
 619 {
 620   assert(debug_info->oop_recorder() == code_buffer->oop_recorder(), "shared OR");
 621   code_buffer->finalize_oop_references(method);
 622   // create nmethod
 623   nmethod* nm = NULL;
 624   { MutexLockerEx mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
 625     int nmethod_size =
 626       allocation_size(code_buffer, sizeof(nmethod))
 627       + adjust_pcs_size(debug_info->pcs_size())
 628       + round_to(dependencies->size_in_bytes() , oopSize)
 629       + round_to(handler_table->size_in_bytes(), oopSize)
 630       + round_to(nul_chk_table->size_in_bytes(), oopSize)
 631       + round_to(debug_info->data_size()       , oopSize);
 632 
 633     nm = new (nmethod_size, comp_level)
 634     nmethod(method(), nmethod_size, compile_id, entry_bci, offsets,
 635             orig_pc_offset, debug_info, dependencies, code_buffer, frame_size,
 636             oop_maps,
 637             handler_table,
 638             nul_chk_table,
 639             compiler,
 640             comp_level
 641 #if INCLUDE_JVMCI
 642             , installed_code,
 643             speculationLog
 644 #endif
 645             );
 646 
 647     if (nm != NULL) {
 648       // To make dependency checking during class loading fast, record
 649       // the nmethod dependencies in the classes it is dependent on.
 650       // This allows the dependency checking code to simply walk the
 651       // class hierarchy above the loaded class, checking only nmethods
 652       // which are dependent on those classes.  The slow way is to
 653       // check every nmethod for dependencies which makes it linear in
 654       // the number of methods compiled.  For applications with a lot
 655       // classes the slow way is too slow.
 656       for (Dependencies::DepStream deps(nm); deps.next(); ) {
 657         if (deps.type() == Dependencies::call_site_target_value) {
 658           // CallSite dependencies are managed on per-CallSite instance basis.
 659           oop call_site = deps.argument_oop(0);
 660           MethodHandles::add_dependent_nmethod(call_site, nm);
 661         } else {
 662           Klass* klass = deps.context_type();
 663           if (klass == NULL) {
 664             continue;  // ignore things like evol_method
 665           }
 666           // record this nmethod as dependent on this klass
 667           InstanceKlass::cast(klass)->add_dependent_nmethod(nm);
 668         }
 669       }
 670       NOT_PRODUCT(if (nm != NULL)  note_java_nmethod(nm));
 671       if (PrintAssembly || CompilerOracle::has_option_string(method, "PrintAssembly")) {
 672         Disassembler::decode(nm);
 673       }
 674     }
 675   }
 676   // Do verification and logging outside CodeCache_lock.
 677   if (nm != NULL) {
 678     // Safepoints in nmethod::verify aren't allowed because nm hasn't been installed yet.
 679     DEBUG_ONLY(nm->verify();)
 680     nm->log_new_nmethod();
 681   }
 682   return nm;
 683 }
 684 
 685 #ifdef _MSC_VER
 686 #pragma warning(push)
 687 #pragma warning(disable:4355) //  warning C4355: 'this' : used in base member initializer list
 688 #endif
 689 // For native wrappers
 690 nmethod::nmethod(
 691   Method* method,
 692   int nmethod_size,
 693   int compile_id,
 694   CodeOffsets* offsets,
 695   CodeBuffer* code_buffer,
 696   int frame_size,
 697   ByteSize basic_lock_owner_sp_offset,
 698   ByteSize basic_lock_sp_offset,
 699   OopMapSet* oop_maps )
 700   : CodeBlob("native nmethod", code_buffer, sizeof(nmethod),
 701              nmethod_size, offsets->value(CodeOffsets::Frame_Complete), frame_size, oop_maps),
 702   _native_receiver_sp_offset(basic_lock_owner_sp_offset),
 703   _native_basic_lock_sp_offset(basic_lock_sp_offset)
 704 {
 705   {
 706     debug_only(No_Safepoint_Verifier nsv;)
 707     assert_locked_or_safepoint(CodeCache_lock);
 708 


 758       xtty->end_head(" address='" INTPTR_FORMAT "'", (intptr_t) this);
 759     }
 760     // print the header part first
 761     print();
 762     // then print the requested information
 763     if (PrintNativeNMethods) {
 764       print_code();
 765       if (oop_maps != NULL) {
 766         oop_maps->print();
 767       }
 768     }
 769     if (PrintRelocations) {
 770       print_relocations();
 771     }
 772     if (xtty != NULL) {
 773       xtty->tail("print_native_nmethod");
 774     }
 775   }
 776 }
 777 
 778 #ifdef _MSC_VER
 779 #pragma warning(pop)
 780 #endif
 781 
 782 void* nmethod::operator new(size_t size, int nmethod_size, int comp_level) throw () {
 783   return CodeCache::allocate(nmethod_size, CodeCache::get_code_blob_type(comp_level));
 784 }
 785 
 786 nmethod::nmethod(
 787   Method* method,
 788   int nmethod_size,
 789   int compile_id,
 790   int entry_bci,
 791   CodeOffsets* offsets,
 792   int orig_pc_offset,
 793   DebugInformationRecorder* debug_info,
 794   Dependencies* dependencies,
 795   CodeBuffer *code_buffer,
 796   int frame_size,
 797   OopMapSet* oop_maps,
 798   ExceptionHandlerTable* handler_table,
 799   ImplicitExceptionTable* nul_chk_table,
 800   AbstractCompiler* compiler,
 801   int comp_level
 802 #if INCLUDE_JVMCI
 803   , Handle installed_code,
 804   Handle speculation_log
 805 #endif
 806   )
 807   : CodeBlob("nmethod", code_buffer, sizeof(nmethod),
 808              nmethod_size, offsets->value(CodeOffsets::Frame_Complete), frame_size, oop_maps),
 809   _native_receiver_sp_offset(in_ByteSize(-1)),
 810   _native_basic_lock_sp_offset(in_ByteSize(-1))
 811 {
 812   assert(debug_info->oop_recorder() == code_buffer->oop_recorder(), "shared OR");
 813   {
 814     debug_only(No_Safepoint_Verifier nsv;)
 815     assert_locked_or_safepoint(CodeCache_lock);
 816 
 817     init_defaults();
 818     _method                  = method;
 819     _entry_bci               = entry_bci;
 820     _compile_id              = compile_id;
 821     _comp_level              = comp_level;
 822     _compiler                = compiler;
 823     _orig_pc_offset          = orig_pc_offset;
 824     _hotness_counter         = NMethodSweeper::hotness_counter_reset_val();
 825 
 826     // Section offsets
 827     _consts_offset           = content_offset()      + code_buffer->total_offset_of(code_buffer->consts());
 828     _stub_offset             = content_offset()      + code_buffer->total_offset_of(code_buffer->stubs());
 829 
 830 #if INCLUDE_JVMCI
 831     _jvmci_installed_code = installed_code();
 832     _speculation_log = (instanceOop)speculation_log();
 833 
 834     if (compiler->is_jvmci()) {
 835       // JVMCI might not produce any stub sections
 836       if (offsets->value(CodeOffsets::Exceptions) != -1) {
 837         _exception_offset        = code_offset()          + offsets->value(CodeOffsets::Exceptions);
 838       } else {
 839         _exception_offset = -1;
 840       }
 841       if (offsets->value(CodeOffsets::Deopt) != -1) {
 842         _deoptimize_offset       = code_offset()          + offsets->value(CodeOffsets::Deopt);
 843       } else {
 844         _deoptimize_offset = -1;
 845       }
 846       if (offsets->value(CodeOffsets::DeoptMH) != -1) {
 847         _deoptimize_mh_offset  = code_offset()          + offsets->value(CodeOffsets::DeoptMH);
 848       } else {
 849         _deoptimize_mh_offset  = -1;
 850       }
 851     } else {
 852 #endif
 853     // Exception handler and deopt handler are in the stub section
 854     assert(offsets->value(CodeOffsets::Exceptions) != -1, "must be set");
 855     assert(offsets->value(CodeOffsets::Deopt     ) != -1, "must be set");
 856 
 857     _exception_offset        = _stub_offset          + offsets->value(CodeOffsets::Exceptions);
 858     _deoptimize_offset       = _stub_offset          + offsets->value(CodeOffsets::Deopt);
 859     if (offsets->value(CodeOffsets::DeoptMH) != -1) {
 860       _deoptimize_mh_offset  = _stub_offset          + offsets->value(CodeOffsets::DeoptMH);
 861     } else {
 862       _deoptimize_mh_offset  = -1;
 863 #if INCLUDE_JVMCI
 864     }
 865 #endif
 866     }
 867     if (offsets->value(CodeOffsets::UnwindHandler) != -1) {
 868       _unwind_handler_offset = code_offset()         + offsets->value(CodeOffsets::UnwindHandler);
 869     } else {
 870       _unwind_handler_offset = -1;
 871     }
 872 
 873     _oops_offset             = data_offset();
 874     _metadata_offset         = _oops_offset          + round_to(code_buffer->total_oop_size(), oopSize);
 875     _scopes_data_offset      = _metadata_offset      + round_to(code_buffer->total_metadata_size(), wordSize);
 876 
 877     _scopes_pcs_offset       = _scopes_data_offset   + round_to(debug_info->data_size       (), oopSize);
 878     _dependencies_offset     = _scopes_pcs_offset    + adjust_pcs_size(debug_info->pcs_size());
 879     _handler_table_offset    = _dependencies_offset  + round_to(dependencies->size_in_bytes (), oopSize);
 880     _nul_chk_table_offset    = _handler_table_offset + round_to(handler_table->size_in_bytes(), oopSize);
 881     _nmethod_end_offset      = _nul_chk_table_offset + round_to(nul_chk_table->size_in_bytes(), oopSize);
 882 
 883     _entry_point             = code_begin()          + offsets->value(CodeOffsets::Entry);
 884     _verified_entry_point    = code_begin()          + offsets->value(CodeOffsets::Verified_Entry);
 885     _osr_entry_point         = code_begin()          + offsets->value(CodeOffsets::OSR_Entry);


 889     // Copy contents of ScopeDescRecorder to nmethod
 890     code_buffer->copy_values_to(this);
 891     debug_info->copy_to(this);
 892     dependencies->copy_to(this);
 893     if (ScavengeRootsInCode) {
 894       if (detect_scavenge_root_oops()) {
 895         CodeCache::add_scavenge_root_nmethod(this);
 896       }
 897       Universe::heap()->register_nmethod(this);
 898     }
 899     debug_only(verify_scavenge_root_oops());
 900 
 901     CodeCache::commit(this);
 902 
 903     // Copy contents of ExceptionHandlerTable to nmethod
 904     handler_table->copy_to(this);
 905     nul_chk_table->copy_to(this);
 906 
 907     // we use the information of entry points to find out if a method is
 908     // static or non static
 909     assert(compiler->is_c2() || compiler->is_jvmci() ||
 910            _method->is_static() == (entry_point() == _verified_entry_point),
 911            " entry points must be same for static methods and vice versa");
 912   }
 913 
 914   bool printnmethods = PrintNMethods || PrintNMethodsAtLevel == _comp_level
 915     || CompilerOracle::should_print(_method)
 916     || CompilerOracle::has_option_string(_method, "PrintNMethods");
 917   if (printnmethods || PrintDebugInfo || PrintRelocations || PrintDependencies || PrintExceptionHandlers) {
 918     print_nmethod(printnmethods);
 919   }
 920 }
 921 

 922 // Print a short set of xml attributes to identify this nmethod.  The
 923 // output should be embedded in some other element.
 924 void nmethod::log_identity(xmlStream* log) const {
 925   log->print(" compile_id='%d'", compile_id());
 926   const char* nm_kind = compile_kind();
 927   if (nm_kind != NULL)  log->print(" compile_kind='%s'", nm_kind);
 928   if (compiler() != NULL) {
 929     log->print(" compiler='%s'", compiler()->name());
 930   }
 931   if (TieredCompilation) {
 932     log->print(" level='%d'", comp_level());
 933   }
 934 }
 935 
 936 
 937 #define LOG_OFFSET(log, name)                    \
 938   if ((intptr_t)name##_end() - (intptr_t)name##_begin()) \
 939     log->print(" " XSTR(name) "_offset='%d'"    , \
 940                (intptr_t)name##_begin() - (intptr_t)this)
 941 
 942 
 943 void nmethod::log_new_nmethod() const {
 944   if (LogCompilation && xtty != NULL) {
 945     ttyLocker ttyl;
 946     HandleMark hm;
 947     xtty->begin_elem("nmethod");
 948     log_identity(xtty);
 949     xtty->print(" entry='" INTPTR_FORMAT "' size='%d'", code_begin(), size());
 950     xtty->print(" address='" INTPTR_FORMAT "'", (intptr_t) this);
 951 
 952     LOG_OFFSET(xtty, relocation);
 953     LOG_OFFSET(xtty, consts);
 954     LOG_OFFSET(xtty, insts);
 955     LOG_OFFSET(xtty, stub);
 956     LOG_OFFSET(xtty, scopes_data);
 957     LOG_OFFSET(xtty, scopes_pcs);
 958     LOG_OFFSET(xtty, dependencies);
 959     LOG_OFFSET(xtty, handler_table);
 960     LOG_OFFSET(xtty, nul_chk_table);
 961     LOG_OFFSET(xtty, oops);
 962     LOG_OFFSET(xtty, metadata);
 963 
 964     xtty->method(method());
 965     xtty->stamp();
 966     xtty->end_elem();
 967   }
 968 }
 969 
 970 #undef LOG_OFFSET
 971 
 972 
 973 // Print out more verbose output usually for a newly created nmethod.
 974 void nmethod::print_on(outputStream* st, const char* msg) const {
 975   if (st != NULL) {
 976     ttyLocker ttyl;
 977     if (WizardMode) {
 978       CompileTask::print_compilation(st, this, msg, /*short_form:*/ true);
 979       st->print_cr(" (" INTPTR_FORMAT ")", this);
 980     } else {
 981       CompileTask::print_compilation(st, this, msg, /*short_form:*/ false);
 982     }


 984 }
 985 
 986 
 987 void nmethod::print_nmethod(bool printmethod) {
 988   ttyLocker ttyl;  // keep the following output all in one block
 989   if (xtty != NULL) {
 990     xtty->begin_head("print_nmethod");
 991     xtty->stamp();
 992     xtty->end_head();
 993   }
 994   // print the header part first
 995   print();
 996   // then print the requested information
 997   if (printmethod) {
 998     print_code();
 999     print_pcs();
1000     if (oop_maps()) {
1001       oop_maps()->print();
1002     }
1003   }
1004   if (PrintDebugInfo || CompilerOracle::has_option_string(_method, "PrintDebugInfo")) {
1005     print_scopes();
1006   }
1007   if (PrintRelocations || CompilerOracle::has_option_string(_method, "PrintRelocations")) {
1008     print_relocations();
1009   }
1010   if (PrintDependencies || CompilerOracle::has_option_string(_method, "PrintDependencies")) {
1011     print_dependencies();
1012   }
1013   if (PrintExceptionHandlers) {
1014     print_handler_table();
1015     print_nul_chk_table();
1016   }
1017   if (xtty != NULL) {
1018     xtty->tail("print_nmethod");
1019   }
1020 }
1021 
1022 
1023 // Promote one word from an assembly-time handle to a live embedded oop.
1024 inline void nmethod::initialize_immediate_oop(oop* dest, jobject handle) {
1025   if (handle == NULL ||
1026       // As a special case, IC oops are initialized to 1 or -1.
1027       handle == (jobject) Universe::non_oop_word()) {
1028     (*dest) = (oop) handle;
1029   } else {
1030     (*dest) = JNIHandles::resolve_non_null(handle);


1100 
1101 
1102 void nmethod::verify_oop_relocations() {
1103   // Ensure sure that the code matches the current oop values
1104   RelocIterator iter(this, NULL, NULL);
1105   while (iter.next()) {
1106     if (iter.type() == relocInfo::oop_type) {
1107       oop_Relocation* reloc = iter.oop_reloc();
1108       if (!reloc->oop_is_immediate()) {
1109         reloc->verify_oop_relocation();
1110       }
1111     }
1112   }
1113 }
1114 
1115 
1116 ScopeDesc* nmethod::scope_desc_at(address pc) {
1117   PcDesc* pd = pc_desc_at(pc);
1118   guarantee(pd != NULL, "scope must be present");
1119   return new ScopeDesc(this, pd->scope_decode_offset(),
1120                        pd->obj_decode_offset(), pd->should_reexecute(), pd->rethrow_exception(),
1121                        pd->return_oop());
1122 }
1123 
1124 
1125 void nmethod::clear_inline_caches() {
1126   assert(SafepointSynchronize::is_at_safepoint(), "cleaning of IC's only allowed at safepoint");
1127   if (is_zombie()) {
1128     return;
1129   }
1130 
1131   RelocIterator iter(this);
1132   while (iter.next()) {
1133     iter.reloc()->clear_inline_cache();
1134   }
1135 }
1136 
1137 // Clear ICStubs of all compiled ICs
1138 void nmethod::clear_ic_stubs() {
1139   assert_locked_or_safepoint(CompiledIC_lock);
1140   RelocIterator iter(this);


1271   assert(is_alive(), "Must be an alive method");
1272   // Set the traversal mark to ensure that the sweeper does 2
1273   // cleaning passes before moving to zombie.
1274   set_stack_traversal_mark(NMethodSweeper::traversal_count());
1275 }
1276 
1277 // Tell if a non-entrant method can be converted to a zombie (i.e.,
1278 // there are no activations on the stack, not in use by the VM,
1279 // and not in use by the ServiceThread)
1280 bool nmethod::can_not_entrant_be_converted() {
1281   assert(is_not_entrant(), "must be a non-entrant method");
1282 
1283   // Since the nmethod sweeper only does partial sweep the sweeper's traversal
1284   // count can be greater than the stack traversal count before it hits the
1285   // nmethod for the second time.
1286   return stack_traversal_mark()+1 < NMethodSweeper::traversal_count() &&
1287          !is_locked_by_vm();
1288 }
1289 
1290 void nmethod::inc_decompile_count() {
1291   if (!is_compiled_by_c2() && !is_compiled_by_jvmci()) return;
1292   // Could be gated by ProfileTraps, but do not bother...
1293   Method* m = method();
1294   if (m == NULL)  return;
1295   MethodData* mdo = m->method_data();
1296   if (mdo == NULL)  return;
1297   // There is a benign race here.  See comments in methodData.hpp.
1298   mdo->inc_decompile_count();
1299 }
1300 
1301 void nmethod::increase_unloading_clock() {
1302   _global_unloading_clock++;
1303   if (_global_unloading_clock == 0) {
1304     // _nmethods are allocated with _unloading_clock == 0,
1305     // so 0 is never used as a clock value.
1306     _global_unloading_clock = 1;
1307   }
1308 }
1309 
1310 void nmethod::set_unloading_clock(unsigned char unloading_clock) {
1311   OrderAccess::release_store((volatile jubyte*)&_unloading_clock, unloading_clock);


1335                   this, (address)_method, (address)cause);
1336     if (!Universe::heap()->is_gc_active())
1337       cause->klass()->print();
1338   }
1339   // Unlink the osr method, so we do not look this up again
1340   if (is_osr_method()) {
1341     invalidate_osr_method();
1342   }
1343   // If _method is already NULL the Method* is about to be unloaded,
1344   // so we don't have to break the cycle. Note that it is possible to
1345   // have the Method* live here, in case we unload the nmethod because
1346   // it is pointing to some oop (other than the Method*) being unloaded.
1347   if (_method != NULL) {
1348     // OSR methods point to the Method*, but the Method* does not
1349     // point back!
1350     if (_method->code() == this) {
1351       _method->clear_code(); // Break a cycle
1352     }
1353     _method = NULL;            // Clear the method of this dead nmethod
1354   }
1355 
1356   // Make the class unloaded - i.e., change state and notify sweeper
1357   assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint");
1358   if (is_in_use()) {
1359     // Transitioning directly from live to unloaded -- so
1360     // we need to force a cache clean-up; remember this
1361     // for later on.
1362     CodeCache::set_needs_cache_clean(true);
1363   }
1364 
1365   // Unregister must be done before the state change
1366   Universe::heap()->unregister_nmethod(this);
1367 
1368 #if INCLUDE_JVMCI
1369   // The method can only be unloaded after the pointer to the installed code
1370   // Java wrapper is no longer alive. Here we need to clear out this weak
1371   // reference to the dead object. Nulling out the reference has to happen
1372   // after the method is unregistered since the original value may be still
1373   // tracked by the rset.
1374   if (_jvmci_installed_code != NULL) {
1375     InstalledCode::set_address(_jvmci_installed_code, 0);
1376     _jvmci_installed_code = NULL;
1377   }
1378 #endif
1379 
1380   _state = unloaded;
1381 
1382   // Log the unloading.
1383   log_state_change();
1384 
1385   // The Method* is gone at this point
1386   assert(_method == NULL, "Tautology");
1387 
1388   set_osr_link(NULL);
1389   //set_scavenge_root_link(NULL); // done by prune_scavenge_root_nmethods
1390   NMethodSweeper::report_state_change(this);
1391 }
1392 
1393 void nmethod::invalidate_osr_method() {
1394   assert(_entry_bci != InvocationEntryBci, "wrong kind of nmethod");
1395   // Remove from list of active nmethods
1396   if (method() != NULL)
1397     method()->method_holder()->remove_osr_nmethod(this);
1398 }
1399 


1523     }
1524 
1525     // zombie only - if a JVMTI agent has enabled the CompiledMethodUnload
1526     // event and it hasn't already been reported for this nmethod then
1527     // report it now. The event may have been reported earilier if the GC
1528     // marked it for unloading). JvmtiDeferredEventQueue support means
1529     // we no longer go to a safepoint here.
1530     post_compiled_method_unload();
1531 
1532 #ifdef ASSERT
1533     // It's no longer safe to access the oops section since zombie
1534     // nmethods aren't scanned for GC.
1535     _oops_are_stale = true;
1536 #endif
1537      // the Method may be reclaimed by class unloading now that the
1538      // nmethod is in zombie state
1539     set_method(NULL);
1540   } else {
1541     assert(state == not_entrant, "other cases may need to be handled differently");
1542   }
1543 #if INCLUDE_JVMCI
1544   if (_jvmci_installed_code != NULL) {
1545     // Break the link between nmethod and InstalledCode such that the nmethod can subsequently be flushed safely.
1546     InstalledCode::set_address(_jvmci_installed_code, 0);
1547   }
1548 #endif
1549 
1550   if (TraceCreateZombies) {
1551     ResourceMark m;
1552     tty->print_cr("nmethod <" INTPTR_FORMAT "> %s code made %s", this, this->method() ? this->method()->name_and_sig_as_C_string() : "null", (state == not_entrant) ? "not entrant" : "zombie");
1553   }
1554 
1555   NMethodSweeper::report_state_change(this);
1556   return true;
1557 }
1558 
1559 void nmethod::flush() {
1560   // Note that there are no valid oops in the nmethod anymore.
1561   assert(is_zombie() || (is_osr_method() && is_unloaded()), "must be a zombie method");
1562   assert(is_marked_for_reclamation() || (is_osr_method() && is_unloaded()), "must be marked for reclamation");
1563 
1564   assert (!is_locked_by_vm(), "locked methods shouldn't be flushed");
1565   assert_locked_or_safepoint(CodeCache_lock);
1566 
1567   // completely deallocate this method
1568   Events::log(JavaThread::current(), "flushing nmethod " INTPTR_FORMAT, this);
1569   if (PrintMethodFlushing) {
1570     tty->print_cr("*flushing nmethod %3d/" INTPTR_FORMAT ". Live blobs:" UINT32_FORMAT "/Free CodeCache:" SIZE_FORMAT "Kb",
1571         _compile_id, this, CodeCache::nof_blobs(), CodeCache::unallocated_capacity(CodeCache::get_code_blob_type(this))/1024);
1572   }


1820                   (r->oop_addr() >= oops_begin() && r->oop_addr() < oops_end()),
1821              "oop must be found in exactly one place");
1822       if (r->oop_is_immediate() && r->oop_value() != NULL) {
1823         if (can_unload(is_alive, r->oop_addr(), unloading_occurred)) {
1824           return;
1825         }
1826       }
1827     }
1828   }
1829   }
1830 
1831 
1832   // Scopes
1833   for (oop* p = oops_begin(); p < oops_end(); p++) {
1834     if (*p == Universe::non_oop_word())  continue;  // skip non-oops
1835     if (can_unload(is_alive, p, unloading_occurred)) {
1836       return;
1837     }
1838   }
1839 
1840 #if INCLUDE_JVMCI
1841   // Follow JVMCI method
1842   BarrierSet* bs = Universe::heap()->barrier_set();
1843   if (_jvmci_installed_code != NULL) {
1844     if (_jvmci_installed_code->is_a(HotSpotNmethod::klass()) && HotSpotNmethod::isDefault(_jvmci_installed_code)) {
1845       if (!is_alive->do_object_b(_jvmci_installed_code)) {
1846         bs->write_ref_nmethod_pre(&_jvmci_installed_code, this);
1847         _jvmci_installed_code = NULL;
1848         bs->write_ref_nmethod_post(&_jvmci_installed_code, this);
1849       }
1850     } else {
1851       if (can_unload(is_alive, (oop*)&_jvmci_installed_code, unloading_occurred)) {
1852         return;
1853       }
1854     }
1855   }
1856 
1857   if (_speculation_log != NULL) {
1858     if (!is_alive->do_object_b(_speculation_log)) {
1859       bs->write_ref_nmethod_pre(&_speculation_log, this);
1860       _speculation_log = NULL;
1861       bs->write_ref_nmethod_post(&_speculation_log, this);
1862     }
1863   }
1864 #endif
1865 
1866 
1867   // Ensure that all metadata is still alive
1868   verify_metadata_loaders(low_boundary, is_alive);
1869 }
1870 
1871 template <class CompiledICorStaticCall>
1872 static bool clean_if_nmethod_is_unloaded(CompiledICorStaticCall *ic, address addr, BoolObjectClosure *is_alive, nmethod* from) {
1873   // Ok, to lookup references to zombies here
1874   CodeBlob *cb = CodeCache::find_blob_unsafe(addr);
1875   if (cb != NULL && cb->is_nmethod()) {
1876     nmethod* nm = (nmethod*)cb;
1877 
1878     if (nm->unloading_clock() != nmethod::global_unloading_clock()) {
1879       // The nmethod has not been processed yet.
1880       return true;
1881     }
1882 
1883     // Clean inline caches pointing to both zombie and not_entrant methods
1884     if (!nm->is_in_use() || (nm->method()->code() != nm)) {
1885       ic->set_to_clean();
1886       assert(ic->is_clean(), err_msg("nmethod " PTR_FORMAT "not clean %s", from, from->method()->name_and_sig_as_C_string()));


1929   // first few bytes.  If an oop in the old code was there, that oop
1930   // should not get GC'd.  Skip the first few bytes of oops on
1931   // not-entrant methods.
1932   address low_boundary = verified_entry_point();
1933   if (is_not_entrant()) {
1934     low_boundary += NativeJump::instruction_size;
1935     // %%% Note:  On SPARC we patch only a 4-byte trap, not a full NativeJump.
1936     // (See comment above.)
1937   }
1938 
1939   // The RedefineClasses() API can cause the class unloading invariant
1940   // to no longer be true. See jvmtiExport.hpp for details.
1941   // Also, leave a debugging breadcrumb in local flag.
1942   if (JvmtiExport::has_redefined_a_class()) {
1943     // This set of the unloading_occurred flag is done before the
1944     // call to post_compiled_method_unload() so that the unloading
1945     // of this nmethod is reported.
1946     unloading_occurred = true;
1947   }
1948 
1949 #if INCLUDE_JVMCI
1950   // Follow JVMCI method
1951   if (_jvmci_installed_code != NULL) {
1952     if (_jvmci_installed_code->is_a(HotSpotNmethod::klass()) && HotSpotNmethod::isDefault(_jvmci_installed_code)) {
1953       if (!is_alive->do_object_b(_jvmci_installed_code)) {
1954         _jvmci_installed_code = NULL;
1955       }
1956     } else {
1957       if (can_unload(is_alive, (oop*)&_jvmci_installed_code, unloading_occurred)) {
1958         return false;
1959       }
1960     }
1961   }
1962 
1963   if (_speculation_log != NULL) {
1964     if (!is_alive->do_object_b(_speculation_log)) {
1965       _speculation_log = NULL;
1966     }
1967   }
1968 #endif
1969 
1970   // Exception cache
1971   clean_exception_cache(is_alive);
1972 
1973   bool is_unloaded = false;
1974   bool postponed = false;
1975 
1976   RelocIterator iter(this, low_boundary);
1977   while(iter.next()) {
1978 
1979     switch (iter.type()) {
1980 
1981     case relocInfo::virtual_call_type:
1982       if (unloading_occurred) {
1983         // If class unloading occurred we first iterate over all inline caches and
1984         // clear ICs where the cached oop is referring to an unloaded klass or method.
1985         clean_ic_if_metadata_is_dead(CompiledIC_at(&iter), is_alive);
1986       }
1987 
1988       postponed |= clean_if_nmethod_is_unloaded(CompiledIC_at(&iter), is_alive, this);
1989       break;


2007     }
2008   }
2009 
2010   if (is_unloaded) {
2011     return postponed;
2012   }
2013 
2014   // Scopes
2015   for (oop* p = oops_begin(); p < oops_end(); p++) {
2016     if (*p == Universe::non_oop_word())  continue;  // skip non-oops
2017     if (can_unload(is_alive, p, unloading_occurred)) {
2018       is_unloaded = true;
2019       break;
2020     }
2021   }
2022 
2023   if (is_unloaded) {
2024     return postponed;
2025   }
2026 
2027 #if INCLUDE_JVMCI
2028   // Follow JVMCI method
2029   BarrierSet* bs = Universe::heap()->barrier_set();
2030   if (_jvmci_installed_code != NULL) {
2031     if (_jvmci_installed_code->is_a(HotSpotNmethod::klass()) && HotSpotNmethod::isDefault(_jvmci_installed_code)) {
2032       if (!is_alive->do_object_b(_jvmci_installed_code)) {
2033         bs->write_ref_nmethod_pre(&_jvmci_installed_code, this);
2034         _jvmci_installed_code = NULL;
2035         bs->write_ref_nmethod_post(&_jvmci_installed_code, this);
2036       }
2037     } else {
2038       if (can_unload(is_alive, (oop*)&_jvmci_installed_code, unloading_occurred)) {
2039         is_unloaded = true;
2040       }
2041     }
2042   }
2043 
2044   if (_speculation_log != NULL) {
2045     if (!is_alive->do_object_b(_speculation_log)) {
2046       bs->write_ref_nmethod_pre(&_speculation_log, this);
2047       _speculation_log = NULL;
2048       bs->write_ref_nmethod_post(&_speculation_log, this);
2049     }
2050   }
2051 #endif
2052 
2053   // Ensure that all metadata is still alive
2054   verify_metadata_loaders(low_boundary, is_alive);
2055 
2056   return postponed;
2057 }
2058 
2059 void nmethod::do_unloading_parallel_postponed(BoolObjectClosure* is_alive, bool unloading_occurred) {
2060   ResourceMark rm;
2061 
2062   // Make sure the oop's ready to receive visitors
2063   assert(!is_zombie(),
2064          "should not call follow on zombie nmethod");
2065 
2066   // If the method is not entrant then a JMP is plastered over the
2067   // first few bytes.  If an oop in the old code was there, that oop
2068   // should not get GC'd.  Skip the first few bytes of oops on
2069   // not-entrant methods.
2070   address low_boundary = verified_entry_point();
2071   if (is_not_entrant()) {
2072     low_boundary += NativeJump::instruction_size;


2217   // Visit metadata not embedded in the other places.
2218   if (_method != NULL) f(_method);
2219 }
2220 
2221 void nmethod::oops_do(OopClosure* f, bool allow_zombie) {
2222   // make sure the oops ready to receive visitors
2223   assert(allow_zombie || !is_zombie(), "should not call follow on zombie nmethod");
2224   assert(!is_unloaded(), "should not call follow on unloaded nmethod");
2225 
2226   // If the method is not entrant or zombie then a JMP is plastered over the
2227   // first few bytes.  If an oop in the old code was there, that oop
2228   // should not get GC'd.  Skip the first few bytes of oops on
2229   // not-entrant methods.
2230   address low_boundary = verified_entry_point();
2231   if (is_not_entrant()) {
2232     low_boundary += NativeJump::instruction_size;
2233     // %%% Note:  On SPARC we patch only a 4-byte trap, not a full NativeJump.
2234     // (See comment above.)
2235   }
2236 
2237 #if INCLUDE_JVMCI
2238   if (_jvmci_installed_code != NULL) {
2239     f->do_oop((oop*) &_jvmci_installed_code);
2240   }
2241   if (_speculation_log != NULL) {
2242     f->do_oop((oop*) &_speculation_log);
2243   }
2244 #endif
2245 
2246   RelocIterator iter(this, low_boundary);
2247 
2248   while (iter.next()) {
2249     if (iter.type() == relocInfo::oop_type ) {
2250       oop_Relocation* r = iter.oop_reloc();
2251       // In this loop, we must only follow those oops directly embedded in
2252       // the code.  Other oops (oop_index>0) are seen as part of scopes_oops.
2253       assert(1 == (r->oop_is_immediate()) +
2254                    (r->oop_addr() >= oops_begin() && r->oop_addr() < oops_end()),
2255              "oop must be found in exactly one place");
2256       if (r->oop_is_immediate() && r->oop_value() != NULL) {
2257         f->do_oop(r->oop_addr());
2258       }
2259     }
2260   }
2261 
2262   // Scopes
2263   // This includes oop constants not inlined in the code stream.
2264   for (oop* p = oops_begin(); p < oops_end(); p++) {
2265     if (*p == Universe::non_oop_word())  continue;  // skip non-oops


2350     if (!_detected_scavenge_root)  _print_nm->print_on(tty, "new scavenge root");
2351     tty->print_cr("" PTR_FORMAT "[offset=%d] detected scavengable oop " PTR_FORMAT " (found at " PTR_FORMAT ")",
2352                   _print_nm, (int)((intptr_t)p - (intptr_t)_print_nm),
2353                   (void *)(*p), (intptr_t)p);
2354     (*p)->print();
2355   }
2356 #endif //PRODUCT
2357 };
2358 
2359 bool nmethod::detect_scavenge_root_oops() {
2360   DetectScavengeRoot detect_scavenge_root;
2361   NOT_PRODUCT(if (TraceScavenge)  detect_scavenge_root._print_nm = this);
2362   oops_do(&detect_scavenge_root);
2363   return detect_scavenge_root.detected_scavenge_root();
2364 }
2365 
2366 // Method that knows how to preserve outgoing arguments at call. This method must be
2367 // called with a frame corresponding to a Java invoke
2368 void nmethod::preserve_callee_argument_oops(frame fr, const RegisterMap *reg_map, OopClosure* f) {
2369 #ifndef SHARK
2370   if (method() != NULL && !method()->is_native()) {
2371     SimpleScopeDesc ssd(this, fr.pc());
2372     Bytecode_invoke call(ssd.method(), ssd.bci());
2373     bool has_receiver = call.has_receiver();
2374     bool has_appendix = call.has_appendix();
2375     Symbol* signature = call.signature();
2376     fr.oops_compiled_arguments_do(signature, has_receiver, has_appendix, reg_map, f);
2377   }
2378 #endif // !SHARK
2379 }
2380 
2381 inline bool includes(void* p, void* from, void* to) {
2382   return from <= p && p < to;
2383 }
2384 
2385 
2386 void nmethod::copy_scopes_pcs(PcDesc* pcs, int count) {
2387   assert(count >= 2, "must be sentinel values, at least");
2388 
2389 #ifdef ASSERT
2390   // must be sorted and unique; we do a binary search in find_pc_desc()


2416   // Adjust the final sentinel downward.
2417   PcDesc* last_pc = &scopes_pcs_begin()[count-1];
2418   assert(last_pc->pc_offset() == PcDesc::upper_offset_limit, "sanity");
2419   last_pc->set_pc_offset(content_size() + 1);
2420   for (; last_pc + 1 < scopes_pcs_end(); last_pc += 1) {
2421     // Fill any rounding gaps with copies of the last record.
2422     last_pc[1] = last_pc[0];
2423   }
2424   // The following assert could fail if sizeof(PcDesc) is not
2425   // an integral multiple of oopSize (the rounding term).
2426   // If it fails, change the logic to always allocate a multiple
2427   // of sizeof(PcDesc), and fill unused words with copies of *last_pc.
2428   assert(last_pc + 1 == scopes_pcs_end(), "must match exactly");
2429 }
2430 
2431 void nmethod::copy_scopes_data(u_char* buffer, int size) {
2432   assert(scopes_data_size() >= size, "oob");
2433   memcpy(scopes_data_begin(), buffer, size);
2434 }
2435 
2436 // When using JVMCI the address might be off by the size of a call instruction.
2437 bool nmethod::is_deopt_entry(address pc) {
2438   return pc == deopt_handler_begin()
2439 #if INCLUDE_JVMCI
2440     || pc == (deopt_handler_begin() + NativeCall::instruction_size)
2441 #endif
2442     ;
2443 }
2444 
2445 #ifdef ASSERT
2446 static PcDesc* linear_search(nmethod* nm, int pc_offset, bool approximate) {
2447   PcDesc* lower = nm->scopes_pcs_begin();
2448   PcDesc* upper = nm->scopes_pcs_end();
2449   lower += 1; // exclude initial sentinel
2450   PcDesc* res = NULL;
2451   for (PcDesc* p = lower; p < upper; p++) {
2452     NOT_PRODUCT(--pc_nmethod_stats.pc_desc_tests);  // don't count this call to match_desc
2453     if (match_desc(p, pc_offset, approximate)) {
2454       if (res == NULL)
2455         res = p;
2456       else
2457         res = (PcDesc*) badAddress;
2458     }
2459   }
2460   return res;
2461 }
2462 #endif
2463 
2464 
2465 // Finds a PcDesc with real-pc equal to "pc"
2466 PcDesc* nmethod::find_pc_desc_internal(address pc, bool approximate) {
2467   address base_address = code_begin();
2468   if ((pc < base_address) ||
2469       (pc - base_address) >= (ptrdiff_t) PcDesc::upper_offset_limit) {
2470     return NULL;  // PC is wildly out of range
2471   }
2472   int pc_offset = (int) (pc - base_address);


2479     return res;
2480   }
2481 
2482   // Fallback algorithm: quasi-linear search for the PcDesc
2483   // Find the last pc_offset less than the given offset.
2484   // The successor must be the required match, if there is a match at all.
2485   // (Use a fixed radix to avoid expensive affine pointer arithmetic.)
2486   PcDesc* lower = scopes_pcs_begin();
2487   PcDesc* upper = scopes_pcs_end();
2488   upper -= 1; // exclude final sentinel
2489   if (lower >= upper)  return NULL;  // native method; no PcDescs at all
2490 
2491 #define assert_LU_OK \
2492   /* invariant on lower..upper during the following search: */ \
2493   assert(lower->pc_offset() <  pc_offset, "sanity"); \
2494   assert(upper->pc_offset() >= pc_offset, "sanity")
2495   assert_LU_OK;
2496 
2497   // Use the last successful return as a split point.
2498   PcDesc* mid = _pc_desc_cache.last_pc_desc();
2499   NOT_PRODUCT(++pc_nmethod_stats.pc_desc_searches);
2500   if (mid->pc_offset() < pc_offset) {
2501     lower = mid;
2502   } else {
2503     upper = mid;
2504   }
2505 
2506   // Take giant steps at first (4096, then 256, then 16, then 1)
2507   const int LOG2_RADIX = 4 /*smaller steps in debug mode:*/ debug_only(-1);
2508   const int RADIX = (1 << LOG2_RADIX);
2509   for (int step = (1 << (LOG2_RADIX*3)); step > 1; step >>= LOG2_RADIX) {
2510     while ((mid = lower + step) < upper) {
2511       assert_LU_OK;
2512       NOT_PRODUCT(++pc_nmethod_stats.pc_desc_searches);
2513       if (mid->pc_offset() < pc_offset) {
2514         lower = mid;
2515       } else {
2516         upper = mid;
2517         break;
2518       }
2519     }
2520     assert_LU_OK;
2521   }
2522 
2523   // Sneak up on the value with a linear search of length ~16.
2524   while (true) {
2525     assert_LU_OK;
2526     mid = lower + 1;
2527     NOT_PRODUCT(++pc_nmethod_stats.pc_desc_searches);
2528     if (mid->pc_offset() < pc_offset) {
2529       lower = mid;
2530     } else {
2531       upper = mid;
2532       break;
2533     }
2534   }
2535 #undef assert_LU_OK
2536 
2537   if (match_desc(upper, pc_offset, approximate)) {
2538     assert(upper == linear_search(this, pc_offset, approximate), "search ok");
2539     _pc_desc_cache.add_pc_desc(upper);
2540     return upper;
2541   } else {
2542     assert(NULL == linear_search(this, pc_offset, approximate), "search ok");
2543     return NULL;
2544   }
2545 }
2546 
2547 


2694   CodeBlob* cb = CodeCache::find_blob(pc);
2695   guarantee(cb != NULL && cb->is_nmethod(), "bad pc for a nmethod found");
2696   _nm = (nmethod*)cb;
2697   lock_nmethod(_nm);
2698 }
2699 
2700 // Only JvmtiDeferredEvent::compiled_method_unload_event()
2701 // should pass zombie_ok == true.
2702 void nmethodLocker::lock_nmethod(nmethod* nm, bool zombie_ok) {
2703   if (nm == NULL)  return;
2704   Atomic::inc(&nm->_lock_count);
2705   assert(zombie_ok || !nm->is_zombie(), "cannot lock a zombie method");
2706 }
2707 
2708 void nmethodLocker::unlock_nmethod(nmethod* nm) {
2709   if (nm == NULL)  return;
2710   Atomic::dec(&nm->_lock_count);
2711   assert(nm->_lock_count >= 0, "unmatched nmethod lock/unlock");
2712 }
2713 

2714 // -----------------------------------------------------------------------------
2715 // nmethod::get_deopt_original_pc
2716 //
2717 // Return the original PC for the given PC if:
2718 // (a) the given PC belongs to a nmethod and
2719 // (b) it is a deopt PC
2720 address nmethod::get_deopt_original_pc(const frame* fr) {
2721   if (fr->cb() == NULL)  return NULL;
2722 
2723   nmethod* nm = fr->cb()->as_nmethod_or_null();
2724   if (nm != NULL && nm->is_deopt_pc(fr->pc()))
2725     return nm->get_original_pc(fr);
2726 
2727   return NULL;
2728 }
2729 
2730 
2731 // -----------------------------------------------------------------------------
2732 // MethodHandle
2733 


2807 void nmethod::verify_interrupt_point(address call_site) {
2808   // Verify IC only when nmethod installation is finished.
2809   bool is_installed = (method()->code() == this) // nmethod is in state 'in_use' and installed
2810                       || !this->is_in_use();     // nmethod is installed, but not in 'in_use' state
2811   if (is_installed) {
2812     Thread *cur = Thread::current();
2813     if (CompiledIC_lock->owner() == cur ||
2814         ((cur->is_VM_thread() || cur->is_ConcurrentGC_thread()) &&
2815          SafepointSynchronize::is_at_safepoint())) {
2816       CompiledIC_at(this, call_site);
2817       CHECK_UNHANDLED_OOPS_ONLY(Thread::current()->clear_unhandled_oops());
2818     } else {
2819       MutexLocker ml_verify (CompiledIC_lock);
2820       CompiledIC_at(this, call_site);
2821     }
2822   }
2823 
2824   PcDesc* pd = pc_desc_at(nativeCall_at(call_site)->return_address());
2825   assert(pd != NULL, "PcDesc must exist");
2826   for (ScopeDesc* sd = new ScopeDesc(this, pd->scope_decode_offset(),
2827                                      pd->obj_decode_offset(), pd->should_reexecute(), pd->rethrow_exception(),
2828                                      pd->return_oop());
2829        !sd->is_top(); sd = sd->sender()) {
2830     sd->verify();
2831   }
2832 }
2833 
2834 void nmethod::verify_scopes() {
2835   if( !method() ) return;       // Runtime stubs have no scope
2836   if (method()->is_native()) return; // Ignore stub methods.
2837   // iterate through all interrupt point
2838   // and verify the debug information is valid.
2839   RelocIterator iter((nmethod*)this);
2840   while (iter.next()) {
2841     address stub = NULL;
2842     switch (iter.type()) {
2843       case relocInfo::virtual_call_type:
2844         verify_interrupt_point(iter.addr());
2845         break;
2846       case relocInfo::opt_virtual_call_type:
2847         stub = iter.opt_virtual_call_reloc()->static_stub();


2900   }
2901   assert(scavenge_root_not_marked(), "");
2902 }
2903 
2904 #endif // PRODUCT
2905 
2906 // Printing operations
2907 
2908 void nmethod::print() const {
2909   ResourceMark rm;
2910   ttyLocker ttyl;   // keep the following output all in one block
2911 
2912   tty->print("Compiled method ");
2913 
2914   if (is_compiled_by_c1()) {
2915     tty->print("(c1) ");
2916   } else if (is_compiled_by_c2()) {
2917     tty->print("(c2) ");
2918   } else if (is_compiled_by_shark()) {
2919     tty->print("(shark) ");
2920   } else if (is_compiled_by_jvmci()) {
2921     tty->print("(JVMCI) ");
2922   } else {
2923     tty->print("(nm) ");
2924   }
2925 
2926   print_on(tty, NULL);
2927 
2928   if (WizardMode) {
2929     tty->print("((nmethod*) " INTPTR_FORMAT ") ", this);
2930     tty->print(" for method " INTPTR_FORMAT , (address)method());
2931     tty->print(" { ");
2932     if (is_in_use())      tty->print("in_use ");
2933     if (is_not_entrant()) tty->print("not_entrant ");
2934     if (is_zombie())      tty->print("zombie ");
2935     if (is_unloaded())    tty->print("unloaded ");
2936     if (on_scavenge_root_list())  tty->print("scavenge_root ");
2937     tty->print_cr("}:");
2938   }
2939   if (size              () > 0) tty->print_cr(" total in heap  [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",
2940                                               (address)this,
2941                                               (address)this + size(),


2986                                               nul_chk_table_size());
2987 }
2988 
2989 void nmethod::print_code() {
2990   HandleMark hm;
2991   ResourceMark m;
2992   Disassembler::decode(this);
2993 }
2994 
2995 
2996 #ifndef PRODUCT
2997 
2998 void nmethod::print_scopes() {
2999   // Find the first pc desc for all scopes in the code and print it.
3000   ResourceMark rm;
3001   for (PcDesc* p = scopes_pcs_begin(); p < scopes_pcs_end(); p++) {
3002     if (p->scope_decode_offset() == DebugInformationRecorder::serialized_null)
3003       continue;
3004 
3005     ScopeDesc* sd = scope_desc_at(p->real_pc(this));
3006     while (sd != NULL) {
3007       sd->print_on(tty, p);
3008       sd = sd->sender();
3009     }
3010   }
3011 }
3012 
3013 void nmethod::print_dependencies() {
3014   ResourceMark rm;
3015   ttyLocker ttyl;   // keep the following output all in one block
3016   tty->print_cr("Dependencies:");
3017   for (Dependencies::DepStream deps(this); deps.next(); ) {
3018     deps.print_dependency();
3019     Klass* ctxk = deps.context_type();
3020     if (ctxk != NULL) {
3021       if (ctxk->oop_is_instance() && ((InstanceKlass*)ctxk)->is_dependent_nmethod(this)) {
3022         tty->print_cr("   [nmethod<=klass]%s", ctxk->external_name());
3023       }
3024     }
3025     deps.log_dependency();  // put it into the xml log also
3026   }
3027 }
3028 
3029 


3106         case relocInfo::virtual_call_type:     return "virtual_call";
3107         case relocInfo::opt_virtual_call_type: return "optimized virtual_call";
3108         case relocInfo::static_call_type:      return "static_call";
3109         case relocInfo::static_stub_type:      return "static_stub";
3110         case relocInfo::external_word_type:    return "external_word";
3111         case relocInfo::internal_word_type:    return "internal_word";
3112         case relocInfo::section_word_type:     return "section_word";
3113         case relocInfo::poll_type:             return "poll";
3114         case relocInfo::poll_return_type:      return "poll_return";
3115         case relocInfo::type_mask:             return "type_bit_mask";
3116     }
3117   }
3118   return have_one ? "other" : NULL;
3119 }
3120 
3121 // Return a the last scope in (begin..end]
3122 ScopeDesc* nmethod::scope_desc_in(address begin, address end) {
3123   PcDesc* p = pc_desc_near(begin+1);
3124   if (p != NULL && p->real_pc(this) <= end) {
3125     return new ScopeDesc(this, p->scope_decode_offset(),
3126                          p->obj_decode_offset(), p->should_reexecute(), p->rethrow_exception(),
3127                          p->return_oop());
3128   }
3129   return NULL;
3130 }
3131 
3132 void nmethod::print_nmethod_labels(outputStream* stream, address block_begin) const {
3133   if (block_begin == entry_point())             stream->print_cr("[Entry Point]");
3134   if (block_begin == verified_entry_point())    stream->print_cr("[Verified Entry Point]");
3135   if (JVMCI_ONLY(_exception_offset >= 0 &&) block_begin == exception_begin())         stream->print_cr("[Exception Handler]");
3136   if (block_begin == stub_begin())              stream->print_cr("[Stub Code]");
3137   if (JVMCI_ONLY(_deoptimize_offset >= 0 &&) block_begin == deopt_handler_begin())     stream->print_cr("[Deopt Handler Code]");
3138 
3139   if (has_method_handle_invokes())
3140     if (block_begin == deopt_mh_handler_begin())  stream->print_cr("[Deopt MH Handler Code]");
3141 
3142   if (block_begin == consts_begin())            stream->print_cr("[Constants]");
3143 
3144   if (block_begin == entry_point()) {
3145     methodHandle m = method();
3146     if (m.not_null()) {
3147       stream->print("  # ");
3148       m->print_value_on(stream);
3149       stream->cr();
3150     }
3151     if (m.not_null() && !is_osr_method()) {
3152       ResourceMark rm;
3153       int sizeargs = m->size_of_parameters();
3154       BasicType* sig_bt = NEW_RESOURCE_ARRAY(BasicType, sizeargs);
3155       VMRegPair* regs   = NEW_RESOURCE_ARRAY(VMRegPair, sizeargs);
3156       {
3157         int sig_index = 0;


3283             if (invoke.name() != NULL)
3284               invoke.name()->print_symbol_on(st);
3285             else
3286               st->print("<UNKNOWN>");
3287             break;
3288           }
3289         case Bytecodes::_getfield:
3290         case Bytecodes::_putfield:
3291         case Bytecodes::_getstatic:
3292         case Bytecodes::_putstatic:
3293           {
3294             Bytecode_field field(sd->method(), sd->bci());
3295             st->print(" ");
3296             if (field.name() != NULL)
3297               field.name()->print_symbol_on(st);
3298             else
3299               st->print("<UNKNOWN>");
3300           }
3301         }
3302       }
3303       st->print(" {reexecute=%d rethrow=%d return_oop=%d}", sd->should_reexecute(), sd->rethrow_exception(), sd->return_oop());
3304     }
3305 
3306     // Print all scopes
3307     for (;sd != NULL; sd = sd->sender()) {
3308       st->move_to(column);
3309       st->print("; -");
3310       if (sd->method() == NULL) {
3311         st->print("method is NULL");
3312       } else {
3313         sd->method()->print_short_name(st);
3314       }
3315       int lineno = sd->method()->line_number_from_bci(sd->bci());
3316       if (lineno != -1) {
3317         st->print("@%d (line %d)", sd->bci(), lineno);
3318       } else {
3319         st->print("@%d", sd->bci());
3320       }
3321       st->cr();
3322     }
3323   }


3356     }
3357     case relocInfo::static_call_type:
3358       st->print_cr("Static call at " INTPTR_FORMAT, iter.reloc()->addr());
3359       compiledStaticCall_at(iter.reloc())->print();
3360       break;
3361     }
3362   }
3363 }
3364 
3365 void nmethod::print_handler_table() {
3366   ExceptionHandlerTable(this).print();
3367 }
3368 
3369 void nmethod::print_nul_chk_table() {
3370   ImplicitExceptionTable(this).print(code_begin());
3371 }
3372 
3373 void nmethod::print_statistics() {
3374   ttyLocker ttyl;
3375   if (xtty != NULL)  xtty->head("statistics type='nmethod'");
3376   native_nmethod_stats.print_native_nmethod_stats();
3377 #ifdef COMPILER1
3378   c1_java_nmethod_stats.print_nmethod_stats("C1");
3379 #endif
3380 #ifdef COMPILER2
3381   c2_java_nmethod_stats.print_nmethod_stats("C2");
3382 #endif
3383 #if INCLUDE_JVMCI
3384   jvmci_java_nmethod_stats.print_nmethod_stats("JVMCI");
3385 #endif
3386 #ifdef SHARK
3387   shark_java_nmethod_stats.print_nmethod_stats("Shark");
3388 #endif
3389   unknown_java_nmethod_stats.print_nmethod_stats("Unknown");
3390   DebugInformationRecorder::print_statistics();
3391 #ifndef PRODUCT
3392   pc_nmethod_stats.print_pc_stats();
3393 #endif
3394   Dependencies::print_statistics();
3395   if (xtty != NULL)  xtty->tail("statistics");
3396 }
3397 
3398 #endif // !PRODUCT
3399 
3400 #if INCLUDE_JVMCI
3401 char* nmethod::jvmci_installed_code_name(char* buf, size_t buflen) {
3402   if (!this->is_compiled_by_jvmci()) {
3403     return NULL;
3404   }
3405   oop installedCode = this->jvmci_installed_code();
3406   if (installedCode != NULL) {
3407     oop installedCodeName = NULL;
3408     if (installedCode->is_a(InstalledCode::klass())) {
3409       installedCodeName = InstalledCode::name(installedCode);
3410     }
3411     if (installedCodeName != NULL) {
3412       return java_lang_String::as_utf8_string(installedCodeName, buf, (int)buflen);
3413     } else {
3414       jio_snprintf(buf, buflen, "null");
3415       return buf;
3416     }
3417   }
3418   jio_snprintf(buf, buflen, "noInstalledCode");
3419   return buf;
3420 }
3421 #endif
src/share/vm/code/nmethod.cpp
Index Unified diffs Context diffs Sdiffs Wdiffs Patch New Old Previous File Next File