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