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