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