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