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