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