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