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