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