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