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