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