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