1 /* 2 * Copyright (c) 1997, 2016, 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 "code/codeCache.hpp" 27 #include "code/compiledIC.hpp" 28 #include "code/dependencies.hpp" 29 #include "code/nativeInst.hpp" 30 #include "code/nmethod.hpp" 31 #include "code/scopeDesc.hpp" 32 #include "compiler/abstractCompiler.hpp" 33 #include "compiler/compileBroker.hpp" 34 #include "compiler/compileLog.hpp" 35 #include "compiler/compilerDirectives.hpp" 36 #include "compiler/disassembler.hpp" 37 #include "interpreter/bytecode.hpp" 38 #include "oops/methodData.hpp" 39 #include "oops/oop.inline.hpp" 40 #include "prims/jvmtiRedefineClassesTrace.hpp" 41 #include "prims/jvmtiImpl.hpp" 42 #include "runtime/atomic.inline.hpp" 43 #include "runtime/orderAccess.inline.hpp" 44 #include "runtime/os.hpp" 45 #include "runtime/sharedRuntime.hpp" 46 #include "runtime/sweeper.hpp" 47 #include "utilities/resourceHash.hpp" 48 #include "utilities/dtrace.hpp" 49 #include "utilities/events.hpp" 50 #include "utilities/xmlstream.hpp" 51 #include "logging/log.hpp" 52 #ifdef TARGET_ARCH_x86 53 # include "nativeInst_x86.hpp" 54 #endif 55 #ifdef TARGET_ARCH_sparc 56 # include "nativeInst_sparc.hpp" 57 #endif 58 #ifdef TARGET_ARCH_zero 59 # include "nativeInst_zero.hpp" 60 #endif 61 #ifdef TARGET_ARCH_arm 62 # include "nativeInst_arm.hpp" 63 #endif 64 #ifdef TARGET_ARCH_ppc 65 # include "nativeInst_ppc.hpp" 66 #endif 67 #ifdef SHARK 68 #include "shark/sharkCompiler.hpp" 69 #endif 70 #if INCLUDE_JVMCI 71 #include "jvmci/jvmciJavaClasses.hpp" 72 #endif 73 74 unsigned char nmethod::_global_unloading_clock = 0; 75 76 #ifdef DTRACE_ENABLED 77 78 // Only bother with this argument setup if dtrace is available 79 80 #define DTRACE_METHOD_UNLOAD_PROBE(method) \ 81 { \ 82 Method* m = (method); \ 83 if (m != NULL) { \ 84 Symbol* klass_name = m->klass_name(); \ 85 Symbol* name = m->name(); \ 86 Symbol* signature = m->signature(); \ 87 HOTSPOT_COMPILED_METHOD_UNLOAD( \ 88 (char *) klass_name->bytes(), klass_name->utf8_length(), \ 89 (char *) name->bytes(), name->utf8_length(), \ 90 (char *) signature->bytes(), signature->utf8_length()); \ 91 } \ 92 } 93 94 #else // ndef DTRACE_ENABLED 95 96 #define DTRACE_METHOD_UNLOAD_PROBE(method) 97 98 #endif 99 100 bool nmethod::is_compiled_by_c1() const { 101 if (compiler() == NULL) { 102 return false; 103 } 104 return compiler()->is_c1(); 105 } 106 bool nmethod::is_compiled_by_jvmci() const { 107 if (compiler() == NULL || method() == NULL) return false; // can happen during debug printing 108 if (is_native_method()) return false; 109 return compiler()->is_jvmci(); 110 } 111 bool nmethod::is_compiled_by_c2() const { 112 if (compiler() == NULL) { 113 return false; 114 } 115 return compiler()->is_c2(); 116 } 117 bool nmethod::is_compiled_by_shark() const { 118 if (compiler() == NULL) { 119 return false; 120 } 121 return compiler()->is_shark(); 122 } 123 124 125 126 //--------------------------------------------------------------------------------- 127 // NMethod statistics 128 // They are printed under various flags, including: 129 // PrintC1Statistics, PrintOptoStatistics, LogVMOutput, and LogCompilation. 130 // (In the latter two cases, they like other stats are printed to the log only.) 131 132 #ifndef PRODUCT 133 // These variables are put into one block to reduce relocations 134 // and make it simpler to print from the debugger. 135 struct java_nmethod_stats_struct { 136 int nmethod_count; 137 int total_size; 138 int relocation_size; 139 int consts_size; 140 int insts_size; 141 int stub_size; 142 int scopes_data_size; 143 int scopes_pcs_size; 144 int dependencies_size; 145 int handler_table_size; 146 int nul_chk_table_size; 147 int oops_size; 148 int metadata_size; 149 150 void note_nmethod(nmethod* nm) { 151 nmethod_count += 1; 152 total_size += nm->size(); 153 relocation_size += nm->relocation_size(); 154 consts_size += nm->consts_size(); 155 insts_size += nm->insts_size(); 156 stub_size += nm->stub_size(); 157 oops_size += nm->oops_size(); 158 metadata_size += nm->metadata_size(); 159 scopes_data_size += nm->scopes_data_size(); 160 scopes_pcs_size += nm->scopes_pcs_size(); 161 dependencies_size += nm->dependencies_size(); 162 handler_table_size += nm->handler_table_size(); 163 nul_chk_table_size += nm->nul_chk_table_size(); 164 } 165 void print_nmethod_stats(const char* name) { 166 if (nmethod_count == 0) return; 167 tty->print_cr("Statistics for %d bytecoded nmethods for %s:", nmethod_count, name); 168 if (total_size != 0) tty->print_cr(" total in heap = %d", total_size); 169 if (nmethod_count != 0) tty->print_cr(" header = " SIZE_FORMAT, nmethod_count * sizeof(nmethod)); 170 if (relocation_size != 0) tty->print_cr(" relocation = %d", relocation_size); 171 if (consts_size != 0) tty->print_cr(" constants = %d", consts_size); 172 if (insts_size != 0) tty->print_cr(" main code = %d", insts_size); 173 if (stub_size != 0) tty->print_cr(" stub code = %d", stub_size); 174 if (oops_size != 0) tty->print_cr(" oops = %d", oops_size); 175 if (metadata_size != 0) tty->print_cr(" metadata = %d", metadata_size); 176 if (scopes_data_size != 0) tty->print_cr(" scopes data = %d", scopes_data_size); 177 if (scopes_pcs_size != 0) tty->print_cr(" scopes pcs = %d", scopes_pcs_size); 178 if (dependencies_size != 0) tty->print_cr(" dependencies = %d", dependencies_size); 179 if (handler_table_size != 0) tty->print_cr(" handler table = %d", handler_table_size); 180 if (nul_chk_table_size != 0) tty->print_cr(" nul chk table = %d", nul_chk_table_size); 181 } 182 }; 183 184 struct native_nmethod_stats_struct { 185 int native_nmethod_count; 186 int native_total_size; 187 int native_relocation_size; 188 int native_insts_size; 189 int native_oops_size; 190 int native_metadata_size; 191 void note_native_nmethod(nmethod* nm) { 192 native_nmethod_count += 1; 193 native_total_size += nm->size(); 194 native_relocation_size += nm->relocation_size(); 195 native_insts_size += nm->insts_size(); 196 native_oops_size += nm->oops_size(); 197 native_metadata_size += nm->metadata_size(); 198 } 199 void print_native_nmethod_stats() { 200 if (native_nmethod_count == 0) return; 201 tty->print_cr("Statistics for %d native nmethods:", native_nmethod_count); 202 if (native_total_size != 0) tty->print_cr(" N. total size = %d", native_total_size); 203 if (native_relocation_size != 0) tty->print_cr(" N. relocation = %d", native_relocation_size); 204 if (native_insts_size != 0) tty->print_cr(" N. main code = %d", native_insts_size); 205 if (native_oops_size != 0) tty->print_cr(" N. oops = %d", native_oops_size); 206 if (native_metadata_size != 0) tty->print_cr(" N. metadata = %d", native_metadata_size); 207 } 208 }; 209 210 struct pc_nmethod_stats_struct { 211 int pc_desc_resets; // number of resets (= number of caches) 212 int pc_desc_queries; // queries to nmethod::find_pc_desc 213 int pc_desc_approx; // number of those which have approximate true 214 int pc_desc_repeats; // number of _pc_descs[0] hits 215 int pc_desc_hits; // number of LRU cache hits 216 int pc_desc_tests; // total number of PcDesc examinations 217 int pc_desc_searches; // total number of quasi-binary search steps 218 int pc_desc_adds; // number of LUR cache insertions 219 220 void print_pc_stats() { 221 tty->print_cr("PcDesc Statistics: %d queries, %.2f comparisons per query", 222 pc_desc_queries, 223 (double)(pc_desc_tests + pc_desc_searches) 224 / pc_desc_queries); 225 tty->print_cr(" caches=%d queries=%d/%d, hits=%d+%d, tests=%d+%d, adds=%d", 226 pc_desc_resets, 227 pc_desc_queries, pc_desc_approx, 228 pc_desc_repeats, pc_desc_hits, 229 pc_desc_tests, pc_desc_searches, pc_desc_adds); 230 } 231 }; 232 233 #ifdef COMPILER1 234 static java_nmethod_stats_struct c1_java_nmethod_stats; 235 #endif 236 #ifdef COMPILER2 237 static java_nmethod_stats_struct c2_java_nmethod_stats; 238 #endif 239 #if INCLUDE_JVMCI 240 static java_nmethod_stats_struct jvmci_java_nmethod_stats; 241 #endif 242 #ifdef SHARK 243 static java_nmethod_stats_struct shark_java_nmethod_stats; 244 #endif 245 static java_nmethod_stats_struct unknown_java_nmethod_stats; 246 247 static native_nmethod_stats_struct native_nmethod_stats; 248 static pc_nmethod_stats_struct pc_nmethod_stats; 249 250 static void note_java_nmethod(nmethod* nm) { 251 #ifdef COMPILER1 252 if (nm->is_compiled_by_c1()) { 253 c1_java_nmethod_stats.note_nmethod(nm); 254 } else 255 #endif 256 #ifdef COMPILER2 257 if (nm->is_compiled_by_c2()) { 258 c2_java_nmethod_stats.note_nmethod(nm); 259 } else 260 #endif 261 #if INCLUDE_JVMCI 262 if (nm->is_compiled_by_jvmci()) { 263 jvmci_java_nmethod_stats.note_nmethod(nm); 264 } else 265 #endif 266 #ifdef SHARK 267 if (nm->is_compiled_by_shark()) { 268 shark_java_nmethod_stats.note_nmethod(nm); 269 } else 270 #endif 271 { 272 unknown_java_nmethod_stats.note_nmethod(nm); 273 } 274 } 275 #endif // !PRODUCT 276 277 //--------------------------------------------------------------------------------- 278 279 280 ExceptionCache::ExceptionCache(Handle exception, address pc, address handler) { 281 assert(pc != NULL, "Must be non null"); 282 assert(exception.not_null(), "Must be non null"); 283 assert(handler != NULL, "Must be non null"); 284 285 _count = 0; 286 _exception_type = exception->klass(); 287 _next = NULL; 288 289 add_address_and_handler(pc,handler); 290 } 291 292 293 address ExceptionCache::match(Handle exception, address pc) { 294 assert(pc != NULL,"Must be non null"); 295 assert(exception.not_null(),"Must be non null"); 296 if (exception->klass() == exception_type()) { 297 return (test_address(pc)); 298 } 299 300 return NULL; 301 } 302 303 304 bool ExceptionCache::match_exception_with_space(Handle exception) { 305 assert(exception.not_null(),"Must be non null"); 306 if (exception->klass() == exception_type() && count() < cache_size) { 307 return true; 308 } 309 return false; 310 } 311 312 313 address ExceptionCache::test_address(address addr) { 314 for (int i=0; i<count(); i++) { 315 if (pc_at(i) == addr) { 316 return handler_at(i); 317 } 318 } 319 return NULL; 320 } 321 322 323 bool ExceptionCache::add_address_and_handler(address addr, address handler) { 324 if (test_address(addr) == handler) return true; 325 if (count() < cache_size) { 326 set_pc_at(count(),addr); 327 set_handler_at(count(), handler); 328 increment_count(); 329 return true; 330 } 331 return false; 332 } 333 334 335 // private method for handling exception cache 336 // These methods are private, and used to manipulate the exception cache 337 // directly. 338 ExceptionCache* nmethod::exception_cache_entry_for_exception(Handle exception) { 339 ExceptionCache* ec = exception_cache(); 340 while (ec != NULL) { 341 if (ec->match_exception_with_space(exception)) { 342 return ec; 343 } 344 ec = ec->next(); 345 } 346 return NULL; 347 } 348 349 350 //----------------------------------------------------------------------------- 351 352 353 // Helper used by both find_pc_desc methods. 354 static inline bool match_desc(PcDesc* pc, int pc_offset, bool approximate) { 355 NOT_PRODUCT(++pc_nmethod_stats.pc_desc_tests); 356 if (!approximate) 357 return pc->pc_offset() == pc_offset; 358 else 359 return (pc-1)->pc_offset() < pc_offset && pc_offset <= pc->pc_offset(); 360 } 361 362 void PcDescCache::reset_to(PcDesc* initial_pc_desc) { 363 if (initial_pc_desc == NULL) { 364 _pc_descs[0] = NULL; // native method; no PcDescs at all 365 return; 366 } 367 NOT_PRODUCT(++pc_nmethod_stats.pc_desc_resets); 368 // reset the cache by filling it with benign (non-null) values 369 assert(initial_pc_desc->pc_offset() < 0, "must be sentinel"); 370 for (int i = 0; i < cache_size; i++) 371 _pc_descs[i] = initial_pc_desc; 372 } 373 374 PcDesc* PcDescCache::find_pc_desc(int pc_offset, bool approximate) { 375 NOT_PRODUCT(++pc_nmethod_stats.pc_desc_queries); 376 NOT_PRODUCT(if (approximate) ++pc_nmethod_stats.pc_desc_approx); 377 378 // Note: one might think that caching the most recently 379 // read value separately would be a win, but one would be 380 // wrong. When many threads are updating it, the cache 381 // line it's in would bounce between caches, negating 382 // any benefit. 383 384 // In order to prevent race conditions do not load cache elements 385 // repeatedly, but use a local copy: 386 PcDesc* res; 387 388 // Step one: Check the most recently added value. 389 res = _pc_descs[0]; 390 if (res == NULL) return NULL; // native method; no PcDescs at all 391 if (match_desc(res, pc_offset, approximate)) { 392 NOT_PRODUCT(++pc_nmethod_stats.pc_desc_repeats); 393 return res; 394 } 395 396 // Step two: Check the rest of the LRU cache. 397 for (int i = 1; i < cache_size; ++i) { 398 res = _pc_descs[i]; 399 if (res->pc_offset() < 0) break; // optimization: skip empty cache 400 if (match_desc(res, pc_offset, approximate)) { 401 NOT_PRODUCT(++pc_nmethod_stats.pc_desc_hits); 402 return res; 403 } 404 } 405 406 // Report failure. 407 return NULL; 408 } 409 410 void PcDescCache::add_pc_desc(PcDesc* pc_desc) { 411 NOT_PRODUCT(++pc_nmethod_stats.pc_desc_adds); 412 // Update the LRU cache by shifting pc_desc forward. 413 for (int i = 0; i < cache_size; i++) { 414 PcDesc* next = _pc_descs[i]; 415 _pc_descs[i] = pc_desc; 416 pc_desc = next; 417 } 418 } 419 420 // adjust pcs_size so that it is a multiple of both oopSize and 421 // sizeof(PcDesc) (assumes that if sizeof(PcDesc) is not a multiple 422 // of oopSize, then 2*sizeof(PcDesc) is) 423 static int adjust_pcs_size(int pcs_size) { 424 int nsize = round_to(pcs_size, oopSize); 425 if ((nsize % sizeof(PcDesc)) != 0) { 426 nsize = pcs_size + sizeof(PcDesc); 427 } 428 assert((nsize % oopSize) == 0, "correct alignment"); 429 return nsize; 430 } 431 432 //----------------------------------------------------------------------------- 433 434 435 void nmethod::add_exception_cache_entry(ExceptionCache* new_entry) { 436 assert(ExceptionCache_lock->owned_by_self(),"Must hold the ExceptionCache_lock"); 437 assert(new_entry != NULL,"Must be non null"); 438 assert(new_entry->next() == NULL, "Must be null"); 439 440 if (exception_cache() != NULL) { 441 new_entry->set_next(exception_cache()); 442 } 443 set_exception_cache(new_entry); 444 } 445 446 void nmethod::clean_exception_cache(BoolObjectClosure* is_alive) { 447 ExceptionCache* prev = NULL; 448 ExceptionCache* curr = exception_cache(); 449 450 while (curr != NULL) { 451 ExceptionCache* next = curr->next(); 452 453 Klass* ex_klass = curr->exception_type(); 454 if (ex_klass != NULL && !ex_klass->is_loader_alive(is_alive)) { 455 if (prev == NULL) { 456 set_exception_cache(next); 457 } else { 458 prev->set_next(next); 459 } 460 delete curr; 461 // prev stays the same. 462 } else { 463 prev = curr; 464 } 465 466 curr = next; 467 } 468 } 469 470 // public method for accessing the exception cache 471 // These are the public access methods. 472 address nmethod::handler_for_exception_and_pc(Handle exception, address pc) { 473 // We never grab a lock to read the exception cache, so we may 474 // have false negatives. This is okay, as it can only happen during 475 // the first few exception lookups for a given nmethod. 476 ExceptionCache* ec = exception_cache(); 477 while (ec != NULL) { 478 address ret_val; 479 if ((ret_val = ec->match(exception,pc)) != NULL) { 480 return ret_val; 481 } 482 ec = ec->next(); 483 } 484 return NULL; 485 } 486 487 488 void nmethod::add_handler_for_exception_and_pc(Handle exception, address pc, address handler) { 489 // There are potential race conditions during exception cache updates, so we 490 // must own the ExceptionCache_lock before doing ANY modifications. Because 491 // we don't lock during reads, it is possible to have several threads attempt 492 // to update the cache with the same data. We need to check for already inserted 493 // copies of the current data before adding it. 494 495 MutexLocker ml(ExceptionCache_lock); 496 ExceptionCache* target_entry = exception_cache_entry_for_exception(exception); 497 498 if (target_entry == NULL || !target_entry->add_address_and_handler(pc,handler)) { 499 target_entry = new ExceptionCache(exception,pc,handler); 500 add_exception_cache_entry(target_entry); 501 } 502 } 503 504 505 //-------------end of code for ExceptionCache-------------- 506 507 508 int nmethod::total_size() const { 509 return 510 consts_size() + 511 insts_size() + 512 stub_size() + 513 scopes_data_size() + 514 scopes_pcs_size() + 515 handler_table_size() + 516 nul_chk_table_size(); 517 } 518 519 const char* nmethod::compile_kind() const { 520 if (is_osr_method()) return "osr"; 521 if (method() != NULL && is_native_method()) return "c2n"; 522 return NULL; 523 } 524 525 // Fill in default values for various flag fields 526 void nmethod::init_defaults() { 527 _state = in_use; 528 _unloading_clock = 0; 529 _marked_for_reclamation = 0; 530 _has_flushed_dependencies = 0; 531 _has_unsafe_access = 0; 532 _has_method_handle_invokes = 0; 533 _lazy_critical_native = 0; 534 _has_wide_vectors = 0; 535 _marked_for_deoptimization = 0; 536 _lock_count = 0; 537 _stack_traversal_mark = 0; 538 _unload_reported = false; // jvmti state 539 540 #ifdef ASSERT 541 _oops_are_stale = false; 542 #endif 543 544 _oops_do_mark_link = NULL; 545 _jmethod_id = NULL; 546 _osr_link = NULL; 547 if (UseG1GC) { 548 _unloading_next = NULL; 549 } else { 550 _scavenge_root_link = NULL; 551 } 552 _scavenge_root_state = 0; 553 _compiler = NULL; 554 #if INCLUDE_RTM_OPT 555 _rtm_state = NoRTM; 556 #endif 557 #if INCLUDE_JVMCI 558 _jvmci_installed_code = NULL; 559 _speculation_log = NULL; 560 #endif 561 } 562 563 nmethod* nmethod::new_native_nmethod(const methodHandle& method, 564 int compile_id, 565 CodeBuffer *code_buffer, 566 int vep_offset, 567 int frame_complete, 568 int frame_size, 569 ByteSize basic_lock_owner_sp_offset, 570 ByteSize basic_lock_sp_offset, 571 OopMapSet* oop_maps) { 572 code_buffer->finalize_oop_references(method); 573 // create nmethod 574 nmethod* nm = NULL; 575 { 576 MutexLockerEx mu(CodeCache_lock, Mutex::_no_safepoint_check_flag); 577 int native_nmethod_size = allocation_size(code_buffer, sizeof(nmethod)); 578 CodeOffsets offsets; 579 offsets.set_value(CodeOffsets::Verified_Entry, vep_offset); 580 offsets.set_value(CodeOffsets::Frame_Complete, frame_complete); 581 nm = new (native_nmethod_size, CompLevel_none) nmethod(method(), native_nmethod_size, 582 compile_id, &offsets, 583 code_buffer, frame_size, 584 basic_lock_owner_sp_offset, 585 basic_lock_sp_offset, oop_maps); 586 NOT_PRODUCT(if (nm != NULL) native_nmethod_stats.note_native_nmethod(nm)); 587 } 588 // verify nmethod 589 debug_only(if (nm) nm->verify();) // might block 590 591 if (nm != NULL) { 592 nm->log_new_nmethod(); 593 } 594 595 return nm; 596 } 597 598 nmethod* nmethod::new_nmethod(const methodHandle& method, 599 int compile_id, 600 int entry_bci, 601 CodeOffsets* offsets, 602 int orig_pc_offset, 603 DebugInformationRecorder* debug_info, 604 Dependencies* dependencies, 605 CodeBuffer* code_buffer, int frame_size, 606 OopMapSet* oop_maps, 607 ExceptionHandlerTable* handler_table, 608 ImplicitExceptionTable* nul_chk_table, 609 AbstractCompiler* compiler, 610 int comp_level 611 #if INCLUDE_JVMCI 612 , Handle installed_code, 613 Handle speculationLog 614 #endif 615 ) 616 { 617 assert(debug_info->oop_recorder() == code_buffer->oop_recorder(), "shared OR"); 618 code_buffer->finalize_oop_references(method); 619 // create nmethod 620 nmethod* nm = NULL; 621 { MutexLockerEx mu(CodeCache_lock, Mutex::_no_safepoint_check_flag); 622 int nmethod_size = 623 allocation_size(code_buffer, sizeof(nmethod)) 624 + adjust_pcs_size(debug_info->pcs_size()) 625 + round_to(dependencies->size_in_bytes() , oopSize) 626 + round_to(handler_table->size_in_bytes(), oopSize) 627 + round_to(nul_chk_table->size_in_bytes(), oopSize) 628 + round_to(debug_info->data_size() , oopSize); 629 630 nm = new (nmethod_size, comp_level) 631 nmethod(method(), nmethod_size, compile_id, entry_bci, offsets, 632 orig_pc_offset, debug_info, dependencies, code_buffer, frame_size, 633 oop_maps, 634 handler_table, 635 nul_chk_table, 636 compiler, 637 comp_level 638 #if INCLUDE_JVMCI 639 , installed_code, 640 speculationLog 641 #endif 642 ); 643 644 if (nm != NULL) { 645 // To make dependency checking during class loading fast, record 646 // the nmethod dependencies in the classes it is dependent on. 647 // This allows the dependency checking code to simply walk the 648 // class hierarchy above the loaded class, checking only nmethods 649 // which are dependent on those classes. The slow way is to 650 // check every nmethod for dependencies which makes it linear in 651 // the number of methods compiled. For applications with a lot 652 // classes the slow way is too slow. 653 for (Dependencies::DepStream deps(nm); deps.next(); ) { 654 if (deps.type() == Dependencies::call_site_target_value) { 655 // CallSite dependencies are managed on per-CallSite instance basis. 656 oop call_site = deps.argument_oop(0); 657 MethodHandles::add_dependent_nmethod(call_site, nm); 658 } else { 659 Klass* klass = deps.context_type(); 660 if (klass == NULL) { 661 continue; // ignore things like evol_method 662 } 663 // record this nmethod as dependent on this klass 664 InstanceKlass::cast(klass)->add_dependent_nmethod(nm); 665 } 666 } 667 NOT_PRODUCT(if (nm != NULL) note_java_nmethod(nm)); 668 } 669 } 670 // Do verification and logging outside CodeCache_lock. 671 if (nm != NULL) { 672 // Safepoints in nmethod::verify aren't allowed because nm hasn't been installed yet. 673 DEBUG_ONLY(nm->verify();) 674 nm->log_new_nmethod(); 675 } 676 return nm; 677 } 678 679 // For native wrappers 680 nmethod::nmethod( 681 Method* method, 682 int nmethod_size, 683 int compile_id, 684 CodeOffsets* offsets, 685 CodeBuffer* code_buffer, 686 int frame_size, 687 ByteSize basic_lock_owner_sp_offset, 688 ByteSize basic_lock_sp_offset, 689 OopMapSet* oop_maps ) 690 : CodeBlob("native nmethod", code_buffer, sizeof(nmethod), 691 nmethod_size, offsets->value(CodeOffsets::Frame_Complete), frame_size, oop_maps), 692 _native_receiver_sp_offset(basic_lock_owner_sp_offset), 693 _native_basic_lock_sp_offset(basic_lock_sp_offset) 694 { 695 { 696 debug_only(NoSafepointVerifier nsv;) 697 assert_locked_or_safepoint(CodeCache_lock); 698 699 init_defaults(); 700 _method = method; 701 _entry_bci = InvocationEntryBci; 702 // We have no exception handler or deopt handler make the 703 // values something that will never match a pc like the nmethod vtable entry 704 _exception_offset = 0; 705 _deoptimize_offset = 0; 706 _deoptimize_mh_offset = 0; 707 _orig_pc_offset = 0; 708 709 _consts_offset = data_offset(); 710 _stub_offset = data_offset(); 711 _oops_offset = data_offset(); 712 _metadata_offset = _oops_offset + round_to(code_buffer->total_oop_size(), oopSize); 713 _scopes_data_offset = _metadata_offset + round_to(code_buffer->total_metadata_size(), wordSize); 714 _scopes_pcs_offset = _scopes_data_offset; 715 _dependencies_offset = _scopes_pcs_offset; 716 _handler_table_offset = _dependencies_offset; 717 _nul_chk_table_offset = _handler_table_offset; 718 _nmethod_end_offset = _nul_chk_table_offset; 719 _compile_id = compile_id; 720 _comp_level = CompLevel_none; 721 _entry_point = code_begin() + offsets->value(CodeOffsets::Entry); 722 _verified_entry_point = code_begin() + offsets->value(CodeOffsets::Verified_Entry); 723 _osr_entry_point = NULL; 724 _exception_cache = NULL; 725 _pc_desc_cache.reset_to(NULL); 726 _hotness_counter = NMethodSweeper::hotness_counter_reset_val(); 727 728 code_buffer->copy_values_to(this); 729 if (ScavengeRootsInCode) { 730 if (detect_scavenge_root_oops()) { 731 CodeCache::add_scavenge_root_nmethod(this); 732 } 733 Universe::heap()->register_nmethod(this); 734 } 735 debug_only(verify_scavenge_root_oops()); 736 CodeCache::commit(this); 737 } 738 739 if (PrintNativeNMethods || PrintDebugInfo || PrintRelocations || PrintDependencies) { 740 ttyLocker ttyl; // keep the following output all in one block 741 // This output goes directly to the tty, not the compiler log. 742 // To enable tools to match it up with the compilation activity, 743 // be sure to tag this tty output with the compile ID. 744 if (xtty != NULL) { 745 xtty->begin_head("print_native_nmethod"); 746 xtty->method(_method); 747 xtty->stamp(); 748 xtty->end_head(" address='" INTPTR_FORMAT "'", (intptr_t) this); 749 } 750 // print the header part first 751 print(); 752 // then print the requested information 753 if (PrintNativeNMethods) { 754 print_code(); 755 if (oop_maps != NULL) { 756 oop_maps->print(); 757 } 758 } 759 if (PrintRelocations) { 760 print_relocations(); 761 } 762 if (xtty != NULL) { 763 xtty->tail("print_native_nmethod"); 764 } 765 } 766 } 767 768 void* nmethod::operator new(size_t size, int nmethod_size, int comp_level) throw () { 769 return CodeCache::allocate(nmethod_size, CodeCache::get_code_blob_type(comp_level)); 770 } 771 772 nmethod::nmethod( 773 Method* method, 774 int nmethod_size, 775 int compile_id, 776 int entry_bci, 777 CodeOffsets* offsets, 778 int orig_pc_offset, 779 DebugInformationRecorder* debug_info, 780 Dependencies* dependencies, 781 CodeBuffer *code_buffer, 782 int frame_size, 783 OopMapSet* oop_maps, 784 ExceptionHandlerTable* handler_table, 785 ImplicitExceptionTable* nul_chk_table, 786 AbstractCompiler* compiler, 787 int comp_level 788 #if INCLUDE_JVMCI 789 , Handle installed_code, 790 Handle speculation_log 791 #endif 792 ) 793 : CodeBlob("nmethod", code_buffer, sizeof(nmethod), 794 nmethod_size, offsets->value(CodeOffsets::Frame_Complete), frame_size, oop_maps), 795 _native_receiver_sp_offset(in_ByteSize(-1)), 796 _native_basic_lock_sp_offset(in_ByteSize(-1)) 797 { 798 assert(debug_info->oop_recorder() == code_buffer->oop_recorder(), "shared OR"); 799 { 800 debug_only(NoSafepointVerifier nsv;) 801 assert_locked_or_safepoint(CodeCache_lock); 802 803 init_defaults(); 804 _method = method; 805 _entry_bci = entry_bci; 806 _compile_id = compile_id; 807 _comp_level = comp_level; 808 _compiler = compiler; 809 _orig_pc_offset = orig_pc_offset; 810 _hotness_counter = NMethodSweeper::hotness_counter_reset_val(); 811 812 // Section offsets 813 _consts_offset = content_offset() + code_buffer->total_offset_of(code_buffer->consts()); 814 _stub_offset = content_offset() + code_buffer->total_offset_of(code_buffer->stubs()); 815 816 #if INCLUDE_JVMCI 817 _jvmci_installed_code = installed_code(); 818 _speculation_log = (instanceOop)speculation_log(); 819 820 if (compiler->is_jvmci()) { 821 // JVMCI might not produce any stub sections 822 if (offsets->value(CodeOffsets::Exceptions) != -1) { 823 _exception_offset = code_offset() + offsets->value(CodeOffsets::Exceptions); 824 } else { 825 _exception_offset = -1; 826 } 827 if (offsets->value(CodeOffsets::Deopt) != -1) { 828 _deoptimize_offset = code_offset() + offsets->value(CodeOffsets::Deopt); 829 } else { 830 _deoptimize_offset = -1; 831 } 832 if (offsets->value(CodeOffsets::DeoptMH) != -1) { 833 _deoptimize_mh_offset = code_offset() + offsets->value(CodeOffsets::DeoptMH); 834 } else { 835 _deoptimize_mh_offset = -1; 836 } 837 } else { 838 #endif 839 // Exception handler and deopt handler are in the stub section 840 assert(offsets->value(CodeOffsets::Exceptions) != -1, "must be set"); 841 assert(offsets->value(CodeOffsets::Deopt ) != -1, "must be set"); 842 843 _exception_offset = _stub_offset + offsets->value(CodeOffsets::Exceptions); 844 _deoptimize_offset = _stub_offset + offsets->value(CodeOffsets::Deopt); 845 if (offsets->value(CodeOffsets::DeoptMH) != -1) { 846 _deoptimize_mh_offset = _stub_offset + offsets->value(CodeOffsets::DeoptMH); 847 } else { 848 _deoptimize_mh_offset = -1; 849 #if INCLUDE_JVMCI 850 } 851 #endif 852 } 853 if (offsets->value(CodeOffsets::UnwindHandler) != -1) { 854 _unwind_handler_offset = code_offset() + offsets->value(CodeOffsets::UnwindHandler); 855 } else { 856 _unwind_handler_offset = -1; 857 } 858 859 _oops_offset = data_offset(); 860 _metadata_offset = _oops_offset + round_to(code_buffer->total_oop_size(), oopSize); 861 _scopes_data_offset = _metadata_offset + round_to(code_buffer->total_metadata_size(), wordSize); 862 863 _scopes_pcs_offset = _scopes_data_offset + round_to(debug_info->data_size (), oopSize); 864 _dependencies_offset = _scopes_pcs_offset + adjust_pcs_size(debug_info->pcs_size()); 865 _handler_table_offset = _dependencies_offset + round_to(dependencies->size_in_bytes (), oopSize); 866 _nul_chk_table_offset = _handler_table_offset + round_to(handler_table->size_in_bytes(), oopSize); 867 _nmethod_end_offset = _nul_chk_table_offset + round_to(nul_chk_table->size_in_bytes(), oopSize); 868 869 _entry_point = code_begin() + offsets->value(CodeOffsets::Entry); 870 _verified_entry_point = code_begin() + offsets->value(CodeOffsets::Verified_Entry); 871 _osr_entry_point = code_begin() + offsets->value(CodeOffsets::OSR_Entry); 872 _exception_cache = NULL; 873 _pc_desc_cache.reset_to(scopes_pcs_begin()); 874 875 // Copy contents of ScopeDescRecorder to nmethod 876 code_buffer->copy_values_to(this); 877 debug_info->copy_to(this); 878 dependencies->copy_to(this); 879 if (ScavengeRootsInCode) { 880 if (detect_scavenge_root_oops()) { 881 CodeCache::add_scavenge_root_nmethod(this); 882 } 883 Universe::heap()->register_nmethod(this); 884 } 885 debug_only(verify_scavenge_root_oops()); 886 887 CodeCache::commit(this); 888 889 // Copy contents of ExceptionHandlerTable to nmethod 890 handler_table->copy_to(this); 891 nul_chk_table->copy_to(this); 892 893 // we use the information of entry points to find out if a method is 894 // static or non static 895 assert(compiler->is_c2() || compiler->is_jvmci() || 896 _method->is_static() == (entry_point() == _verified_entry_point), 897 " entry points must be same for static methods and vice versa"); 898 } 899 } 900 901 // Print a short set of xml attributes to identify this nmethod. The 902 // output should be embedded in some other element. 903 void nmethod::log_identity(xmlStream* log) const { 904 log->print(" compile_id='%d'", compile_id()); 905 const char* nm_kind = compile_kind(); 906 if (nm_kind != NULL) log->print(" compile_kind='%s'", nm_kind); 907 if (compiler() != NULL) { 908 log->print(" compiler='%s'", compiler()->name()); 909 } 910 if (TieredCompilation) { 911 log->print(" level='%d'", comp_level()); 912 } 913 } 914 915 916 #define LOG_OFFSET(log, name) \ 917 if (p2i(name##_end()) - p2i(name##_begin())) \ 918 log->print(" " XSTR(name) "_offset='" INTX_FORMAT "'" , \ 919 p2i(name##_begin()) - p2i(this)) 920 921 922 void nmethod::log_new_nmethod() const { 923 if (LogCompilation && xtty != NULL) { 924 ttyLocker ttyl; 925 HandleMark hm; 926 xtty->begin_elem("nmethod"); 927 log_identity(xtty); 928 xtty->print(" entry='" INTPTR_FORMAT "' size='%d'", p2i(code_begin()), size()); 929 xtty->print(" address='" INTPTR_FORMAT "'", p2i(this)); 930 931 LOG_OFFSET(xtty, relocation); 932 LOG_OFFSET(xtty, consts); 933 LOG_OFFSET(xtty, insts); 934 LOG_OFFSET(xtty, stub); 935 LOG_OFFSET(xtty, scopes_data); 936 LOG_OFFSET(xtty, scopes_pcs); 937 LOG_OFFSET(xtty, dependencies); 938 LOG_OFFSET(xtty, handler_table); 939 LOG_OFFSET(xtty, nul_chk_table); 940 LOG_OFFSET(xtty, oops); 941 LOG_OFFSET(xtty, metadata); 942 943 xtty->method(method()); 944 xtty->stamp(); 945 xtty->end_elem(); 946 } 947 } 948 949 #undef LOG_OFFSET 950 951 952 // Print out more verbose output usually for a newly created nmethod. 953 void nmethod::print_on(outputStream* st, const char* msg) const { 954 if (st != NULL) { 955 ttyLocker ttyl; 956 if (WizardMode) { 957 CompileTask::print(st, this, msg, /*short_form:*/ true); 958 st->print_cr(" (" INTPTR_FORMAT ")", p2i(this)); 959 } else { 960 CompileTask::print(st, this, msg, /*short_form:*/ false); 961 } 962 } 963 } 964 965 966 void nmethod::print_nmethod(bool printmethod) { 967 ttyLocker ttyl; // keep the following output all in one block 968 if (xtty != NULL) { 969 xtty->begin_head("print_nmethod"); 970 xtty->stamp(); 971 xtty->end_head(); 972 } 973 // print the header part first 974 print(); 975 // then print the requested information 976 if (printmethod) { 977 print_code(); 978 print_pcs(); 979 if (oop_maps()) { 980 oop_maps()->print(); 981 } 982 } 983 if (printmethod || PrintDebugInfo || CompilerOracle::has_option_string(_method, "PrintDebugInfo")) { 984 print_scopes(); 985 } 986 if (printmethod || PrintRelocations || CompilerOracle::has_option_string(_method, "PrintRelocations")) { 987 print_relocations(); 988 } 989 if (printmethod || PrintDependencies || CompilerOracle::has_option_string(_method, "PrintDependencies")) { 990 print_dependencies(); 991 } 992 if (printmethod || PrintExceptionHandlers) { 993 print_handler_table(); 994 print_nul_chk_table(); 995 } 996 if (printmethod) { 997 print_recorded_oops(); 998 print_recorded_metadata(); 999 } 1000 if (xtty != NULL) { 1001 xtty->tail("print_nmethod"); 1002 } 1003 } 1004 1005 1006 // Promote one word from an assembly-time handle to a live embedded oop. 1007 inline void nmethod::initialize_immediate_oop(oop* dest, jobject handle) { 1008 if (handle == NULL || 1009 // As a special case, IC oops are initialized to 1 or -1. 1010 handle == (jobject) Universe::non_oop_word()) { 1011 (*dest) = (oop) handle; 1012 } else { 1013 (*dest) = JNIHandles::resolve_non_null(handle); 1014 } 1015 } 1016 1017 1018 // Have to have the same name because it's called by a template 1019 void nmethod::copy_values(GrowableArray<jobject>* array) { 1020 int length = array->length(); 1021 assert((address)(oops_begin() + length) <= (address)oops_end(), "oops big enough"); 1022 oop* dest = oops_begin(); 1023 for (int index = 0 ; index < length; index++) { 1024 initialize_immediate_oop(&dest[index], array->at(index)); 1025 } 1026 1027 // Now we can fix up all the oops in the code. We need to do this 1028 // in the code because the assembler uses jobjects as placeholders. 1029 // The code and relocations have already been initialized by the 1030 // CodeBlob constructor, so it is valid even at this early point to 1031 // iterate over relocations and patch the code. 1032 fix_oop_relocations(NULL, NULL, /*initialize_immediates=*/ true); 1033 } 1034 1035 void nmethod::copy_values(GrowableArray<Metadata*>* array) { 1036 int length = array->length(); 1037 assert((address)(metadata_begin() + length) <= (address)metadata_end(), "big enough"); 1038 Metadata** dest = metadata_begin(); 1039 for (int index = 0 ; index < length; index++) { 1040 dest[index] = array->at(index); 1041 } 1042 } 1043 1044 bool nmethod::is_at_poll_return(address pc) { 1045 RelocIterator iter(this, pc, pc+1); 1046 while (iter.next()) { 1047 if (iter.type() == relocInfo::poll_return_type) 1048 return true; 1049 } 1050 return false; 1051 } 1052 1053 1054 bool nmethod::is_at_poll_or_poll_return(address pc) { 1055 RelocIterator iter(this, pc, pc+1); 1056 while (iter.next()) { 1057 relocInfo::relocType t = iter.type(); 1058 if (t == relocInfo::poll_return_type || t == relocInfo::poll_type) 1059 return true; 1060 } 1061 return false; 1062 } 1063 1064 1065 void nmethod::fix_oop_relocations(address begin, address end, bool initialize_immediates) { 1066 // re-patch all oop-bearing instructions, just in case some oops moved 1067 RelocIterator iter(this, begin, end); 1068 while (iter.next()) { 1069 if (iter.type() == relocInfo::oop_type) { 1070 oop_Relocation* reloc = iter.oop_reloc(); 1071 if (initialize_immediates && reloc->oop_is_immediate()) { 1072 oop* dest = reloc->oop_addr(); 1073 initialize_immediate_oop(dest, (jobject) *dest); 1074 } 1075 // Refresh the oop-related bits of this instruction. 1076 reloc->fix_oop_relocation(); 1077 } else if (iter.type() == relocInfo::metadata_type) { 1078 metadata_Relocation* reloc = iter.metadata_reloc(); 1079 reloc->fix_metadata_relocation(); 1080 } 1081 } 1082 } 1083 1084 1085 void nmethod::verify_oop_relocations() { 1086 // Ensure sure that the code matches the current oop values 1087 RelocIterator iter(this, NULL, NULL); 1088 while (iter.next()) { 1089 if (iter.type() == relocInfo::oop_type) { 1090 oop_Relocation* reloc = iter.oop_reloc(); 1091 if (!reloc->oop_is_immediate()) { 1092 reloc->verify_oop_relocation(); 1093 } 1094 } 1095 } 1096 } 1097 1098 1099 ScopeDesc* nmethod::scope_desc_at(address pc) { 1100 PcDesc* pd = pc_desc_at(pc); 1101 guarantee(pd != NULL, "scope must be present"); 1102 return new ScopeDesc(this, pd->scope_decode_offset(), 1103 pd->obj_decode_offset(), pd->should_reexecute(), pd->rethrow_exception(), 1104 pd->return_oop()); 1105 } 1106 1107 1108 void nmethod::clear_inline_caches() { 1109 assert(SafepointSynchronize::is_at_safepoint(), "cleaning of IC's only allowed at safepoint"); 1110 if (is_zombie()) { 1111 return; 1112 } 1113 1114 RelocIterator iter(this); 1115 while (iter.next()) { 1116 iter.reloc()->clear_inline_cache(); 1117 } 1118 } 1119 1120 // Clear ICStubs of all compiled ICs 1121 void nmethod::clear_ic_stubs() { 1122 assert_locked_or_safepoint(CompiledIC_lock); 1123 RelocIterator iter(this); 1124 while(iter.next()) { 1125 if (iter.type() == relocInfo::virtual_call_type) { 1126 CompiledIC* ic = CompiledIC_at(&iter); 1127 ic->clear_ic_stub(); 1128 } 1129 } 1130 } 1131 1132 1133 void nmethod::cleanup_inline_caches() { 1134 assert_locked_or_safepoint(CompiledIC_lock); 1135 1136 // If the method is not entrant or zombie then a JMP is plastered over the 1137 // first few bytes. If an oop in the old code was there, that oop 1138 // should not get GC'd. Skip the first few bytes of oops on 1139 // not-entrant methods. 1140 address low_boundary = verified_entry_point(); 1141 if (!is_in_use()) { 1142 low_boundary += NativeJump::instruction_size; 1143 // %%% Note: On SPARC we patch only a 4-byte trap, not a full NativeJump. 1144 // This means that the low_boundary is going to be a little too high. 1145 // This shouldn't matter, since oops of non-entrant methods are never used. 1146 // In fact, why are we bothering to look at oops in a non-entrant method?? 1147 } 1148 1149 // Find all calls in an nmethod and clear the ones that point to non-entrant, 1150 // zombie and unloaded nmethods. 1151 ResourceMark rm; 1152 RelocIterator iter(this, low_boundary); 1153 while(iter.next()) { 1154 switch(iter.type()) { 1155 case relocInfo::virtual_call_type: 1156 case relocInfo::opt_virtual_call_type: { 1157 CompiledIC *ic = CompiledIC_at(&iter); 1158 // Ok, to lookup references to zombies here 1159 CodeBlob *cb = CodeCache::find_blob_unsafe(ic->ic_destination()); 1160 if( cb != NULL && cb->is_nmethod() ) { 1161 nmethod* nm = (nmethod*)cb; 1162 // Clean inline caches pointing to zombie, non-entrant and unloaded methods 1163 if (!nm->is_in_use() || (nm->method()->code() != nm)) ic->set_to_clean(is_alive()); 1164 } 1165 break; 1166 } 1167 case relocInfo::static_call_type: { 1168 CompiledStaticCall *csc = compiledStaticCall_at(iter.reloc()); 1169 CodeBlob *cb = CodeCache::find_blob_unsafe(csc->destination()); 1170 if( cb != NULL && cb->is_nmethod() ) { 1171 nmethod* nm = (nmethod*)cb; 1172 // Clean inline caches pointing to zombie, non-entrant and unloaded methods 1173 if (!nm->is_in_use() || (nm->method()->code() != nm)) csc->set_to_clean(); 1174 } 1175 break; 1176 } 1177 } 1178 } 1179 } 1180 1181 void nmethod::verify_clean_inline_caches() { 1182 assert_locked_or_safepoint(CompiledIC_lock); 1183 1184 // If the method is not entrant or zombie then a JMP is plastered over the 1185 // first few bytes. If an oop in the old code was there, that oop 1186 // should not get GC'd. Skip the first few bytes of oops on 1187 // not-entrant methods. 1188 address low_boundary = verified_entry_point(); 1189 if (!is_in_use()) { 1190 low_boundary += NativeJump::instruction_size; 1191 // %%% Note: On SPARC we patch only a 4-byte trap, not a full NativeJump. 1192 // This means that the low_boundary is going to be a little too high. 1193 // This shouldn't matter, since oops of non-entrant methods are never used. 1194 // In fact, why are we bothering to look at oops in a non-entrant method?? 1195 } 1196 1197 ResourceMark rm; 1198 RelocIterator iter(this, low_boundary); 1199 while(iter.next()) { 1200 switch(iter.type()) { 1201 case relocInfo::virtual_call_type: 1202 case relocInfo::opt_virtual_call_type: { 1203 CompiledIC *ic = CompiledIC_at(&iter); 1204 // Ok, to lookup references to zombies here 1205 CodeBlob *cb = CodeCache::find_blob_unsafe(ic->ic_destination()); 1206 if( cb != NULL && cb->is_nmethod() ) { 1207 nmethod* nm = (nmethod*)cb; 1208 // Verify that inline caches pointing to both zombie and not_entrant methods are clean 1209 if (!nm->is_in_use() || (nm->method()->code() != nm)) { 1210 assert(ic->is_clean(), "IC should be clean"); 1211 } 1212 } 1213 break; 1214 } 1215 case relocInfo::static_call_type: { 1216 CompiledStaticCall *csc = compiledStaticCall_at(iter.reloc()); 1217 CodeBlob *cb = CodeCache::find_blob_unsafe(csc->destination()); 1218 if( cb != NULL && cb->is_nmethod() ) { 1219 nmethod* nm = (nmethod*)cb; 1220 // Verify that inline caches pointing to both zombie and not_entrant methods are clean 1221 if (!nm->is_in_use() || (nm->method()->code() != nm)) { 1222 assert(csc->is_clean(), "IC should be clean"); 1223 } 1224 } 1225 break; 1226 } 1227 } 1228 } 1229 } 1230 1231 int nmethod::verify_icholder_relocations() { 1232 int count = 0; 1233 1234 RelocIterator iter(this); 1235 while(iter.next()) { 1236 if (iter.type() == relocInfo::virtual_call_type) { 1237 if (CompiledIC::is_icholder_call_site(iter.virtual_call_reloc())) { 1238 CompiledIC *ic = CompiledIC_at(&iter); 1239 if (TraceCompiledIC) { 1240 tty->print("noticed icholder " INTPTR_FORMAT " ", p2i(ic->cached_icholder())); 1241 ic->print(); 1242 } 1243 assert(ic->cached_icholder() != NULL, "must be non-NULL"); 1244 count++; 1245 } 1246 } 1247 } 1248 1249 return count; 1250 } 1251 1252 // This is a private interface with the sweeper. 1253 void nmethod::mark_as_seen_on_stack() { 1254 assert(is_alive(), "Must be an alive method"); 1255 // Set the traversal mark to ensure that the sweeper does 2 1256 // cleaning passes before moving to zombie. 1257 set_stack_traversal_mark(NMethodSweeper::traversal_count()); 1258 } 1259 1260 // Tell if a non-entrant method can be converted to a zombie (i.e., 1261 // there are no activations on the stack, not in use by the VM, 1262 // and not in use by the ServiceThread) 1263 bool nmethod::can_convert_to_zombie() { 1264 assert(is_not_entrant(), "must be a non-entrant method"); 1265 1266 // Since the nmethod sweeper only does partial sweep the sweeper's traversal 1267 // count can be greater than the stack traversal count before it hits the 1268 // nmethod for the second time. 1269 return stack_traversal_mark()+1 < NMethodSweeper::traversal_count() && 1270 !is_locked_by_vm(); 1271 } 1272 1273 void nmethod::inc_decompile_count() { 1274 if (!is_compiled_by_c2() && !is_compiled_by_jvmci()) return; 1275 // Could be gated by ProfileTraps, but do not bother... 1276 Method* m = method(); 1277 if (m == NULL) return; 1278 MethodData* mdo = m->method_data(); 1279 if (mdo == NULL) return; 1280 // There is a benign race here. See comments in methodData.hpp. 1281 mdo->inc_decompile_count(); 1282 } 1283 1284 void nmethod::increase_unloading_clock() { 1285 _global_unloading_clock++; 1286 if (_global_unloading_clock == 0) { 1287 // _nmethods are allocated with _unloading_clock == 0, 1288 // so 0 is never used as a clock value. 1289 _global_unloading_clock = 1; 1290 } 1291 } 1292 1293 void nmethod::set_unloading_clock(unsigned char unloading_clock) { 1294 OrderAccess::release_store((volatile jubyte*)&_unloading_clock, unloading_clock); 1295 } 1296 1297 unsigned char nmethod::unloading_clock() { 1298 return (unsigned char)OrderAccess::load_acquire((volatile jubyte*)&_unloading_clock); 1299 } 1300 1301 void nmethod::make_unloaded(BoolObjectClosure* is_alive, oop cause) { 1302 1303 post_compiled_method_unload(); 1304 1305 // Since this nmethod is being unloaded, make sure that dependencies 1306 // recorded in instanceKlasses get flushed and pass non-NULL closure to 1307 // indicate that this work is being done during a GC. 1308 assert(Universe::heap()->is_gc_active(), "should only be called during gc"); 1309 assert(is_alive != NULL, "Should be non-NULL"); 1310 // A non-NULL is_alive closure indicates that this is being called during GC. 1311 flush_dependencies(is_alive); 1312 1313 // Break cycle between nmethod & method 1314 if (log_is_enabled(Trace, classunload)) { 1315 outputStream* log = LogHandle(classunload)::trace_stream(); 1316 log->print_cr("making nmethod " INTPTR_FORMAT 1317 " unloadable, Method*(" INTPTR_FORMAT 1318 "), cause(" INTPTR_FORMAT ")", 1319 p2i(this), p2i(_method), p2i(cause)); 1320 if (!Universe::heap()->is_gc_active()) 1321 cause->klass()->print_on(log); 1322 } 1323 // Unlink the osr method, so we do not look this up again 1324 if (is_osr_method()) { 1325 invalidate_osr_method(); 1326 } 1327 // If _method is already NULL the Method* is about to be unloaded, 1328 // so we don't have to break the cycle. Note that it is possible to 1329 // have the Method* live here, in case we unload the nmethod because 1330 // it is pointing to some oop (other than the Method*) being unloaded. 1331 if (_method != NULL) { 1332 // OSR methods point to the Method*, but the Method* does not 1333 // point back! 1334 if (_method->code() == this) { 1335 _method->clear_code(); // Break a cycle 1336 } 1337 _method = NULL; // Clear the method of this dead nmethod 1338 } 1339 1340 // Make the class unloaded - i.e., change state and notify sweeper 1341 assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint"); 1342 if (is_in_use()) { 1343 // Transitioning directly from live to unloaded -- so 1344 // we need to force a cache clean-up; remember this 1345 // for later on. 1346 CodeCache::set_needs_cache_clean(true); 1347 } 1348 1349 // Unregister must be done before the state change 1350 Universe::heap()->unregister_nmethod(this); 1351 1352 _state = unloaded; 1353 1354 // Log the unloading. 1355 log_state_change(); 1356 1357 #if INCLUDE_JVMCI 1358 // The method can only be unloaded after the pointer to the installed code 1359 // Java wrapper is no longer alive. Here we need to clear out this weak 1360 // reference to the dead object. Nulling out the reference has to happen 1361 // after the method is unregistered since the original value may be still 1362 // tracked by the rset. 1363 maybe_invalidate_installed_code(); 1364 // Clear these out after the nmethod has been unregistered and any 1365 // updates to the InstalledCode instance have been performed. 1366 _jvmci_installed_code = NULL; 1367 _speculation_log = NULL; 1368 #endif 1369 1370 // The Method* is gone at this point 1371 assert(_method == NULL, "Tautology"); 1372 1373 set_osr_link(NULL); 1374 //set_scavenge_root_link(NULL); // done by prune_scavenge_root_nmethods 1375 NMethodSweeper::report_state_change(this); 1376 } 1377 1378 void nmethod::invalidate_osr_method() { 1379 assert(_entry_bci != InvocationEntryBci, "wrong kind of nmethod"); 1380 // Remove from list of active nmethods 1381 if (method() != NULL) 1382 method()->method_holder()->remove_osr_nmethod(this); 1383 } 1384 1385 void nmethod::log_state_change() const { 1386 if (LogCompilation) { 1387 if (xtty != NULL) { 1388 ttyLocker ttyl; // keep the following output all in one block 1389 if (_state == unloaded) { 1390 xtty->begin_elem("make_unloaded thread='" UINTX_FORMAT "'", 1391 os::current_thread_id()); 1392 } else { 1393 xtty->begin_elem("make_not_entrant thread='" UINTX_FORMAT "'%s", 1394 os::current_thread_id(), 1395 (_state == zombie ? " zombie='1'" : "")); 1396 } 1397 log_identity(xtty); 1398 xtty->stamp(); 1399 xtty->end_elem(); 1400 } 1401 } 1402 if (PrintCompilation && _state != unloaded) { 1403 print_on(tty, _state == zombie ? "made zombie" : "made not entrant"); 1404 } 1405 } 1406 1407 /** 1408 * Common functionality for both make_not_entrant and make_zombie 1409 */ 1410 bool nmethod::make_not_entrant_or_zombie(unsigned int state) { 1411 assert(state == zombie || state == not_entrant, "must be zombie or not_entrant"); 1412 assert(!is_zombie(), "should not already be a zombie"); 1413 1414 // Make sure neither the nmethod nor the method is flushed in case of a safepoint in code below. 1415 nmethodLocker nml(this); 1416 methodHandle the_method(method()); 1417 NoSafepointVerifier nsv; 1418 1419 // during patching, depending on the nmethod state we must notify the GC that 1420 // code has been unloaded, unregistering it. We cannot do this right while 1421 // holding the Patching_lock because we need to use the CodeCache_lock. This 1422 // would be prone to deadlocks. 1423 // This flag is used to remember whether we need to later lock and unregister. 1424 bool nmethod_needs_unregister = false; 1425 1426 { 1427 // invalidate osr nmethod before acquiring the patching lock since 1428 // they both acquire leaf locks and we don't want a deadlock. 1429 // This logic is equivalent to the logic below for patching the 1430 // verified entry point of regular methods. 1431 if (is_osr_method()) { 1432 // this effectively makes the osr nmethod not entrant 1433 invalidate_osr_method(); 1434 } 1435 1436 // Enter critical section. Does not block for safepoint. 1437 MutexLockerEx pl(Patching_lock, Mutex::_no_safepoint_check_flag); 1438 1439 if (_state == state) { 1440 // another thread already performed this transition so nothing 1441 // to do, but return false to indicate this. 1442 return false; 1443 } 1444 1445 // The caller can be calling the method statically or through an inline 1446 // cache call. 1447 if (!is_osr_method() && !is_not_entrant()) { 1448 NativeJump::patch_verified_entry(entry_point(), verified_entry_point(), 1449 SharedRuntime::get_handle_wrong_method_stub()); 1450 } 1451 1452 if (is_in_use()) { 1453 // It's a true state change, so mark the method as decompiled. 1454 // Do it only for transition from alive. 1455 inc_decompile_count(); 1456 } 1457 1458 // If the state is becoming a zombie, signal to unregister the nmethod with 1459 // the heap. 1460 // This nmethod may have already been unloaded during a full GC. 1461 if ((state == zombie) && !is_unloaded()) { 1462 nmethod_needs_unregister = true; 1463 } 1464 1465 // Must happen before state change. Otherwise we have a race condition in 1466 // nmethod::can_not_entrant_be_converted(). I.e., a method can immediately 1467 // transition its state from 'not_entrant' to 'zombie' without having to wait 1468 // for stack scanning. 1469 if (state == not_entrant) { 1470 mark_as_seen_on_stack(); 1471 OrderAccess::storestore(); 1472 } 1473 1474 // Change state 1475 _state = state; 1476 1477 // Log the transition once 1478 log_state_change(); 1479 1480 // Invalidate while holding the patching lock 1481 JVMCI_ONLY(maybe_invalidate_installed_code()); 1482 1483 // Remove nmethod from method. 1484 // We need to check if both the _code and _from_compiled_code_entry_point 1485 // refer to this nmethod because there is a race in setting these two fields 1486 // in Method* as seen in bugid 4947125. 1487 // If the vep() points to the zombie nmethod, the memory for the nmethod 1488 // could be flushed and the compiler and vtable stubs could still call 1489 // through it. 1490 if (method() != NULL && (method()->code() == this || 1491 method()->from_compiled_entry() == verified_entry_point())) { 1492 HandleMark hm; 1493 method()->clear_code(); 1494 } 1495 } // leave critical region under Patching_lock 1496 1497 // When the nmethod becomes zombie it is no longer alive so the 1498 // dependencies must be flushed. nmethods in the not_entrant 1499 // state will be flushed later when the transition to zombie 1500 // happens or they get unloaded. 1501 if (state == zombie) { 1502 { 1503 // Flushing dependecies must be done before any possible 1504 // safepoint can sneak in, otherwise the oops used by the 1505 // dependency logic could have become stale. 1506 MutexLockerEx mu(CodeCache_lock, Mutex::_no_safepoint_check_flag); 1507 if (nmethod_needs_unregister) { 1508 Universe::heap()->unregister_nmethod(this); 1509 #ifdef JVMCI 1510 _jvmci_installed_code = NULL; 1511 _speculation_log = NULL; 1512 #endif 1513 } 1514 flush_dependencies(NULL); 1515 } 1516 1517 // zombie only - if a JVMTI agent has enabled the CompiledMethodUnload 1518 // event and it hasn't already been reported for this nmethod then 1519 // report it now. The event may have been reported earilier if the GC 1520 // marked it for unloading). JvmtiDeferredEventQueue support means 1521 // we no longer go to a safepoint here. 1522 post_compiled_method_unload(); 1523 1524 #ifdef ASSERT 1525 // It's no longer safe to access the oops section since zombie 1526 // nmethods aren't scanned for GC. 1527 _oops_are_stale = true; 1528 #endif 1529 // the Method may be reclaimed by class unloading now that the 1530 // nmethod is in zombie state 1531 set_method(NULL); 1532 } else { 1533 assert(state == not_entrant, "other cases may need to be handled differently"); 1534 } 1535 1536 if (TraceCreateZombies) { 1537 ResourceMark m; 1538 tty->print_cr("nmethod <" INTPTR_FORMAT "> %s code made %s", p2i(this), this->method() ? this->method()->name_and_sig_as_C_string() : "null", (state == not_entrant) ? "not entrant" : "zombie"); 1539 } 1540 1541 NMethodSweeper::report_state_change(this); 1542 return true; 1543 } 1544 1545 void nmethod::flush() { 1546 // Note that there are no valid oops in the nmethod anymore. 1547 assert(is_zombie() || (is_osr_method() && is_unloaded()), "must be a zombie method"); 1548 assert(is_marked_for_reclamation() || (is_osr_method() && is_unloaded()), "must be marked for reclamation"); 1549 1550 assert (!is_locked_by_vm(), "locked methods shouldn't be flushed"); 1551 assert_locked_or_safepoint(CodeCache_lock); 1552 1553 // completely deallocate this method 1554 Events::log(JavaThread::current(), "flushing nmethod " INTPTR_FORMAT, p2i(this)); 1555 if (PrintMethodFlushing) { 1556 tty->print_cr("*flushing nmethod %3d/" INTPTR_FORMAT ". Live blobs:" UINT32_FORMAT 1557 "/Free CodeCache:" SIZE_FORMAT "Kb", 1558 _compile_id, p2i(this), CodeCache::blob_count(), 1559 CodeCache::unallocated_capacity(CodeCache::get_code_blob_type(this))/1024); 1560 } 1561 1562 // We need to deallocate any ExceptionCache data. 1563 // Note that we do not need to grab the nmethod lock for this, it 1564 // better be thread safe if we're disposing of it! 1565 ExceptionCache* ec = exception_cache(); 1566 set_exception_cache(NULL); 1567 while(ec != NULL) { 1568 ExceptionCache* next = ec->next(); 1569 delete ec; 1570 ec = next; 1571 } 1572 1573 if (on_scavenge_root_list()) { 1574 CodeCache::drop_scavenge_root_nmethod(this); 1575 } 1576 1577 #ifdef SHARK 1578 ((SharkCompiler *) compiler())->free_compiled_method(insts_begin()); 1579 #endif // SHARK 1580 1581 ((CodeBlob*)(this))->flush(); 1582 1583 CodeCache::free(this); 1584 } 1585 1586 // 1587 // Notify all classes this nmethod is dependent on that it is no 1588 // longer dependent. This should only be called in two situations. 1589 // First, when a nmethod transitions to a zombie all dependents need 1590 // to be clear. Since zombification happens at a safepoint there's no 1591 // synchronization issues. The second place is a little more tricky. 1592 // During phase 1 of mark sweep class unloading may happen and as a 1593 // result some nmethods may get unloaded. In this case the flushing 1594 // of dependencies must happen during phase 1 since after GC any 1595 // dependencies in the unloaded nmethod won't be updated, so 1596 // traversing the dependency information in unsafe. In that case this 1597 // function is called with a non-NULL argument and this function only 1598 // notifies instanceKlasses that are reachable 1599 1600 void nmethod::flush_dependencies(BoolObjectClosure* is_alive) { 1601 assert_locked_or_safepoint(CodeCache_lock); 1602 assert(Universe::heap()->is_gc_active() == (is_alive != NULL), 1603 "is_alive is non-NULL if and only if we are called during GC"); 1604 if (!has_flushed_dependencies()) { 1605 set_has_flushed_dependencies(); 1606 for (Dependencies::DepStream deps(this); deps.next(); ) { 1607 if (deps.type() == Dependencies::call_site_target_value) { 1608 // CallSite dependencies are managed on per-CallSite instance basis. 1609 oop call_site = deps.argument_oop(0); 1610 MethodHandles::remove_dependent_nmethod(call_site, this); 1611 } else { 1612 Klass* klass = deps.context_type(); 1613 if (klass == NULL) { 1614 continue; // ignore things like evol_method 1615 } 1616 // During GC the is_alive closure is non-NULL, and is used to 1617 // determine liveness of dependees that need to be updated. 1618 if (is_alive == NULL || klass->is_loader_alive(is_alive)) { 1619 // The GC defers deletion of this entry, since there might be multiple threads 1620 // iterating over the _dependencies graph. Other call paths are single-threaded 1621 // and may delete it immediately. 1622 bool delete_immediately = is_alive == NULL; 1623 InstanceKlass::cast(klass)->remove_dependent_nmethod(this, delete_immediately); 1624 } 1625 } 1626 } 1627 } 1628 } 1629 1630 1631 // If this oop is not live, the nmethod can be unloaded. 1632 bool nmethod::can_unload(BoolObjectClosure* is_alive, oop* root, bool unloading_occurred) { 1633 assert(root != NULL, "just checking"); 1634 oop obj = *root; 1635 if (obj == NULL || is_alive->do_object_b(obj)) { 1636 return false; 1637 } 1638 1639 // If ScavengeRootsInCode is true, an nmethod might be unloaded 1640 // simply because one of its constant oops has gone dead. 1641 // No actual classes need to be unloaded in order for this to occur. 1642 assert(unloading_occurred || ScavengeRootsInCode, "Inconsistency in unloading"); 1643 make_unloaded(is_alive, obj); 1644 return true; 1645 } 1646 1647 // ------------------------------------------------------------------ 1648 // post_compiled_method_load_event 1649 // new method for install_code() path 1650 // Transfer information from compilation to jvmti 1651 void nmethod::post_compiled_method_load_event() { 1652 1653 Method* moop = method(); 1654 HOTSPOT_COMPILED_METHOD_LOAD( 1655 (char *) moop->klass_name()->bytes(), 1656 moop->klass_name()->utf8_length(), 1657 (char *) moop->name()->bytes(), 1658 moop->name()->utf8_length(), 1659 (char *) moop->signature()->bytes(), 1660 moop->signature()->utf8_length(), 1661 insts_begin(), insts_size()); 1662 1663 if (JvmtiExport::should_post_compiled_method_load() || 1664 JvmtiExport::should_post_compiled_method_unload()) { 1665 get_and_cache_jmethod_id(); 1666 } 1667 1668 if (JvmtiExport::should_post_compiled_method_load()) { 1669 // Let the Service thread (which is a real Java thread) post the event 1670 MutexLockerEx ml(Service_lock, Mutex::_no_safepoint_check_flag); 1671 JvmtiDeferredEventQueue::enqueue( 1672 JvmtiDeferredEvent::compiled_method_load_event(this)); 1673 } 1674 } 1675 1676 jmethodID nmethod::get_and_cache_jmethod_id() { 1677 if (_jmethod_id == NULL) { 1678 // Cache the jmethod_id since it can no longer be looked up once the 1679 // method itself has been marked for unloading. 1680 _jmethod_id = method()->jmethod_id(); 1681 } 1682 return _jmethod_id; 1683 } 1684 1685 void nmethod::post_compiled_method_unload() { 1686 if (unload_reported()) { 1687 // During unloading we transition to unloaded and then to zombie 1688 // and the unloading is reported during the first transition. 1689 return; 1690 } 1691 1692 assert(_method != NULL && !is_unloaded(), "just checking"); 1693 DTRACE_METHOD_UNLOAD_PROBE(method()); 1694 1695 // If a JVMTI agent has enabled the CompiledMethodUnload event then 1696 // post the event. Sometime later this nmethod will be made a zombie 1697 // by the sweeper but the Method* will not be valid at that point. 1698 // If the _jmethod_id is null then no load event was ever requested 1699 // so don't bother posting the unload. The main reason for this is 1700 // that the jmethodID is a weak reference to the Method* so if 1701 // it's being unloaded there's no way to look it up since the weak 1702 // ref will have been cleared. 1703 if (_jmethod_id != NULL && JvmtiExport::should_post_compiled_method_unload()) { 1704 assert(!unload_reported(), "already unloaded"); 1705 JvmtiDeferredEvent event = 1706 JvmtiDeferredEvent::compiled_method_unload_event(this, 1707 _jmethod_id, insts_begin()); 1708 if (SafepointSynchronize::is_at_safepoint()) { 1709 // Don't want to take the queueing lock. Add it as pending and 1710 // it will get enqueued later. 1711 JvmtiDeferredEventQueue::add_pending_event(event); 1712 } else { 1713 MutexLockerEx ml(Service_lock, Mutex::_no_safepoint_check_flag); 1714 JvmtiDeferredEventQueue::enqueue(event); 1715 } 1716 } 1717 1718 // The JVMTI CompiledMethodUnload event can be enabled or disabled at 1719 // any time. As the nmethod is being unloaded now we mark it has 1720 // having the unload event reported - this will ensure that we don't 1721 // attempt to report the event in the unlikely scenario where the 1722 // event is enabled at the time the nmethod is made a zombie. 1723 set_unload_reported(); 1724 } 1725 1726 void static clean_ic_if_metadata_is_dead(CompiledIC *ic, BoolObjectClosure *is_alive) { 1727 if (ic->is_icholder_call()) { 1728 // The only exception is compiledICHolder oops which may 1729 // yet be marked below. (We check this further below). 1730 CompiledICHolder* cichk_oop = ic->cached_icholder(); 1731 1732 if (cichk_oop->holder_method()->method_holder()->is_loader_alive(is_alive) && 1733 cichk_oop->holder_klass()->is_loader_alive(is_alive)) { 1734 return; 1735 } 1736 } else { 1737 Metadata* ic_oop = ic->cached_metadata(); 1738 if (ic_oop != NULL) { 1739 if (ic_oop->is_klass()) { 1740 if (((Klass*)ic_oop)->is_loader_alive(is_alive)) { 1741 return; 1742 } 1743 } else if (ic_oop->is_method()) { 1744 if (((Method*)ic_oop)->method_holder()->is_loader_alive(is_alive)) { 1745 return; 1746 } 1747 } else { 1748 ShouldNotReachHere(); 1749 } 1750 } 1751 } 1752 1753 ic->set_to_clean(); 1754 } 1755 1756 // This is called at the end of the strong tracing/marking phase of a 1757 // GC to unload an nmethod if it contains otherwise unreachable 1758 // oops. 1759 1760 void nmethod::do_unloading(BoolObjectClosure* is_alive, bool unloading_occurred) { 1761 // Make sure the oop's ready to receive visitors 1762 assert(!is_zombie() && !is_unloaded(), 1763 "should not call follow on zombie or unloaded nmethod"); 1764 1765 // If the method is not entrant then a JMP is plastered over the 1766 // first few bytes. If an oop in the old code was there, that oop 1767 // should not get GC'd. Skip the first few bytes of oops on 1768 // not-entrant methods. 1769 address low_boundary = verified_entry_point(); 1770 if (is_not_entrant()) { 1771 low_boundary += NativeJump::instruction_size; 1772 // %%% Note: On SPARC we patch only a 4-byte trap, not a full NativeJump. 1773 // (See comment above.) 1774 } 1775 1776 // The RedefineClasses() API can cause the class unloading invariant 1777 // to no longer be true. See jvmtiExport.hpp for details. 1778 // Also, leave a debugging breadcrumb in local flag. 1779 if (JvmtiExport::has_redefined_a_class()) { 1780 // This set of the unloading_occurred flag is done before the 1781 // call to post_compiled_method_unload() so that the unloading 1782 // of this nmethod is reported. 1783 unloading_occurred = true; 1784 } 1785 1786 // Exception cache 1787 clean_exception_cache(is_alive); 1788 1789 // If class unloading occurred we first iterate over all inline caches and 1790 // clear ICs where the cached oop is referring to an unloaded klass or method. 1791 // The remaining live cached oops will be traversed in the relocInfo::oop_type 1792 // iteration below. 1793 if (unloading_occurred) { 1794 RelocIterator iter(this, low_boundary); 1795 while(iter.next()) { 1796 if (iter.type() == relocInfo::virtual_call_type) { 1797 CompiledIC *ic = CompiledIC_at(&iter); 1798 clean_ic_if_metadata_is_dead(ic, is_alive); 1799 } 1800 } 1801 } 1802 1803 // Compiled code 1804 { 1805 RelocIterator iter(this, low_boundary); 1806 while (iter.next()) { 1807 if (iter.type() == relocInfo::oop_type) { 1808 oop_Relocation* r = iter.oop_reloc(); 1809 // In this loop, we must only traverse those oops directly embedded in 1810 // the code. Other oops (oop_index>0) are seen as part of scopes_oops. 1811 assert(1 == (r->oop_is_immediate()) + 1812 (r->oop_addr() >= oops_begin() && r->oop_addr() < oops_end()), 1813 "oop must be found in exactly one place"); 1814 if (r->oop_is_immediate() && r->oop_value() != NULL) { 1815 if (can_unload(is_alive, r->oop_addr(), unloading_occurred)) { 1816 return; 1817 } 1818 } 1819 } 1820 } 1821 } 1822 1823 1824 // Scopes 1825 for (oop* p = oops_begin(); p < oops_end(); p++) { 1826 if (*p == Universe::non_oop_word()) continue; // skip non-oops 1827 if (can_unload(is_alive, p, unloading_occurred)) { 1828 return; 1829 } 1830 } 1831 1832 #if INCLUDE_JVMCI 1833 // Follow JVMCI method 1834 BarrierSet* bs = Universe::heap()->barrier_set(); 1835 if (_jvmci_installed_code != NULL) { 1836 if (_jvmci_installed_code->is_a(HotSpotNmethod::klass()) && HotSpotNmethod::isDefault(_jvmci_installed_code)) { 1837 if (!is_alive->do_object_b(_jvmci_installed_code)) { 1838 clear_jvmci_installed_code(); 1839 } 1840 } else { 1841 if (can_unload(is_alive, (oop*)&_jvmci_installed_code, unloading_occurred)) { 1842 return; 1843 } 1844 } 1845 } 1846 1847 if (_speculation_log != NULL) { 1848 if (!is_alive->do_object_b(_speculation_log)) { 1849 bs->write_ref_nmethod_pre(&_speculation_log, this); 1850 _speculation_log = NULL; 1851 bs->write_ref_nmethod_post(&_speculation_log, this); 1852 } 1853 } 1854 #endif 1855 1856 1857 // Ensure that all metadata is still alive 1858 verify_metadata_loaders(low_boundary, is_alive); 1859 } 1860 1861 template <class CompiledICorStaticCall> 1862 static bool clean_if_nmethod_is_unloaded(CompiledICorStaticCall *ic, address addr, BoolObjectClosure *is_alive, nmethod* from) { 1863 // Ok, to lookup references to zombies here 1864 CodeBlob *cb = CodeCache::find_blob_unsafe(addr); 1865 if (cb != NULL && cb->is_nmethod()) { 1866 nmethod* nm = (nmethod*)cb; 1867 1868 if (nm->unloading_clock() != nmethod::global_unloading_clock()) { 1869 // The nmethod has not been processed yet. 1870 return true; 1871 } 1872 1873 // Clean inline caches pointing to both zombie and not_entrant methods 1874 if (!nm->is_in_use() || (nm->method()->code() != nm)) { 1875 ic->set_to_clean(); 1876 assert(ic->is_clean(), "nmethod " PTR_FORMAT "not clean %s", p2i(from), from->method()->name_and_sig_as_C_string()); 1877 } 1878 } 1879 1880 return false; 1881 } 1882 1883 static bool clean_if_nmethod_is_unloaded(CompiledIC *ic, BoolObjectClosure *is_alive, nmethod* from) { 1884 return clean_if_nmethod_is_unloaded(ic, ic->ic_destination(), is_alive, from); 1885 } 1886 1887 static bool clean_if_nmethod_is_unloaded(CompiledStaticCall *csc, BoolObjectClosure *is_alive, nmethod* from) { 1888 return clean_if_nmethod_is_unloaded(csc, csc->destination(), is_alive, from); 1889 } 1890 1891 bool nmethod::unload_if_dead_at(RelocIterator* iter_at_oop, BoolObjectClosure *is_alive, bool unloading_occurred) { 1892 assert(iter_at_oop->type() == relocInfo::oop_type, "Wrong relocation type"); 1893 1894 oop_Relocation* r = iter_at_oop->oop_reloc(); 1895 // Traverse those oops directly embedded in the code. 1896 // Other oops (oop_index>0) are seen as part of scopes_oops. 1897 assert(1 == (r->oop_is_immediate()) + 1898 (r->oop_addr() >= oops_begin() && r->oop_addr() < oops_end()), 1899 "oop must be found in exactly one place"); 1900 if (r->oop_is_immediate() && r->oop_value() != NULL) { 1901 // Unload this nmethod if the oop is dead. 1902 if (can_unload(is_alive, r->oop_addr(), unloading_occurred)) { 1903 return true;; 1904 } 1905 } 1906 1907 return false; 1908 } 1909 1910 1911 bool nmethod::do_unloading_parallel(BoolObjectClosure* is_alive, bool unloading_occurred) { 1912 ResourceMark rm; 1913 1914 // Make sure the oop's ready to receive visitors 1915 assert(!is_zombie() && !is_unloaded(), 1916 "should not call follow on zombie or unloaded nmethod"); 1917 1918 // If the method is not entrant then a JMP is plastered over the 1919 // first few bytes. If an oop in the old code was there, that oop 1920 // should not get GC'd. Skip the first few bytes of oops on 1921 // not-entrant methods. 1922 address low_boundary = verified_entry_point(); 1923 if (is_not_entrant()) { 1924 low_boundary += NativeJump::instruction_size; 1925 // %%% Note: On SPARC we patch only a 4-byte trap, not a full NativeJump. 1926 // (See comment above.) 1927 } 1928 1929 // The RedefineClasses() API can cause the class unloading invariant 1930 // to no longer be true. See jvmtiExport.hpp for details. 1931 // Also, leave a debugging breadcrumb in local flag. 1932 if (JvmtiExport::has_redefined_a_class()) { 1933 // This set of the unloading_occurred flag is done before the 1934 // call to post_compiled_method_unload() so that the unloading 1935 // of this nmethod is reported. 1936 unloading_occurred = true; 1937 } 1938 1939 // Exception cache 1940 clean_exception_cache(is_alive); 1941 1942 bool is_unloaded = false; 1943 bool postponed = false; 1944 1945 RelocIterator iter(this, low_boundary); 1946 while(iter.next()) { 1947 1948 switch (iter.type()) { 1949 1950 case relocInfo::virtual_call_type: 1951 if (unloading_occurred) { 1952 // If class unloading occurred we first iterate over all inline caches and 1953 // clear ICs where the cached oop is referring to an unloaded klass or method. 1954 clean_ic_if_metadata_is_dead(CompiledIC_at(&iter), is_alive); 1955 } 1956 1957 postponed |= clean_if_nmethod_is_unloaded(CompiledIC_at(&iter), is_alive, this); 1958 break; 1959 1960 case relocInfo::opt_virtual_call_type: 1961 postponed |= clean_if_nmethod_is_unloaded(CompiledIC_at(&iter), is_alive, this); 1962 break; 1963 1964 case relocInfo::static_call_type: 1965 postponed |= clean_if_nmethod_is_unloaded(compiledStaticCall_at(iter.reloc()), is_alive, this); 1966 break; 1967 1968 case relocInfo::oop_type: 1969 if (!is_unloaded) { 1970 is_unloaded = unload_if_dead_at(&iter, is_alive, unloading_occurred); 1971 } 1972 break; 1973 1974 case relocInfo::metadata_type: 1975 break; // nothing to do. 1976 } 1977 } 1978 1979 if (is_unloaded) { 1980 return postponed; 1981 } 1982 1983 // Scopes 1984 for (oop* p = oops_begin(); p < oops_end(); p++) { 1985 if (*p == Universe::non_oop_word()) continue; // skip non-oops 1986 if (can_unload(is_alive, p, unloading_occurred)) { 1987 is_unloaded = true; 1988 break; 1989 } 1990 } 1991 1992 if (is_unloaded) { 1993 return postponed; 1994 } 1995 1996 #if INCLUDE_JVMCI 1997 // Follow JVMCI method 1998 BarrierSet* bs = Universe::heap()->barrier_set(); 1999 if (_jvmci_installed_code != NULL) { 2000 if (_jvmci_installed_code->is_a(HotSpotNmethod::klass()) && HotSpotNmethod::isDefault(_jvmci_installed_code)) { 2001 if (!is_alive->do_object_b(_jvmci_installed_code)) { 2002 clear_jvmci_installed_code(); 2003 } 2004 } else { 2005 if (can_unload(is_alive, (oop*)&_jvmci_installed_code, unloading_occurred)) { 2006 is_unloaded = true; 2007 } 2008 } 2009 } 2010 2011 if (_speculation_log != NULL) { 2012 if (!is_alive->do_object_b(_speculation_log)) { 2013 bs->write_ref_nmethod_pre(&_speculation_log, this); 2014 _speculation_log = NULL; 2015 bs->write_ref_nmethod_post(&_speculation_log, this); 2016 } 2017 } 2018 #endif 2019 2020 // Ensure that all metadata is still alive 2021 verify_metadata_loaders(low_boundary, is_alive); 2022 2023 return postponed; 2024 } 2025 2026 void nmethod::do_unloading_parallel_postponed(BoolObjectClosure* is_alive, bool unloading_occurred) { 2027 ResourceMark rm; 2028 2029 // Make sure the oop's ready to receive visitors 2030 assert(!is_zombie(), 2031 "should not call follow on zombie nmethod"); 2032 2033 // If the method is not entrant then a JMP is plastered over the 2034 // first few bytes. If an oop in the old code was there, that oop 2035 // should not get GC'd. Skip the first few bytes of oops on 2036 // not-entrant methods. 2037 address low_boundary = verified_entry_point(); 2038 if (is_not_entrant()) { 2039 low_boundary += NativeJump::instruction_size; 2040 // %%% Note: On SPARC we patch only a 4-byte trap, not a full NativeJump. 2041 // (See comment above.) 2042 } 2043 2044 RelocIterator iter(this, low_boundary); 2045 while(iter.next()) { 2046 2047 switch (iter.type()) { 2048 2049 case relocInfo::virtual_call_type: 2050 clean_if_nmethod_is_unloaded(CompiledIC_at(&iter), is_alive, this); 2051 break; 2052 2053 case relocInfo::opt_virtual_call_type: 2054 clean_if_nmethod_is_unloaded(CompiledIC_at(&iter), is_alive, this); 2055 break; 2056 2057 case relocInfo::static_call_type: 2058 clean_if_nmethod_is_unloaded(compiledStaticCall_at(iter.reloc()), is_alive, this); 2059 break; 2060 } 2061 } 2062 } 2063 2064 #ifdef ASSERT 2065 2066 class CheckClass : AllStatic { 2067 static BoolObjectClosure* _is_alive; 2068 2069 // Check class_loader is alive for this bit of metadata. 2070 static void check_class(Metadata* md) { 2071 Klass* klass = NULL; 2072 if (md->is_klass()) { 2073 klass = ((Klass*)md); 2074 } else if (md->is_method()) { 2075 klass = ((Method*)md)->method_holder(); 2076 } else if (md->is_methodData()) { 2077 klass = ((MethodData*)md)->method()->method_holder(); 2078 } else { 2079 md->print(); 2080 ShouldNotReachHere(); 2081 } 2082 assert(klass->is_loader_alive(_is_alive), "must be alive"); 2083 } 2084 public: 2085 static void do_check_class(BoolObjectClosure* is_alive, nmethod* nm) { 2086 assert(SafepointSynchronize::is_at_safepoint(), "this is only ok at safepoint"); 2087 _is_alive = is_alive; 2088 nm->metadata_do(check_class); 2089 } 2090 }; 2091 2092 // This is called during a safepoint so can use static data 2093 BoolObjectClosure* CheckClass::_is_alive = NULL; 2094 #endif // ASSERT 2095 2096 2097 // Processing of oop references should have been sufficient to keep 2098 // all strong references alive. Any weak references should have been 2099 // cleared as well. Visit all the metadata and ensure that it's 2100 // really alive. 2101 void nmethod::verify_metadata_loaders(address low_boundary, BoolObjectClosure* is_alive) { 2102 #ifdef ASSERT 2103 RelocIterator iter(this, low_boundary); 2104 while (iter.next()) { 2105 // static_stub_Relocations may have dangling references to 2106 // Method*s so trim them out here. Otherwise it looks like 2107 // compiled code is maintaining a link to dead metadata. 2108 address static_call_addr = NULL; 2109 if (iter.type() == relocInfo::opt_virtual_call_type) { 2110 CompiledIC* cic = CompiledIC_at(&iter); 2111 if (!cic->is_call_to_interpreted()) { 2112 static_call_addr = iter.addr(); 2113 } 2114 } else if (iter.type() == relocInfo::static_call_type) { 2115 CompiledStaticCall* csc = compiledStaticCall_at(iter.reloc()); 2116 if (!csc->is_call_to_interpreted()) { 2117 static_call_addr = iter.addr(); 2118 } 2119 } 2120 if (static_call_addr != NULL) { 2121 RelocIterator sciter(this, low_boundary); 2122 while (sciter.next()) { 2123 if (sciter.type() == relocInfo::static_stub_type && 2124 sciter.static_stub_reloc()->static_call() == static_call_addr) { 2125 sciter.static_stub_reloc()->clear_inline_cache(); 2126 } 2127 } 2128 } 2129 } 2130 // Check that the metadata embedded in the nmethod is alive 2131 CheckClass::do_check_class(is_alive, this); 2132 #endif 2133 } 2134 2135 2136 // Iterate over metadata calling this function. Used by RedefineClasses 2137 void nmethod::metadata_do(void f(Metadata*)) { 2138 address low_boundary = verified_entry_point(); 2139 if (is_not_entrant()) { 2140 low_boundary += NativeJump::instruction_size; 2141 // %%% Note: On SPARC we patch only a 4-byte trap, not a full NativeJump. 2142 // (See comment above.) 2143 } 2144 { 2145 // Visit all immediate references that are embedded in the instruction stream. 2146 RelocIterator iter(this, low_boundary); 2147 while (iter.next()) { 2148 if (iter.type() == relocInfo::metadata_type ) { 2149 metadata_Relocation* r = iter.metadata_reloc(); 2150 // In this metadata, we must only follow those metadatas directly embedded in 2151 // the code. Other metadatas (oop_index>0) are seen as part of 2152 // the metadata section below. 2153 assert(1 == (r->metadata_is_immediate()) + 2154 (r->metadata_addr() >= metadata_begin() && r->metadata_addr() < metadata_end()), 2155 "metadata must be found in exactly one place"); 2156 if (r->metadata_is_immediate() && r->metadata_value() != NULL) { 2157 Metadata* md = r->metadata_value(); 2158 if (md != _method) f(md); 2159 } 2160 } else if (iter.type() == relocInfo::virtual_call_type) { 2161 // Check compiledIC holders associated with this nmethod 2162 CompiledIC *ic = CompiledIC_at(&iter); 2163 if (ic->is_icholder_call()) { 2164 CompiledICHolder* cichk = ic->cached_icholder(); 2165 f(cichk->holder_method()); 2166 f(cichk->holder_klass()); 2167 } else { 2168 Metadata* ic_oop = ic->cached_metadata(); 2169 if (ic_oop != NULL) { 2170 f(ic_oop); 2171 } 2172 } 2173 } 2174 } 2175 } 2176 2177 // Visit the metadata section 2178 for (Metadata** p = metadata_begin(); p < metadata_end(); p++) { 2179 if (*p == Universe::non_oop_word() || *p == NULL) continue; // skip non-oops 2180 Metadata* md = *p; 2181 f(md); 2182 } 2183 2184 // Visit metadata not embedded in the other places. 2185 if (_method != NULL) f(_method); 2186 } 2187 2188 void nmethod::oops_do(OopClosure* f, bool allow_zombie) { 2189 // make sure the oops ready to receive visitors 2190 assert(allow_zombie || !is_zombie(), "should not call follow on zombie nmethod"); 2191 assert(!is_unloaded(), "should not call follow on unloaded nmethod"); 2192 2193 // If the method is not entrant or zombie then a JMP is plastered over the 2194 // first few bytes. If an oop in the old code was there, that oop 2195 // should not get GC'd. Skip the first few bytes of oops on 2196 // not-entrant methods. 2197 address low_boundary = verified_entry_point(); 2198 if (is_not_entrant()) { 2199 low_boundary += NativeJump::instruction_size; 2200 // %%% Note: On SPARC we patch only a 4-byte trap, not a full NativeJump. 2201 // (See comment above.) 2202 } 2203 2204 #if INCLUDE_JVMCI 2205 if (_jvmci_installed_code != NULL) { 2206 f->do_oop((oop*) &_jvmci_installed_code); 2207 } 2208 if (_speculation_log != NULL) { 2209 f->do_oop((oop*) &_speculation_log); 2210 } 2211 #endif 2212 2213 RelocIterator iter(this, low_boundary); 2214 2215 while (iter.next()) { 2216 if (iter.type() == relocInfo::oop_type ) { 2217 oop_Relocation* r = iter.oop_reloc(); 2218 // In this loop, we must only follow those oops directly embedded in 2219 // the code. Other oops (oop_index>0) are seen as part of scopes_oops. 2220 assert(1 == (r->oop_is_immediate()) + 2221 (r->oop_addr() >= oops_begin() && r->oop_addr() < oops_end()), 2222 "oop must be found in exactly one place"); 2223 if (r->oop_is_immediate() && r->oop_value() != NULL) { 2224 f->do_oop(r->oop_addr()); 2225 } 2226 } 2227 } 2228 2229 // Scopes 2230 // This includes oop constants not inlined in the code stream. 2231 for (oop* p = oops_begin(); p < oops_end(); p++) { 2232 if (*p == Universe::non_oop_word()) continue; // skip non-oops 2233 f->do_oop(p); 2234 } 2235 } 2236 2237 #define NMETHOD_SENTINEL ((nmethod*)badAddress) 2238 2239 nmethod* volatile nmethod::_oops_do_mark_nmethods; 2240 2241 // An nmethod is "marked" if its _mark_link is set non-null. 2242 // Even if it is the end of the linked list, it will have a non-null link value, 2243 // as long as it is on the list. 2244 // This code must be MP safe, because it is used from parallel GC passes. 2245 bool nmethod::test_set_oops_do_mark() { 2246 assert(nmethod::oops_do_marking_is_active(), "oops_do_marking_prologue must be called"); 2247 nmethod* observed_mark_link = _oops_do_mark_link; 2248 if (observed_mark_link == NULL) { 2249 // Claim this nmethod for this thread to mark. 2250 observed_mark_link = (nmethod*) 2251 Atomic::cmpxchg_ptr(NMETHOD_SENTINEL, &_oops_do_mark_link, NULL); 2252 if (observed_mark_link == NULL) { 2253 2254 // Atomically append this nmethod (now claimed) to the head of the list: 2255 nmethod* observed_mark_nmethods = _oops_do_mark_nmethods; 2256 for (;;) { 2257 nmethod* required_mark_nmethods = observed_mark_nmethods; 2258 _oops_do_mark_link = required_mark_nmethods; 2259 observed_mark_nmethods = (nmethod*) 2260 Atomic::cmpxchg_ptr(this, &_oops_do_mark_nmethods, required_mark_nmethods); 2261 if (observed_mark_nmethods == required_mark_nmethods) 2262 break; 2263 } 2264 // Mark was clear when we first saw this guy. 2265 if (TraceScavenge) { print_on(tty, "oops_do, mark"); } 2266 return false; 2267 } 2268 } 2269 // On fall through, another racing thread marked this nmethod before we did. 2270 return true; 2271 } 2272 2273 void nmethod::oops_do_marking_prologue() { 2274 if (TraceScavenge) { tty->print_cr("[oops_do_marking_prologue"); } 2275 assert(_oops_do_mark_nmethods == NULL, "must not call oops_do_marking_prologue twice in a row"); 2276 // We use cmpxchg_ptr instead of regular assignment here because the user 2277 // may fork a bunch of threads, and we need them all to see the same state. 2278 void* observed = Atomic::cmpxchg_ptr(NMETHOD_SENTINEL, &_oops_do_mark_nmethods, NULL); 2279 guarantee(observed == NULL, "no races in this sequential code"); 2280 } 2281 2282 void nmethod::oops_do_marking_epilogue() { 2283 assert(_oops_do_mark_nmethods != NULL, "must not call oops_do_marking_epilogue twice in a row"); 2284 nmethod* cur = _oops_do_mark_nmethods; 2285 while (cur != NMETHOD_SENTINEL) { 2286 assert(cur != NULL, "not NULL-terminated"); 2287 nmethod* next = cur->_oops_do_mark_link; 2288 cur->_oops_do_mark_link = NULL; 2289 DEBUG_ONLY(cur->verify_oop_relocations()); 2290 NOT_PRODUCT(if (TraceScavenge) cur->print_on(tty, "oops_do, unmark")); 2291 cur = next; 2292 } 2293 void* required = _oops_do_mark_nmethods; 2294 void* observed = Atomic::cmpxchg_ptr(NULL, &_oops_do_mark_nmethods, required); 2295 guarantee(observed == required, "no races in this sequential code"); 2296 if (TraceScavenge) { tty->print_cr("oops_do_marking_epilogue]"); } 2297 } 2298 2299 class DetectScavengeRoot: public OopClosure { 2300 bool _detected_scavenge_root; 2301 public: 2302 DetectScavengeRoot() : _detected_scavenge_root(false) 2303 { NOT_PRODUCT(_print_nm = NULL); } 2304 bool detected_scavenge_root() { return _detected_scavenge_root; } 2305 virtual void do_oop(oop* p) { 2306 if ((*p) != NULL && (*p)->is_scavengable()) { 2307 NOT_PRODUCT(maybe_print(p)); 2308 _detected_scavenge_root = true; 2309 } 2310 } 2311 virtual void do_oop(narrowOop* p) { ShouldNotReachHere(); } 2312 2313 #ifndef PRODUCT 2314 nmethod* _print_nm; 2315 void maybe_print(oop* p) { 2316 if (_print_nm == NULL) return; 2317 if (!_detected_scavenge_root) _print_nm->print_on(tty, "new scavenge root"); 2318 tty->print_cr("" PTR_FORMAT "[offset=%d] detected scavengable oop " PTR_FORMAT " (found at " PTR_FORMAT ")", 2319 p2i(_print_nm), (int)((intptr_t)p - (intptr_t)_print_nm), 2320 p2i(*p), p2i(p)); 2321 (*p)->print(); 2322 } 2323 #endif //PRODUCT 2324 }; 2325 2326 bool nmethod::detect_scavenge_root_oops() { 2327 DetectScavengeRoot detect_scavenge_root; 2328 NOT_PRODUCT(if (TraceScavenge) detect_scavenge_root._print_nm = this); 2329 oops_do(&detect_scavenge_root); 2330 return detect_scavenge_root.detected_scavenge_root(); 2331 } 2332 2333 // Method that knows how to preserve outgoing arguments at call. This method must be 2334 // called with a frame corresponding to a Java invoke 2335 void nmethod::preserve_callee_argument_oops(frame fr, const RegisterMap *reg_map, OopClosure* f) { 2336 #ifndef SHARK 2337 if (method() != NULL && !method()->is_native()) { 2338 address pc = fr.pc(); 2339 SimpleScopeDesc ssd(this, pc); 2340 Bytecode_invoke call(ssd.method(), ssd.bci()); 2341 bool has_receiver = call.has_receiver(); 2342 bool has_appendix = call.has_appendix(); 2343 Symbol* signature = call.signature(); 2344 2345 // The method attached by JIT-compilers should be used, if present. 2346 // Bytecode can be inaccurate in such case. 2347 Method* callee = attached_method_before_pc(pc); 2348 if (callee != NULL) { 2349 has_receiver = !(callee->access_flags().is_static()); 2350 has_appendix = false; 2351 signature = callee->signature(); 2352 } 2353 2354 fr.oops_compiled_arguments_do(signature, has_receiver, has_appendix, reg_map, f); 2355 } 2356 #endif // !SHARK 2357 } 2358 2359 inline bool includes(void* p, void* from, void* to) { 2360 return from <= p && p < to; 2361 } 2362 2363 2364 void nmethod::copy_scopes_pcs(PcDesc* pcs, int count) { 2365 assert(count >= 2, "must be sentinel values, at least"); 2366 2367 #ifdef ASSERT 2368 // must be sorted and unique; we do a binary search in find_pc_desc() 2369 int prev_offset = pcs[0].pc_offset(); 2370 assert(prev_offset == PcDesc::lower_offset_limit, 2371 "must start with a sentinel"); 2372 for (int i = 1; i < count; i++) { 2373 int this_offset = pcs[i].pc_offset(); 2374 assert(this_offset > prev_offset, "offsets must be sorted"); 2375 prev_offset = this_offset; 2376 } 2377 assert(prev_offset == PcDesc::upper_offset_limit, 2378 "must end with a sentinel"); 2379 #endif //ASSERT 2380 2381 // Search for MethodHandle invokes and tag the nmethod. 2382 for (int i = 0; i < count; i++) { 2383 if (pcs[i].is_method_handle_invoke()) { 2384 set_has_method_handle_invokes(true); 2385 break; 2386 } 2387 } 2388 assert(has_method_handle_invokes() == (_deoptimize_mh_offset != -1), "must have deopt mh handler"); 2389 2390 int size = count * sizeof(PcDesc); 2391 assert(scopes_pcs_size() >= size, "oob"); 2392 memcpy(scopes_pcs_begin(), pcs, size); 2393 2394 // Adjust the final sentinel downward. 2395 PcDesc* last_pc = &scopes_pcs_begin()[count-1]; 2396 assert(last_pc->pc_offset() == PcDesc::upper_offset_limit, "sanity"); 2397 last_pc->set_pc_offset(content_size() + 1); 2398 for (; last_pc + 1 < scopes_pcs_end(); last_pc += 1) { 2399 // Fill any rounding gaps with copies of the last record. 2400 last_pc[1] = last_pc[0]; 2401 } 2402 // The following assert could fail if sizeof(PcDesc) is not 2403 // an integral multiple of oopSize (the rounding term). 2404 // If it fails, change the logic to always allocate a multiple 2405 // of sizeof(PcDesc), and fill unused words with copies of *last_pc. 2406 assert(last_pc + 1 == scopes_pcs_end(), "must match exactly"); 2407 } 2408 2409 void nmethod::copy_scopes_data(u_char* buffer, int size) { 2410 assert(scopes_data_size() >= size, "oob"); 2411 memcpy(scopes_data_begin(), buffer, size); 2412 } 2413 2414 // When using JVMCI the address might be off by the size of a call instruction. 2415 bool nmethod::is_deopt_entry(address pc) { 2416 return pc == deopt_handler_begin() 2417 #if INCLUDE_JVMCI 2418 || pc == (deopt_handler_begin() + NativeCall::instruction_size) 2419 #endif 2420 ; 2421 } 2422 2423 #ifdef ASSERT 2424 static PcDesc* linear_search(nmethod* nm, int pc_offset, bool approximate) { 2425 PcDesc* lower = nm->scopes_pcs_begin(); 2426 PcDesc* upper = nm->scopes_pcs_end(); 2427 lower += 1; // exclude initial sentinel 2428 PcDesc* res = NULL; 2429 for (PcDesc* p = lower; p < upper; p++) { 2430 NOT_PRODUCT(--pc_nmethod_stats.pc_desc_tests); // don't count this call to match_desc 2431 if (match_desc(p, pc_offset, approximate)) { 2432 if (res == NULL) 2433 res = p; 2434 else 2435 res = (PcDesc*) badAddress; 2436 } 2437 } 2438 return res; 2439 } 2440 #endif 2441 2442 2443 // Finds a PcDesc with real-pc equal to "pc" 2444 PcDesc* nmethod::find_pc_desc_internal(address pc, bool approximate) { 2445 address base_address = code_begin(); 2446 if ((pc < base_address) || 2447 (pc - base_address) >= (ptrdiff_t) PcDesc::upper_offset_limit) { 2448 return NULL; // PC is wildly out of range 2449 } 2450 int pc_offset = (int) (pc - base_address); 2451 2452 // Check the PcDesc cache if it contains the desired PcDesc 2453 // (This as an almost 100% hit rate.) 2454 PcDesc* res = _pc_desc_cache.find_pc_desc(pc_offset, approximate); 2455 if (res != NULL) { 2456 assert(res == linear_search(this, pc_offset, approximate), "cache ok"); 2457 return res; 2458 } 2459 2460 // Fallback algorithm: quasi-linear search for the PcDesc 2461 // Find the last pc_offset less than the given offset. 2462 // The successor must be the required match, if there is a match at all. 2463 // (Use a fixed radix to avoid expensive affine pointer arithmetic.) 2464 PcDesc* lower = scopes_pcs_begin(); 2465 PcDesc* upper = scopes_pcs_end(); 2466 upper -= 1; // exclude final sentinel 2467 if (lower >= upper) return NULL; // native method; no PcDescs at all 2468 2469 #define assert_LU_OK \ 2470 /* invariant on lower..upper during the following search: */ \ 2471 assert(lower->pc_offset() < pc_offset, "sanity"); \ 2472 assert(upper->pc_offset() >= pc_offset, "sanity") 2473 assert_LU_OK; 2474 2475 // Use the last successful return as a split point. 2476 PcDesc* mid = _pc_desc_cache.last_pc_desc(); 2477 NOT_PRODUCT(++pc_nmethod_stats.pc_desc_searches); 2478 if (mid->pc_offset() < pc_offset) { 2479 lower = mid; 2480 } else { 2481 upper = mid; 2482 } 2483 2484 // Take giant steps at first (4096, then 256, then 16, then 1) 2485 const int LOG2_RADIX = 4 /*smaller steps in debug mode:*/ debug_only(-1); 2486 const int RADIX = (1 << LOG2_RADIX); 2487 for (int step = (1 << (LOG2_RADIX*3)); step > 1; step >>= LOG2_RADIX) { 2488 while ((mid = lower + step) < upper) { 2489 assert_LU_OK; 2490 NOT_PRODUCT(++pc_nmethod_stats.pc_desc_searches); 2491 if (mid->pc_offset() < pc_offset) { 2492 lower = mid; 2493 } else { 2494 upper = mid; 2495 break; 2496 } 2497 } 2498 assert_LU_OK; 2499 } 2500 2501 // Sneak up on the value with a linear search of length ~16. 2502 while (true) { 2503 assert_LU_OK; 2504 mid = lower + 1; 2505 NOT_PRODUCT(++pc_nmethod_stats.pc_desc_searches); 2506 if (mid->pc_offset() < pc_offset) { 2507 lower = mid; 2508 } else { 2509 upper = mid; 2510 break; 2511 } 2512 } 2513 #undef assert_LU_OK 2514 2515 if (match_desc(upper, pc_offset, approximate)) { 2516 assert(upper == linear_search(this, pc_offset, approximate), "search ok"); 2517 _pc_desc_cache.add_pc_desc(upper); 2518 return upper; 2519 } else { 2520 assert(NULL == linear_search(this, pc_offset, approximate), "search ok"); 2521 return NULL; 2522 } 2523 } 2524 2525 2526 void nmethod::check_all_dependencies(DepChange& changes) { 2527 // Checked dependencies are allocated into this ResourceMark 2528 ResourceMark rm; 2529 2530 // Turn off dependency tracing while actually testing dependencies. 2531 NOT_PRODUCT( FlagSetting fs(TraceDependencies, false) ); 2532 2533 typedef ResourceHashtable<DependencySignature, int, &DependencySignature::hash, 2534 &DependencySignature::equals, 11027> DepTable; 2535 2536 DepTable* table = new DepTable(); 2537 2538 // Iterate over live nmethods and check dependencies of all nmethods that are not 2539 // marked for deoptimization. A particular dependency is only checked once. 2540 NMethodIterator iter; 2541 while(iter.next()) { 2542 nmethod* nm = iter.method(); 2543 // Only notify for live nmethods 2544 if (nm->is_alive() && !nm->is_marked_for_deoptimization()) { 2545 for (Dependencies::DepStream deps(nm); deps.next(); ) { 2546 // Construct abstraction of a dependency. 2547 DependencySignature* current_sig = new DependencySignature(deps); 2548 2549 // Determine if dependency is already checked. table->put(...) returns 2550 // 'true' if the dependency is added (i.e., was not in the hashtable). 2551 if (table->put(*current_sig, 1)) { 2552 if (deps.check_dependency() != NULL) { 2553 // Dependency checking failed. Print out information about the failed 2554 // dependency and finally fail with an assert. We can fail here, since 2555 // dependency checking is never done in a product build. 2556 tty->print_cr("Failed dependency:"); 2557 changes.print(); 2558 nm->print(); 2559 nm->print_dependencies(); 2560 assert(false, "Should have been marked for deoptimization"); 2561 } 2562 } 2563 } 2564 } 2565 } 2566 } 2567 2568 bool nmethod::check_dependency_on(DepChange& changes) { 2569 // What has happened: 2570 // 1) a new class dependee has been added 2571 // 2) dependee and all its super classes have been marked 2572 bool found_check = false; // set true if we are upset 2573 for (Dependencies::DepStream deps(this); deps.next(); ) { 2574 // Evaluate only relevant dependencies. 2575 if (deps.spot_check_dependency_at(changes) != NULL) { 2576 found_check = true; 2577 NOT_DEBUG(break); 2578 } 2579 } 2580 return found_check; 2581 } 2582 2583 bool nmethod::is_evol_dependent_on(Klass* dependee) { 2584 InstanceKlass *dependee_ik = InstanceKlass::cast(dependee); 2585 Array<Method*>* dependee_methods = dependee_ik->methods(); 2586 for (Dependencies::DepStream deps(this); deps.next(); ) { 2587 if (deps.type() == Dependencies::evol_method) { 2588 Method* method = deps.method_argument(0); 2589 for (int j = 0; j < dependee_methods->length(); j++) { 2590 if (dependee_methods->at(j) == method) { 2591 // RC_TRACE macro has an embedded ResourceMark 2592 RC_TRACE(0x01000000, 2593 ("Found evol dependency of nmethod %s.%s(%s) compile_id=%d on method %s.%s(%s)", 2594 _method->method_holder()->external_name(), 2595 _method->name()->as_C_string(), 2596 _method->signature()->as_C_string(), compile_id(), 2597 method->method_holder()->external_name(), 2598 method->name()->as_C_string(), 2599 method->signature()->as_C_string())); 2600 if (TraceDependencies || LogCompilation) 2601 deps.log_dependency(dependee); 2602 return true; 2603 } 2604 } 2605 } 2606 } 2607 return false; 2608 } 2609 2610 // Called from mark_for_deoptimization, when dependee is invalidated. 2611 bool nmethod::is_dependent_on_method(Method* dependee) { 2612 for (Dependencies::DepStream deps(this); deps.next(); ) { 2613 if (deps.type() != Dependencies::evol_method) 2614 continue; 2615 Method* method = deps.method_argument(0); 2616 if (method == dependee) return true; 2617 } 2618 return false; 2619 } 2620 2621 2622 bool nmethod::is_patchable_at(address instr_addr) { 2623 assert(insts_contains(instr_addr), "wrong nmethod used"); 2624 if (is_zombie()) { 2625 // a zombie may never be patched 2626 return false; 2627 } 2628 return true; 2629 } 2630 2631 2632 address nmethod::continuation_for_implicit_exception(address pc) { 2633 // Exception happened outside inline-cache check code => we are inside 2634 // an active nmethod => use cpc to determine a return address 2635 int exception_offset = pc - code_begin(); 2636 int cont_offset = ImplicitExceptionTable(this).at( exception_offset ); 2637 #ifdef ASSERT 2638 if (cont_offset == 0) { 2639 Thread* thread = Thread::current(); 2640 ResetNoHandleMark rnm; // Might be called from LEAF/QUICK ENTRY 2641 HandleMark hm(thread); 2642 ResourceMark rm(thread); 2643 CodeBlob* cb = CodeCache::find_blob(pc); 2644 assert(cb != NULL && cb == this, ""); 2645 ttyLocker ttyl; 2646 tty->print_cr("implicit exception happened at " INTPTR_FORMAT, p2i(pc)); 2647 print(); 2648 method()->print_codes(); 2649 print_code(); 2650 print_pcs(); 2651 } 2652 #endif 2653 if (cont_offset == 0) { 2654 // Let the normal error handling report the exception 2655 return NULL; 2656 } 2657 return code_begin() + cont_offset; 2658 } 2659 2660 2661 2662 void nmethod_init() { 2663 // make sure you didn't forget to adjust the filler fields 2664 assert(sizeof(nmethod) % oopSize == 0, "nmethod size must be multiple of a word"); 2665 } 2666 2667 2668 //------------------------------------------------------------------------------------------- 2669 2670 2671 // QQQ might we make this work from a frame?? 2672 nmethodLocker::nmethodLocker(address pc) { 2673 CodeBlob* cb = CodeCache::find_blob(pc); 2674 guarantee(cb != NULL && cb->is_nmethod(), "bad pc for a nmethod found"); 2675 _nm = (nmethod*)cb; 2676 lock_nmethod(_nm); 2677 } 2678 2679 // Only JvmtiDeferredEvent::compiled_method_unload_event() 2680 // should pass zombie_ok == true. 2681 void nmethodLocker::lock_nmethod(nmethod* nm, bool zombie_ok) { 2682 if (nm == NULL) return; 2683 Atomic::inc(&nm->_lock_count); 2684 assert(zombie_ok || !nm->is_zombie(), "cannot lock a zombie method"); 2685 } 2686 2687 void nmethodLocker::unlock_nmethod(nmethod* nm) { 2688 if (nm == NULL) return; 2689 Atomic::dec(&nm->_lock_count); 2690 assert(nm->_lock_count >= 0, "unmatched nmethod lock/unlock"); 2691 } 2692 2693 // ----------------------------------------------------------------------------- 2694 // nmethod::get_deopt_original_pc 2695 // 2696 // Return the original PC for the given PC if: 2697 // (a) the given PC belongs to a nmethod and 2698 // (b) it is a deopt PC 2699 address nmethod::get_deopt_original_pc(const frame* fr) { 2700 if (fr->cb() == NULL) return NULL; 2701 2702 nmethod* nm = fr->cb()->as_nmethod_or_null(); 2703 if (nm != NULL && nm->is_deopt_pc(fr->pc())) 2704 return nm->get_original_pc(fr); 2705 2706 return NULL; 2707 } 2708 2709 2710 // ----------------------------------------------------------------------------- 2711 // MethodHandle 2712 2713 bool nmethod::is_method_handle_return(address return_pc) { 2714 if (!has_method_handle_invokes()) return false; 2715 PcDesc* pd = pc_desc_at(return_pc); 2716 if (pd == NULL) 2717 return false; 2718 return pd->is_method_handle_invoke(); 2719 } 2720 2721 2722 // ----------------------------------------------------------------------------- 2723 // Verification 2724 2725 class VerifyOopsClosure: public OopClosure { 2726 nmethod* _nm; 2727 bool _ok; 2728 public: 2729 VerifyOopsClosure(nmethod* nm) : _nm(nm), _ok(true) { } 2730 bool ok() { return _ok; } 2731 virtual void do_oop(oop* p) { 2732 if ((*p) == NULL || (*p)->is_oop()) return; 2733 if (_ok) { 2734 _nm->print_nmethod(true); 2735 _ok = false; 2736 } 2737 tty->print_cr("*** non-oop " PTR_FORMAT " found at " PTR_FORMAT " (offset %d)", 2738 p2i(*p), p2i(p), (int)((intptr_t)p - (intptr_t)_nm)); 2739 } 2740 virtual void do_oop(narrowOop* p) { ShouldNotReachHere(); } 2741 }; 2742 2743 void nmethod::verify() { 2744 2745 // Hmm. OSR methods can be deopted but not marked as zombie or not_entrant 2746 // seems odd. 2747 2748 if (is_zombie() || is_not_entrant() || is_unloaded()) 2749 return; 2750 2751 // Make sure all the entry points are correctly aligned for patching. 2752 NativeJump::check_verified_entry_alignment(entry_point(), verified_entry_point()); 2753 2754 // assert(method()->is_oop(), "must be valid"); 2755 2756 ResourceMark rm; 2757 2758 if (!CodeCache::contains(this)) { 2759 fatal("nmethod at " INTPTR_FORMAT " not in zone", p2i(this)); 2760 } 2761 2762 if(is_native_method() ) 2763 return; 2764 2765 nmethod* nm = CodeCache::find_nmethod(verified_entry_point()); 2766 if (nm != this) { 2767 fatal("findNMethod did not find this nmethod (" INTPTR_FORMAT ")", p2i(this)); 2768 } 2769 2770 for (PcDesc* p = scopes_pcs_begin(); p < scopes_pcs_end(); p++) { 2771 if (! p->verify(this)) { 2772 tty->print_cr("\t\tin nmethod at " INTPTR_FORMAT " (pcs)", p2i(this)); 2773 } 2774 } 2775 2776 VerifyOopsClosure voc(this); 2777 oops_do(&voc); 2778 assert(voc.ok(), "embedded oops must be OK"); 2779 verify_scavenge_root_oops(); 2780 2781 verify_scopes(); 2782 } 2783 2784 2785 void nmethod::verify_interrupt_point(address call_site) { 2786 // Verify IC only when nmethod installation is finished. 2787 bool is_installed = (method()->code() == this) // nmethod is in state 'in_use' and installed 2788 || !this->is_in_use(); // nmethod is installed, but not in 'in_use' state 2789 if (is_installed) { 2790 Thread *cur = Thread::current(); 2791 if (CompiledIC_lock->owner() == cur || 2792 ((cur->is_VM_thread() || cur->is_ConcurrentGC_thread()) && 2793 SafepointSynchronize::is_at_safepoint())) { 2794 CompiledIC_at(this, call_site); 2795 CHECK_UNHANDLED_OOPS_ONLY(Thread::current()->clear_unhandled_oops()); 2796 } else { 2797 MutexLocker ml_verify (CompiledIC_lock); 2798 CompiledIC_at(this, call_site); 2799 } 2800 } 2801 2802 PcDesc* pd = pc_desc_at(nativeCall_at(call_site)->return_address()); 2803 assert(pd != NULL, "PcDesc must exist"); 2804 for (ScopeDesc* sd = new ScopeDesc(this, pd->scope_decode_offset(), 2805 pd->obj_decode_offset(), pd->should_reexecute(), pd->rethrow_exception(), 2806 pd->return_oop()); 2807 !sd->is_top(); sd = sd->sender()) { 2808 sd->verify(); 2809 } 2810 } 2811 2812 void nmethod::verify_scopes() { 2813 if( !method() ) return; // Runtime stubs have no scope 2814 if (method()->is_native()) return; // Ignore stub methods. 2815 // iterate through all interrupt point 2816 // and verify the debug information is valid. 2817 RelocIterator iter((nmethod*)this); 2818 while (iter.next()) { 2819 address stub = NULL; 2820 switch (iter.type()) { 2821 case relocInfo::virtual_call_type: 2822 verify_interrupt_point(iter.addr()); 2823 break; 2824 case relocInfo::opt_virtual_call_type: 2825 stub = iter.opt_virtual_call_reloc()->static_stub(); 2826 verify_interrupt_point(iter.addr()); 2827 break; 2828 case relocInfo::static_call_type: 2829 stub = iter.static_call_reloc()->static_stub(); 2830 //verify_interrupt_point(iter.addr()); 2831 break; 2832 case relocInfo::runtime_call_type: 2833 address destination = iter.reloc()->value(); 2834 // Right now there is no way to find out which entries support 2835 // an interrupt point. It would be nice if we had this 2836 // information in a table. 2837 break; 2838 } 2839 assert(stub == NULL || stub_contains(stub), "static call stub outside stub section"); 2840 } 2841 } 2842 2843 2844 // ----------------------------------------------------------------------------- 2845 // Non-product code 2846 #ifndef PRODUCT 2847 2848 class DebugScavengeRoot: public OopClosure { 2849 nmethod* _nm; 2850 bool _ok; 2851 public: 2852 DebugScavengeRoot(nmethod* nm) : _nm(nm), _ok(true) { } 2853 bool ok() { return _ok; } 2854 virtual void do_oop(oop* p) { 2855 if ((*p) == NULL || !(*p)->is_scavengable()) return; 2856 if (_ok) { 2857 _nm->print_nmethod(true); 2858 _ok = false; 2859 } 2860 tty->print_cr("*** scavengable oop " PTR_FORMAT " found at " PTR_FORMAT " (offset %d)", 2861 p2i(*p), p2i(p), (int)((intptr_t)p - (intptr_t)_nm)); 2862 (*p)->print(); 2863 } 2864 virtual void do_oop(narrowOop* p) { ShouldNotReachHere(); } 2865 }; 2866 2867 void nmethod::verify_scavenge_root_oops() { 2868 if (UseG1GC) { 2869 return; 2870 } 2871 2872 if (!on_scavenge_root_list()) { 2873 // Actually look inside, to verify the claim that it's clean. 2874 DebugScavengeRoot debug_scavenge_root(this); 2875 oops_do(&debug_scavenge_root); 2876 if (!debug_scavenge_root.ok()) 2877 fatal("found an unadvertised bad scavengable oop in the code cache"); 2878 } 2879 assert(scavenge_root_not_marked(), ""); 2880 } 2881 2882 #endif // PRODUCT 2883 2884 // Printing operations 2885 2886 void nmethod::print() const { 2887 ResourceMark rm; 2888 ttyLocker ttyl; // keep the following output all in one block 2889 2890 tty->print("Compiled method "); 2891 2892 if (is_compiled_by_c1()) { 2893 tty->print("(c1) "); 2894 } else if (is_compiled_by_c2()) { 2895 tty->print("(c2) "); 2896 } else if (is_compiled_by_shark()) { 2897 tty->print("(shark) "); 2898 } else if (is_compiled_by_jvmci()) { 2899 tty->print("(JVMCI) "); 2900 } else { 2901 tty->print("(nm) "); 2902 } 2903 2904 print_on(tty, NULL); 2905 2906 if (WizardMode) { 2907 tty->print("((nmethod*) " INTPTR_FORMAT ") ", p2i(this)); 2908 tty->print(" for method " INTPTR_FORMAT , p2i(method())); 2909 tty->print(" { "); 2910 if (is_in_use()) tty->print("in_use "); 2911 if (is_not_entrant()) tty->print("not_entrant "); 2912 if (is_zombie()) tty->print("zombie "); 2913 if (is_unloaded()) tty->print("unloaded "); 2914 if (on_scavenge_root_list()) tty->print("scavenge_root "); 2915 tty->print_cr("}:"); 2916 } 2917 if (size () > 0) tty->print_cr(" total in heap [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d", 2918 p2i(this), 2919 p2i(this) + size(), 2920 size()); 2921 if (relocation_size () > 0) tty->print_cr(" relocation [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d", 2922 p2i(relocation_begin()), 2923 p2i(relocation_end()), 2924 relocation_size()); 2925 if (consts_size () > 0) tty->print_cr(" constants [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d", 2926 p2i(consts_begin()), 2927 p2i(consts_end()), 2928 consts_size()); 2929 if (insts_size () > 0) tty->print_cr(" main code [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d", 2930 p2i(insts_begin()), 2931 p2i(insts_end()), 2932 insts_size()); 2933 if (stub_size () > 0) tty->print_cr(" stub code [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d", 2934 p2i(stub_begin()), 2935 p2i(stub_end()), 2936 stub_size()); 2937 if (oops_size () > 0) tty->print_cr(" oops [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d", 2938 p2i(oops_begin()), 2939 p2i(oops_end()), 2940 oops_size()); 2941 if (metadata_size () > 0) tty->print_cr(" metadata [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d", 2942 p2i(metadata_begin()), 2943 p2i(metadata_end()), 2944 metadata_size()); 2945 if (scopes_data_size () > 0) tty->print_cr(" scopes data [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d", 2946 p2i(scopes_data_begin()), 2947 p2i(scopes_data_end()), 2948 scopes_data_size()); 2949 if (scopes_pcs_size () > 0) tty->print_cr(" scopes pcs [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d", 2950 p2i(scopes_pcs_begin()), 2951 p2i(scopes_pcs_end()), 2952 scopes_pcs_size()); 2953 if (dependencies_size () > 0) tty->print_cr(" dependencies [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d", 2954 p2i(dependencies_begin()), 2955 p2i(dependencies_end()), 2956 dependencies_size()); 2957 if (handler_table_size() > 0) tty->print_cr(" handler table [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d", 2958 p2i(handler_table_begin()), 2959 p2i(handler_table_end()), 2960 handler_table_size()); 2961 if (nul_chk_table_size() > 0) tty->print_cr(" nul chk table [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d", 2962 p2i(nul_chk_table_begin()), 2963 p2i(nul_chk_table_end()), 2964 nul_chk_table_size()); 2965 } 2966 2967 #ifndef PRODUCT 2968 2969 void nmethod::print_scopes() { 2970 // Find the first pc desc for all scopes in the code and print it. 2971 ResourceMark rm; 2972 for (PcDesc* p = scopes_pcs_begin(); p < scopes_pcs_end(); p++) { 2973 if (p->scope_decode_offset() == DebugInformationRecorder::serialized_null) 2974 continue; 2975 2976 ScopeDesc* sd = scope_desc_at(p->real_pc(this)); 2977 while (sd != NULL) { 2978 sd->print_on(tty, p); 2979 sd = sd->sender(); 2980 } 2981 } 2982 } 2983 2984 void nmethod::print_dependencies() { 2985 ResourceMark rm; 2986 ttyLocker ttyl; // keep the following output all in one block 2987 tty->print_cr("Dependencies:"); 2988 for (Dependencies::DepStream deps(this); deps.next(); ) { 2989 deps.print_dependency(); 2990 Klass* ctxk = deps.context_type(); 2991 if (ctxk != NULL) { 2992 if (ctxk->is_instance_klass() && InstanceKlass::cast(ctxk)->is_dependent_nmethod(this)) { 2993 tty->print_cr(" [nmethod<=klass]%s", ctxk->external_name()); 2994 } 2995 } 2996 deps.log_dependency(); // put it into the xml log also 2997 } 2998 } 2999 3000 3001 void nmethod::print_relocations() { 3002 ResourceMark m; // in case methods get printed via the debugger 3003 tty->print_cr("relocations:"); 3004 RelocIterator iter(this); 3005 iter.print(); 3006 if (UseRelocIndex) { 3007 jint* index_end = (jint*)relocation_end() - 1; 3008 jint index_size = *index_end; 3009 jint* index_start = (jint*)( (address)index_end - index_size ); 3010 tty->print_cr(" index @" INTPTR_FORMAT ": index_size=%d", p2i(index_start), index_size); 3011 if (index_size > 0) { 3012 jint* ip; 3013 for (ip = index_start; ip+2 <= index_end; ip += 2) 3014 tty->print_cr(" (%d %d) addr=" INTPTR_FORMAT " @" INTPTR_FORMAT, 3015 ip[0], 3016 ip[1], 3017 p2i(header_end()+ip[0]), 3018 p2i(relocation_begin()-1+ip[1])); 3019 for (; ip < index_end; ip++) 3020 tty->print_cr(" (%d ?)", ip[0]); 3021 tty->print_cr(" @" INTPTR_FORMAT ": index_size=%d", p2i(ip), *ip); 3022 ip++; 3023 tty->print_cr("reloc_end @" INTPTR_FORMAT ":", p2i(ip)); 3024 } 3025 } 3026 } 3027 3028 3029 void nmethod::print_pcs() { 3030 ResourceMark m; // in case methods get printed via debugger 3031 tty->print_cr("pc-bytecode offsets:"); 3032 for (PcDesc* p = scopes_pcs_begin(); p < scopes_pcs_end(); p++) { 3033 p->print(this); 3034 } 3035 } 3036 3037 void nmethod::print_recorded_oops() { 3038 tty->print_cr("Recorded oops:"); 3039 for (int i = 0; i < oops_count(); i++) { 3040 oop o = oop_at(i); 3041 tty->print("#%3d: " INTPTR_FORMAT " ", i, p2i(o)); 3042 if (o == (oop)Universe::non_oop_word()) { 3043 tty->print("non-oop word"); 3044 } else { 3045 o->print_value(); 3046 } 3047 tty->cr(); 3048 } 3049 } 3050 3051 void nmethod::print_recorded_metadata() { 3052 tty->print_cr("Recorded metadata:"); 3053 for (int i = 0; i < metadata_count(); i++) { 3054 Metadata* m = metadata_at(i); 3055 tty->print("#%3d: " INTPTR_FORMAT " ", i, p2i(m)); 3056 if (m == (Metadata*)Universe::non_oop_word()) { 3057 tty->print("non-metadata word"); 3058 } else { 3059 m->print_value_on_maybe_null(tty); 3060 } 3061 tty->cr(); 3062 } 3063 } 3064 3065 #endif // PRODUCT 3066 3067 const char* nmethod::reloc_string_for(u_char* begin, u_char* end) { 3068 RelocIterator iter(this, begin, end); 3069 bool have_one = false; 3070 while (iter.next()) { 3071 have_one = true; 3072 switch (iter.type()) { 3073 case relocInfo::none: return "no_reloc"; 3074 case relocInfo::oop_type: { 3075 stringStream st; 3076 oop_Relocation* r = iter.oop_reloc(); 3077 oop obj = r->oop_value(); 3078 st.print("oop("); 3079 if (obj == NULL) st.print("NULL"); 3080 else obj->print_value_on(&st); 3081 st.print(")"); 3082 return st.as_string(); 3083 } 3084 case relocInfo::metadata_type: { 3085 stringStream st; 3086 metadata_Relocation* r = iter.metadata_reloc(); 3087 Metadata* obj = r->metadata_value(); 3088 st.print("metadata("); 3089 if (obj == NULL) st.print("NULL"); 3090 else obj->print_value_on(&st); 3091 st.print(")"); 3092 return st.as_string(); 3093 } 3094 case relocInfo::runtime_call_type: { 3095 stringStream st; 3096 st.print("runtime_call"); 3097 runtime_call_Relocation* r = iter.runtime_call_reloc(); 3098 address dest = r->destination(); 3099 CodeBlob* cb = CodeCache::find_blob(dest); 3100 if (cb != NULL) { 3101 st.print(" %s", cb->name()); 3102 } else { 3103 ResourceMark rm; 3104 const int buflen = 1024; 3105 char* buf = NEW_RESOURCE_ARRAY(char, buflen); 3106 int offset; 3107 if (os::dll_address_to_function_name(dest, buf, buflen, &offset)) { 3108 st.print(" %s", buf); 3109 if (offset != 0) { 3110 st.print("+%d", offset); 3111 } 3112 } 3113 } 3114 return st.as_string(); 3115 } 3116 case relocInfo::virtual_call_type: { 3117 stringStream st; 3118 st.print_raw("virtual_call"); 3119 virtual_call_Relocation* r = iter.virtual_call_reloc(); 3120 Method* m = r->method_value(); 3121 if (m != NULL) { 3122 assert(m->is_method(), ""); 3123 m->print_short_name(&st); 3124 } 3125 return st.as_string(); 3126 } 3127 case relocInfo::opt_virtual_call_type: { 3128 stringStream st; 3129 st.print_raw("optimized virtual_call"); 3130 opt_virtual_call_Relocation* r = iter.opt_virtual_call_reloc(); 3131 Method* m = r->method_value(); 3132 if (m != NULL) { 3133 assert(m->is_method(), ""); 3134 m->print_short_name(&st); 3135 } 3136 return st.as_string(); 3137 } 3138 case relocInfo::static_call_type: { 3139 stringStream st; 3140 st.print_raw("static_call"); 3141 static_call_Relocation* r = iter.static_call_reloc(); 3142 Method* m = r->method_value(); 3143 if (m != NULL) { 3144 assert(m->is_method(), ""); 3145 m->print_short_name(&st); 3146 } 3147 return st.as_string(); 3148 } 3149 case relocInfo::static_stub_type: return "static_stub"; 3150 case relocInfo::external_word_type: return "external_word"; 3151 case relocInfo::internal_word_type: return "internal_word"; 3152 case relocInfo::section_word_type: return "section_word"; 3153 case relocInfo::poll_type: return "poll"; 3154 case relocInfo::poll_return_type: return "poll_return"; 3155 case relocInfo::type_mask: return "type_bit_mask"; 3156 } 3157 } 3158 return have_one ? "other" : NULL; 3159 } 3160 3161 // Return a the last scope in (begin..end] 3162 ScopeDesc* nmethod::scope_desc_in(address begin, address end) { 3163 PcDesc* p = pc_desc_near(begin+1); 3164 if (p != NULL && p->real_pc(this) <= end) { 3165 return new ScopeDesc(this, p->scope_decode_offset(), 3166 p->obj_decode_offset(), p->should_reexecute(), p->rethrow_exception(), 3167 p->return_oop()); 3168 } 3169 return NULL; 3170 } 3171 3172 void nmethod::print_nmethod_labels(outputStream* stream, address block_begin) const { 3173 if (block_begin == entry_point()) stream->print_cr("[Entry Point]"); 3174 if (block_begin == verified_entry_point()) stream->print_cr("[Verified Entry Point]"); 3175 if (JVMCI_ONLY(_exception_offset >= 0 &&) block_begin == exception_begin()) stream->print_cr("[Exception Handler]"); 3176 if (block_begin == stub_begin()) stream->print_cr("[Stub Code]"); 3177 if (JVMCI_ONLY(_deoptimize_offset >= 0 &&) block_begin == deopt_handler_begin()) stream->print_cr("[Deopt Handler Code]"); 3178 3179 if (has_method_handle_invokes()) 3180 if (block_begin == deopt_mh_handler_begin()) stream->print_cr("[Deopt MH Handler Code]"); 3181 3182 if (block_begin == consts_begin()) stream->print_cr("[Constants]"); 3183 3184 if (block_begin == entry_point()) { 3185 methodHandle m = method(); 3186 if (m.not_null()) { 3187 stream->print(" # "); 3188 m->print_value_on(stream); 3189 stream->cr(); 3190 } 3191 if (m.not_null() && !is_osr_method()) { 3192 ResourceMark rm; 3193 int sizeargs = m->size_of_parameters(); 3194 BasicType* sig_bt = NEW_RESOURCE_ARRAY(BasicType, sizeargs); 3195 VMRegPair* regs = NEW_RESOURCE_ARRAY(VMRegPair, sizeargs); 3196 { 3197 int sig_index = 0; 3198 if (!m->is_static()) 3199 sig_bt[sig_index++] = T_OBJECT; // 'this' 3200 for (SignatureStream ss(m->signature()); !ss.at_return_type(); ss.next()) { 3201 BasicType t = ss.type(); 3202 sig_bt[sig_index++] = t; 3203 if (type2size[t] == 2) { 3204 sig_bt[sig_index++] = T_VOID; 3205 } else { 3206 assert(type2size[t] == 1, "size is 1 or 2"); 3207 } 3208 } 3209 assert(sig_index == sizeargs, ""); 3210 } 3211 const char* spname = "sp"; // make arch-specific? 3212 intptr_t out_preserve = SharedRuntime::java_calling_convention(sig_bt, regs, sizeargs, false); 3213 int stack_slot_offset = this->frame_size() * wordSize; 3214 int tab1 = 14, tab2 = 24; 3215 int sig_index = 0; 3216 int arg_index = (m->is_static() ? 0 : -1); 3217 bool did_old_sp = false; 3218 for (SignatureStream ss(m->signature()); !ss.at_return_type(); ) { 3219 bool at_this = (arg_index == -1); 3220 bool at_old_sp = false; 3221 BasicType t = (at_this ? T_OBJECT : ss.type()); 3222 assert(t == sig_bt[sig_index], "sigs in sync"); 3223 if (at_this) 3224 stream->print(" # this: "); 3225 else 3226 stream->print(" # parm%d: ", arg_index); 3227 stream->move_to(tab1); 3228 VMReg fst = regs[sig_index].first(); 3229 VMReg snd = regs[sig_index].second(); 3230 if (fst->is_reg()) { 3231 stream->print("%s", fst->name()); 3232 if (snd->is_valid()) { 3233 stream->print(":%s", snd->name()); 3234 } 3235 } else if (fst->is_stack()) { 3236 int offset = fst->reg2stack() * VMRegImpl::stack_slot_size + stack_slot_offset; 3237 if (offset == stack_slot_offset) at_old_sp = true; 3238 stream->print("[%s+0x%x]", spname, offset); 3239 } else { 3240 stream->print("reg%d:%d??", (int)(intptr_t)fst, (int)(intptr_t)snd); 3241 } 3242 stream->print(" "); 3243 stream->move_to(tab2); 3244 stream->print("= "); 3245 if (at_this) { 3246 m->method_holder()->print_value_on(stream); 3247 } else { 3248 bool did_name = false; 3249 if (!at_this && ss.is_object()) { 3250 Symbol* name = ss.as_symbol_or_null(); 3251 if (name != NULL) { 3252 name->print_value_on(stream); 3253 did_name = true; 3254 } 3255 } 3256 if (!did_name) 3257 stream->print("%s", type2name(t)); 3258 } 3259 if (at_old_sp) { 3260 stream->print(" (%s of caller)", spname); 3261 did_old_sp = true; 3262 } 3263 stream->cr(); 3264 sig_index += type2size[t]; 3265 arg_index += 1; 3266 if (!at_this) ss.next(); 3267 } 3268 if (!did_old_sp) { 3269 stream->print(" # "); 3270 stream->move_to(tab1); 3271 stream->print("[%s+0x%x]", spname, stack_slot_offset); 3272 stream->print(" (%s of caller)", spname); 3273 stream->cr(); 3274 } 3275 } 3276 } 3277 } 3278 3279 void nmethod::print_code_comment_on(outputStream* st, int column, u_char* begin, u_char* end) { 3280 // First, find an oopmap in (begin, end]. 3281 // We use the odd half-closed interval so that oop maps and scope descs 3282 // which are tied to the byte after a call are printed with the call itself. 3283 address base = code_begin(); 3284 ImmutableOopMapSet* oms = oop_maps(); 3285 if (oms != NULL) { 3286 for (int i = 0, imax = oms->count(); i < imax; i++) { 3287 const ImmutableOopMapPair* pair = oms->pair_at(i); 3288 const ImmutableOopMap* om = pair->get_from(oms); 3289 address pc = base + pair->pc_offset(); 3290 if (pc > begin) { 3291 if (pc <= end) { 3292 st->move_to(column); 3293 st->print("; "); 3294 om->print_on(st); 3295 } 3296 break; 3297 } 3298 } 3299 } 3300 3301 // Print any debug info present at this pc. 3302 ScopeDesc* sd = scope_desc_in(begin, end); 3303 if (sd != NULL) { 3304 st->move_to(column); 3305 if (sd->bci() == SynchronizationEntryBCI) { 3306 st->print(";*synchronization entry"); 3307 } else { 3308 if (sd->method() == NULL) { 3309 st->print("method is NULL"); 3310 } else if (sd->method()->is_native()) { 3311 st->print("method is native"); 3312 } else { 3313 Bytecodes::Code bc = sd->method()->java_code_at(sd->bci()); 3314 st->print(";*%s", Bytecodes::name(bc)); 3315 switch (bc) { 3316 case Bytecodes::_invokevirtual: 3317 case Bytecodes::_invokespecial: 3318 case Bytecodes::_invokestatic: 3319 case Bytecodes::_invokeinterface: 3320 { 3321 Bytecode_invoke invoke(sd->method(), sd->bci()); 3322 st->print(" "); 3323 if (invoke.name() != NULL) 3324 invoke.name()->print_symbol_on(st); 3325 else 3326 st->print("<UNKNOWN>"); 3327 break; 3328 } 3329 case Bytecodes::_getfield: 3330 case Bytecodes::_putfield: 3331 case Bytecodes::_getstatic: 3332 case Bytecodes::_putstatic: 3333 { 3334 Bytecode_field field(sd->method(), sd->bci()); 3335 st->print(" "); 3336 if (field.name() != NULL) 3337 field.name()->print_symbol_on(st); 3338 else 3339 st->print("<UNKNOWN>"); 3340 } 3341 } 3342 } 3343 st->print(" {reexecute=%d rethrow=%d return_oop=%d}", sd->should_reexecute(), sd->rethrow_exception(), sd->return_oop()); 3344 } 3345 3346 // Print all scopes 3347 for (;sd != NULL; sd = sd->sender()) { 3348 st->move_to(column); 3349 st->print("; -"); 3350 if (sd->method() == NULL) { 3351 st->print("method is NULL"); 3352 } else { 3353 sd->method()->print_short_name(st); 3354 } 3355 int lineno = sd->method()->line_number_from_bci(sd->bci()); 3356 if (lineno != -1) { 3357 st->print("@%d (line %d)", sd->bci(), lineno); 3358 } else { 3359 st->print("@%d", sd->bci()); 3360 } 3361 st->cr(); 3362 } 3363 } 3364 3365 // Print relocation information 3366 const char* str = reloc_string_for(begin, end); 3367 if (str != NULL) { 3368 if (sd != NULL) st->cr(); 3369 st->move_to(column); 3370 st->print("; {%s}", str); 3371 } 3372 int cont_offset = ImplicitExceptionTable(this).at(begin - code_begin()); 3373 if (cont_offset != 0) { 3374 st->move_to(column); 3375 st->print("; implicit exception: dispatches to " INTPTR_FORMAT, p2i(code_begin() + cont_offset)); 3376 } 3377 3378 } 3379 3380 #ifndef PRODUCT 3381 3382 void nmethod::print_value_on(outputStream* st) const { 3383 st->print("nmethod"); 3384 print_on(st, NULL); 3385 } 3386 3387 void nmethod::print_calls(outputStream* st) { 3388 RelocIterator iter(this); 3389 while (iter.next()) { 3390 switch (iter.type()) { 3391 case relocInfo::virtual_call_type: 3392 case relocInfo::opt_virtual_call_type: { 3393 VerifyMutexLocker mc(CompiledIC_lock); 3394 CompiledIC_at(&iter)->print(); 3395 break; 3396 } 3397 case relocInfo::static_call_type: 3398 st->print_cr("Static call at " INTPTR_FORMAT, p2i(iter.reloc()->addr())); 3399 compiledStaticCall_at(iter.reloc())->print(); 3400 break; 3401 } 3402 } 3403 } 3404 3405 void nmethod::print_handler_table() { 3406 ExceptionHandlerTable(this).print(); 3407 } 3408 3409 void nmethod::print_nul_chk_table() { 3410 ImplicitExceptionTable(this).print(code_begin()); 3411 } 3412 3413 void nmethod::print_statistics() { 3414 ttyLocker ttyl; 3415 if (xtty != NULL) xtty->head("statistics type='nmethod'"); 3416 native_nmethod_stats.print_native_nmethod_stats(); 3417 #ifdef COMPILER1 3418 c1_java_nmethod_stats.print_nmethod_stats("C1"); 3419 #endif 3420 #ifdef COMPILER2 3421 c2_java_nmethod_stats.print_nmethod_stats("C2"); 3422 #endif 3423 #if INCLUDE_JVMCI 3424 jvmci_java_nmethod_stats.print_nmethod_stats("JVMCI"); 3425 #endif 3426 #ifdef SHARK 3427 shark_java_nmethod_stats.print_nmethod_stats("Shark"); 3428 #endif 3429 unknown_java_nmethod_stats.print_nmethod_stats("Unknown"); 3430 DebugInformationRecorder::print_statistics(); 3431 #ifndef PRODUCT 3432 pc_nmethod_stats.print_pc_stats(); 3433 #endif 3434 Dependencies::print_statistics(); 3435 if (xtty != NULL) xtty->tail("statistics"); 3436 } 3437 3438 #endif // !PRODUCT 3439 3440 #if INCLUDE_JVMCI 3441 void nmethod::clear_jvmci_installed_code() { 3442 // write_ref_method_pre/post can only be safely called at a 3443 // safepoint or while holding the CodeCache_lock 3444 assert(CodeCache_lock->is_locked() || 3445 SafepointSynchronize::is_at_safepoint(), "should be performed under a lock for consistency"); 3446 if (_jvmci_installed_code != NULL) { 3447 // This must be done carefully to maintain nmethod remembered sets properly 3448 BarrierSet* bs = Universe::heap()->barrier_set(); 3449 bs->write_ref_nmethod_pre(&_jvmci_installed_code, this); 3450 _jvmci_installed_code = NULL; 3451 bs->write_ref_nmethod_post(&_jvmci_installed_code, this); 3452 } 3453 } 3454 3455 void nmethod::maybe_invalidate_installed_code() { 3456 assert(Patching_lock->is_locked() || 3457 SafepointSynchronize::is_at_safepoint(), "should be performed under a lock for consistency"); 3458 oop installed_code = jvmci_installed_code(); 3459 if (installed_code != NULL) { 3460 nmethod* nm = (nmethod*)InstalledCode::address(installed_code); 3461 if (nm == NULL || nm != this) { 3462 // The link has been broken or the InstalledCode instance is 3463 // associated with another nmethod so do nothing. 3464 return; 3465 } 3466 if (!is_alive()) { 3467 // Break the link between nmethod and InstalledCode such that the nmethod 3468 // can subsequently be flushed safely. The link must be maintained while 3469 // the method could have live activations since invalidateInstalledCode 3470 // might want to invalidate all existing activations. 3471 InstalledCode::set_address(installed_code, 0); 3472 InstalledCode::set_entryPoint(installed_code, 0); 3473 } else if (is_not_entrant()) { 3474 // Remove the entry point so any invocation will fail but keep 3475 // the address link around that so that existing activations can 3476 // be invalidated. 3477 InstalledCode::set_entryPoint(installed_code, 0); 3478 } 3479 } 3480 } 3481 3482 void nmethod::invalidate_installed_code(Handle installedCode, TRAPS) { 3483 if (installedCode() == NULL) { 3484 THROW(vmSymbols::java_lang_NullPointerException()); 3485 } 3486 jlong nativeMethod = InstalledCode::address(installedCode); 3487 nmethod* nm = (nmethod*)nativeMethod; 3488 if (nm == NULL) { 3489 // Nothing to do 3490 return; 3491 } 3492 3493 nmethodLocker nml(nm); 3494 #ifdef ASSERT 3495 { 3496 MutexLockerEx pl(Patching_lock, Mutex::_no_safepoint_check_flag); 3497 // This relationship can only be checked safely under a lock 3498 assert(nm == NULL || !nm->is_alive() || nm->jvmci_installed_code() == installedCode(), "sanity check"); 3499 } 3500 #endif 3501 3502 if (nm->is_alive()) { 3503 // The nmethod state machinery maintains the link between the 3504 // HotSpotInstalledCode and nmethod* so as long as the nmethod appears to be 3505 // alive assume there is work to do and deoptimize the nmethod. 3506 nm->mark_for_deoptimization(); 3507 VM_Deoptimize op; 3508 VMThread::execute(&op); 3509 } 3510 3511 MutexLockerEx pl(Patching_lock, Mutex::_no_safepoint_check_flag); 3512 // Check that it's still associated with the same nmethod and break 3513 // the link if it is. 3514 if (InstalledCode::address(installedCode) == nativeMethod) { 3515 InstalledCode::set_address(installedCode, 0); 3516 } 3517 } 3518 3519 char* nmethod::jvmci_installed_code_name(char* buf, size_t buflen) { 3520 if (!this->is_compiled_by_jvmci()) { 3521 return NULL; 3522 } 3523 oop installedCode = this->jvmci_installed_code(); 3524 if (installedCode != NULL) { 3525 oop installedCodeName = NULL; 3526 if (installedCode->is_a(InstalledCode::klass())) { 3527 installedCodeName = InstalledCode::name(installedCode); 3528 } 3529 if (installedCodeName != NULL) { 3530 return java_lang_String::as_utf8_string(installedCodeName, buf, (int)buflen); 3531 } else { 3532 jio_snprintf(buf, buflen, "null"); 3533 return buf; 3534 } 3535 } 3536 jio_snprintf(buf, buflen, "noInstalledCode"); 3537 return buf; 3538 } 3539 #endif 3540 3541 Method* nmethod::attached_method(address call_instr) { 3542 assert(code_contains(call_instr), "not part of the nmethod"); 3543 RelocIterator iter(this, call_instr, call_instr + 1); 3544 while (iter.next()) { 3545 if (iter.addr() == call_instr) { 3546 switch(iter.type()) { 3547 case relocInfo::static_call_type: return iter.static_call_reloc()->method_value(); 3548 case relocInfo::opt_virtual_call_type: return iter.opt_virtual_call_reloc()->method_value(); 3549 case relocInfo::virtual_call_type: return iter.virtual_call_reloc()->method_value(); 3550 } 3551 } 3552 } 3553 return NULL; // not found 3554 } 3555 3556 Method* nmethod::attached_method_before_pc(address pc) { 3557 if (NativeCall::is_call_before(pc)) { 3558 NativeCall* ncall = nativeCall_before(pc); 3559 return attached_method(ncall->instruction_address()); 3560 } 3561 return NULL; // not a call 3562 } 3563