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