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