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