src/share/vm/code/nmethod.cpp

Thu, 05 Sep 2019 18:52:27 +0800

author
aoqi
date
Thu, 05 Sep 2019 18:52:27 +0800
changeset 9703
2fdf635bcf28
parent 9448
73d689add964
parent 9661
379a59bf685d
permissions
-rw-r--r--

Merge

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

mercurial