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