Path: blob/master/src/hotspot/share/code/nmethod.cpp
64440 views
/*1* Copyright (c) 1997, 2021, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation.7*8* This code is distributed in the hope that it will be useful, but WITHOUT9* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or10* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License11* version 2 for more details (a copy is included in the LICENSE file that12* accompanied this code).13*14* You should have received a copy of the GNU General Public License version15* 2 along with this work; if not, write to the Free Software Foundation,16* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.17*18* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA19* or visit www.oracle.com if you need additional information or have any20* questions.21*22*/2324#include "precompiled.hpp"25#include "jvm.h"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/compileBroker.hpp"36#include "compiler/compileLog.hpp"37#include "compiler/compilerDirectives.hpp"38#include "compiler/directivesParser.hpp"39#include "compiler/disassembler.hpp"40#include "compiler/oopMap.hpp"41#include "gc/shared/collectedHeap.hpp"42#include "interpreter/bytecode.hpp"43#include "logging/log.hpp"44#include "logging/logStream.hpp"45#include "memory/allocation.inline.hpp"46#include "memory/resourceArea.hpp"47#include "memory/universe.hpp"48#include "oops/access.inline.hpp"49#include "oops/klass.inline.hpp"50#include "oops/method.inline.hpp"51#include "oops/methodData.hpp"52#include "oops/oop.inline.hpp"53#include "prims/jvmtiImpl.hpp"54#include "prims/jvmtiThreadState.hpp"55#include "prims/methodHandles.hpp"56#include "runtime/atomic.hpp"57#include "runtime/deoptimization.hpp"58#include "runtime/flags/flagSetting.hpp"59#include "runtime/frame.inline.hpp"60#include "runtime/handles.inline.hpp"61#include "runtime/jniHandles.inline.hpp"62#include "runtime/orderAccess.hpp"63#include "runtime/os.hpp"64#include "runtime/safepointVerifiers.hpp"65#include "runtime/serviceThread.hpp"66#include "runtime/sharedRuntime.hpp"67#include "runtime/signature.hpp"68#include "runtime/sweeper.hpp"69#include "runtime/vmThread.hpp"70#include "utilities/align.hpp"71#include "utilities/copy.hpp"72#include "utilities/dtrace.hpp"73#include "utilities/events.hpp"74#include "utilities/globalDefinitions.hpp"75#include "utilities/resourceHash.hpp"76#include "utilities/xmlstream.hpp"77#if INCLUDE_JVMCI78#include "jvmci/jvmciRuntime.hpp"79#endif8081#ifdef DTRACE_ENABLED8283// Only bother with this argument setup if dtrace is available8485#define DTRACE_METHOD_UNLOAD_PROBE(method) \86{ \87Method* m = (method); \88if (m != NULL) { \89Symbol* klass_name = m->klass_name(); \90Symbol* name = m->name(); \91Symbol* signature = m->signature(); \92HOTSPOT_COMPILED_METHOD_UNLOAD( \93(char *) klass_name->bytes(), klass_name->utf8_length(), \94(char *) name->bytes(), name->utf8_length(), \95(char *) signature->bytes(), signature->utf8_length()); \96} \97}9899#else // ndef DTRACE_ENABLED100101#define DTRACE_METHOD_UNLOAD_PROBE(method)102103#endif104105//---------------------------------------------------------------------------------106// NMethod statistics107// They are printed under various flags, including:108// PrintC1Statistics, PrintOptoStatistics, LogVMOutput, and LogCompilation.109// (In the latter two cases, they like other stats are printed to the log only.)110111#ifndef PRODUCT112// These variables are put into one block to reduce relocations113// and make it simpler to print from the debugger.114struct java_nmethod_stats_struct {115int nmethod_count;116int total_size;117int relocation_size;118int consts_size;119int insts_size;120int stub_size;121int scopes_data_size;122int scopes_pcs_size;123int dependencies_size;124int handler_table_size;125int nul_chk_table_size;126#if INCLUDE_JVMCI127int speculations_size;128int jvmci_data_size;129#endif130int oops_size;131int metadata_size;132133void note_nmethod(nmethod* nm) {134nmethod_count += 1;135total_size += nm->size();136relocation_size += nm->relocation_size();137consts_size += nm->consts_size();138insts_size += nm->insts_size();139stub_size += nm->stub_size();140oops_size += nm->oops_size();141metadata_size += nm->metadata_size();142scopes_data_size += nm->scopes_data_size();143scopes_pcs_size += nm->scopes_pcs_size();144dependencies_size += nm->dependencies_size();145handler_table_size += nm->handler_table_size();146nul_chk_table_size += nm->nul_chk_table_size();147#if INCLUDE_JVMCI148speculations_size += nm->speculations_size();149jvmci_data_size += nm->jvmci_data_size();150#endif151}152void print_nmethod_stats(const char* name) {153if (nmethod_count == 0) return;154tty->print_cr("Statistics for %d bytecoded nmethods for %s:", nmethod_count, name);155if (total_size != 0) tty->print_cr(" total in heap = %d", total_size);156if (nmethod_count != 0) tty->print_cr(" header = " SIZE_FORMAT, nmethod_count * sizeof(nmethod));157if (relocation_size != 0) tty->print_cr(" relocation = %d", relocation_size);158if (consts_size != 0) tty->print_cr(" constants = %d", consts_size);159if (insts_size != 0) tty->print_cr(" main code = %d", insts_size);160if (stub_size != 0) tty->print_cr(" stub code = %d", stub_size);161if (oops_size != 0) tty->print_cr(" oops = %d", oops_size);162if (metadata_size != 0) tty->print_cr(" metadata = %d", metadata_size);163if (scopes_data_size != 0) tty->print_cr(" scopes data = %d", scopes_data_size);164if (scopes_pcs_size != 0) tty->print_cr(" scopes pcs = %d", scopes_pcs_size);165if (dependencies_size != 0) tty->print_cr(" dependencies = %d", dependencies_size);166if (handler_table_size != 0) tty->print_cr(" handler table = %d", handler_table_size);167if (nul_chk_table_size != 0) tty->print_cr(" nul chk table = %d", nul_chk_table_size);168#if INCLUDE_JVMCI169if (speculations_size != 0) tty->print_cr(" speculations = %d", speculations_size);170if (jvmci_data_size != 0) tty->print_cr(" JVMCI data = %d", jvmci_data_size);171#endif172}173};174175struct native_nmethod_stats_struct {176int native_nmethod_count;177int native_total_size;178int native_relocation_size;179int native_insts_size;180int native_oops_size;181int native_metadata_size;182void note_native_nmethod(nmethod* nm) {183native_nmethod_count += 1;184native_total_size += nm->size();185native_relocation_size += nm->relocation_size();186native_insts_size += nm->insts_size();187native_oops_size += nm->oops_size();188native_metadata_size += nm->metadata_size();189}190void print_native_nmethod_stats() {191if (native_nmethod_count == 0) return;192tty->print_cr("Statistics for %d native nmethods:", native_nmethod_count);193if (native_total_size != 0) tty->print_cr(" N. total size = %d", native_total_size);194if (native_relocation_size != 0) tty->print_cr(" N. relocation = %d", native_relocation_size);195if (native_insts_size != 0) tty->print_cr(" N. main code = %d", native_insts_size);196if (native_oops_size != 0) tty->print_cr(" N. oops = %d", native_oops_size);197if (native_metadata_size != 0) tty->print_cr(" N. metadata = %d", native_metadata_size);198}199};200201struct pc_nmethod_stats_struct {202int pc_desc_resets; // number of resets (= number of caches)203int pc_desc_queries; // queries to nmethod::find_pc_desc204int pc_desc_approx; // number of those which have approximate true205int pc_desc_repeats; // number of _pc_descs[0] hits206int pc_desc_hits; // number of LRU cache hits207int pc_desc_tests; // total number of PcDesc examinations208int pc_desc_searches; // total number of quasi-binary search steps209int pc_desc_adds; // number of LUR cache insertions210211void print_pc_stats() {212tty->print_cr("PcDesc Statistics: %d queries, %.2f comparisons per query",213pc_desc_queries,214(double)(pc_desc_tests + pc_desc_searches)215/ pc_desc_queries);216tty->print_cr(" caches=%d queries=%d/%d, hits=%d+%d, tests=%d+%d, adds=%d",217pc_desc_resets,218pc_desc_queries, pc_desc_approx,219pc_desc_repeats, pc_desc_hits,220pc_desc_tests, pc_desc_searches, pc_desc_adds);221}222};223224#ifdef COMPILER1225static java_nmethod_stats_struct c1_java_nmethod_stats;226#endif227#ifdef COMPILER2228static java_nmethod_stats_struct c2_java_nmethod_stats;229#endif230#if INCLUDE_JVMCI231static java_nmethod_stats_struct jvmci_java_nmethod_stats;232#endif233static java_nmethod_stats_struct unknown_java_nmethod_stats;234235static native_nmethod_stats_struct native_nmethod_stats;236static pc_nmethod_stats_struct pc_nmethod_stats;237238static void note_java_nmethod(nmethod* nm) {239#ifdef COMPILER1240if (nm->is_compiled_by_c1()) {241c1_java_nmethod_stats.note_nmethod(nm);242} else243#endif244#ifdef COMPILER2245if (nm->is_compiled_by_c2()) {246c2_java_nmethod_stats.note_nmethod(nm);247} else248#endif249#if INCLUDE_JVMCI250if (nm->is_compiled_by_jvmci()) {251jvmci_java_nmethod_stats.note_nmethod(nm);252} else253#endif254{255unknown_java_nmethod_stats.note_nmethod(nm);256}257}258#endif // !PRODUCT259260//---------------------------------------------------------------------------------261262263ExceptionCache::ExceptionCache(Handle exception, address pc, address handler) {264assert(pc != NULL, "Must be non null");265assert(exception.not_null(), "Must be non null");266assert(handler != NULL, "Must be non null");267268_count = 0;269_exception_type = exception->klass();270_next = NULL;271_purge_list_next = NULL;272273add_address_and_handler(pc,handler);274}275276277address ExceptionCache::match(Handle exception, address pc) {278assert(pc != NULL,"Must be non null");279assert(exception.not_null(),"Must be non null");280if (exception->klass() == exception_type()) {281return (test_address(pc));282}283284return NULL;285}286287288bool ExceptionCache::match_exception_with_space(Handle exception) {289assert(exception.not_null(),"Must be non null");290if (exception->klass() == exception_type() && count() < cache_size) {291return true;292}293return false;294}295296297address ExceptionCache::test_address(address addr) {298int limit = count();299for (int i = 0; i < limit; i++) {300if (pc_at(i) == addr) {301return handler_at(i);302}303}304return NULL;305}306307308bool ExceptionCache::add_address_and_handler(address addr, address handler) {309if (test_address(addr) == handler) return true;310311int index = count();312if (index < cache_size) {313set_pc_at(index, addr);314set_handler_at(index, handler);315increment_count();316return true;317}318return false;319}320321ExceptionCache* ExceptionCache::next() {322return Atomic::load(&_next);323}324325void ExceptionCache::set_next(ExceptionCache *ec) {326Atomic::store(&_next, ec);327}328329//-----------------------------------------------------------------------------330331332// Helper used by both find_pc_desc methods.333static inline bool match_desc(PcDesc* pc, int pc_offset, bool approximate) {334NOT_PRODUCT(++pc_nmethod_stats.pc_desc_tests);335if (!approximate)336return pc->pc_offset() == pc_offset;337else338return (pc-1)->pc_offset() < pc_offset && pc_offset <= pc->pc_offset();339}340341void PcDescCache::reset_to(PcDesc* initial_pc_desc) {342if (initial_pc_desc == NULL) {343_pc_descs[0] = NULL; // native method; no PcDescs at all344return;345}346NOT_PRODUCT(++pc_nmethod_stats.pc_desc_resets);347// reset the cache by filling it with benign (non-null) values348assert(initial_pc_desc->pc_offset() < 0, "must be sentinel");349for (int i = 0; i < cache_size; i++)350_pc_descs[i] = initial_pc_desc;351}352353PcDesc* PcDescCache::find_pc_desc(int pc_offset, bool approximate) {354NOT_PRODUCT(++pc_nmethod_stats.pc_desc_queries);355NOT_PRODUCT(if (approximate) ++pc_nmethod_stats.pc_desc_approx);356357// Note: one might think that caching the most recently358// read value separately would be a win, but one would be359// wrong. When many threads are updating it, the cache360// line it's in would bounce between caches, negating361// any benefit.362363// In order to prevent race conditions do not load cache elements364// repeatedly, but use a local copy:365PcDesc* res;366367// Step one: Check the most recently added value.368res = _pc_descs[0];369if (res == NULL) return NULL; // native method; no PcDescs at all370if (match_desc(res, pc_offset, approximate)) {371NOT_PRODUCT(++pc_nmethod_stats.pc_desc_repeats);372return res;373}374375// Step two: Check the rest of the LRU cache.376for (int i = 1; i < cache_size; ++i) {377res = _pc_descs[i];378if (res->pc_offset() < 0) break; // optimization: skip empty cache379if (match_desc(res, pc_offset, approximate)) {380NOT_PRODUCT(++pc_nmethod_stats.pc_desc_hits);381return res;382}383}384385// Report failure.386return NULL;387}388389void PcDescCache::add_pc_desc(PcDesc* pc_desc) {390NOT_PRODUCT(++pc_nmethod_stats.pc_desc_adds);391// Update the LRU cache by shifting pc_desc forward.392for (int i = 0; i < cache_size; i++) {393PcDesc* next = _pc_descs[i];394_pc_descs[i] = pc_desc;395pc_desc = next;396}397}398399// adjust pcs_size so that it is a multiple of both oopSize and400// sizeof(PcDesc) (assumes that if sizeof(PcDesc) is not a multiple401// of oopSize, then 2*sizeof(PcDesc) is)402static int adjust_pcs_size(int pcs_size) {403int nsize = align_up(pcs_size, oopSize);404if ((nsize % sizeof(PcDesc)) != 0) {405nsize = pcs_size + sizeof(PcDesc);406}407assert((nsize % oopSize) == 0, "correct alignment");408return nsize;409}410411412int nmethod::total_size() const {413return414consts_size() +415insts_size() +416stub_size() +417scopes_data_size() +418scopes_pcs_size() +419handler_table_size() +420nul_chk_table_size();421}422423address* nmethod::orig_pc_addr(const frame* fr) {424return (address*) ((address)fr->unextended_sp() + _orig_pc_offset);425}426427const char* nmethod::compile_kind() const {428if (is_osr_method()) return "osr";429if (method() != NULL && is_native_method()) return "c2n";430return NULL;431}432433// Fill in default values for various flag fields434void nmethod::init_defaults() {435_state = not_installed;436_has_flushed_dependencies = 0;437_lock_count = 0;438_stack_traversal_mark = 0;439_load_reported = false; // jvmti state440_unload_reported = false;441442#ifdef ASSERT443_oops_are_stale = false;444#endif445446_oops_do_mark_link = NULL;447_osr_link = NULL;448#if INCLUDE_RTM_OPT449_rtm_state = NoRTM;450#endif451}452453nmethod* nmethod::new_native_nmethod(const methodHandle& method,454int compile_id,455CodeBuffer *code_buffer,456int vep_offset,457int frame_complete,458int frame_size,459ByteSize basic_lock_owner_sp_offset,460ByteSize basic_lock_sp_offset,461OopMapSet* oop_maps) {462code_buffer->finalize_oop_references(method);463// create nmethod464nmethod* nm = NULL;465{466MutexLocker mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);467int native_nmethod_size = CodeBlob::allocation_size(code_buffer, sizeof(nmethod));468469CodeOffsets offsets;470offsets.set_value(CodeOffsets::Verified_Entry, vep_offset);471offsets.set_value(CodeOffsets::Frame_Complete, frame_complete);472nm = new (native_nmethod_size, CompLevel_none)473nmethod(method(), compiler_none, native_nmethod_size,474compile_id, &offsets,475code_buffer, frame_size,476basic_lock_owner_sp_offset,477basic_lock_sp_offset,478oop_maps);479NOT_PRODUCT(if (nm != NULL) native_nmethod_stats.note_native_nmethod(nm));480}481482if (nm != NULL) {483// verify nmethod484debug_only(nm->verify();) // might block485486nm->log_new_nmethod();487}488return nm;489}490491nmethod* nmethod::new_nmethod(const methodHandle& method,492int compile_id,493int entry_bci,494CodeOffsets* offsets,495int orig_pc_offset,496DebugInformationRecorder* debug_info,497Dependencies* dependencies,498CodeBuffer* code_buffer, int frame_size,499OopMapSet* oop_maps,500ExceptionHandlerTable* handler_table,501ImplicitExceptionTable* nul_chk_table,502AbstractCompiler* compiler,503int comp_level,504const GrowableArrayView<RuntimeStub*>& native_invokers505#if INCLUDE_JVMCI506, char* speculations,507int speculations_len,508int nmethod_mirror_index,509const char* nmethod_mirror_name,510FailedSpeculation** failed_speculations511#endif512)513{514assert(debug_info->oop_recorder() == code_buffer->oop_recorder(), "shared OR");515code_buffer->finalize_oop_references(method);516// create nmethod517nmethod* nm = NULL;518{ MutexLocker mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);519#if INCLUDE_JVMCI520int jvmci_data_size = !compiler->is_jvmci() ? 0 : JVMCINMethodData::compute_size(nmethod_mirror_name);521#endif522int nmethod_size =523CodeBlob::allocation_size(code_buffer, sizeof(nmethod))524+ adjust_pcs_size(debug_info->pcs_size())525+ align_up((int)dependencies->size_in_bytes(), oopSize)526+ align_up(checked_cast<int>(native_invokers.data_size_in_bytes()), oopSize)527+ align_up(handler_table->size_in_bytes() , oopSize)528+ align_up(nul_chk_table->size_in_bytes() , oopSize)529#if INCLUDE_JVMCI530+ align_up(speculations_len , oopSize)531+ align_up(jvmci_data_size , oopSize)532#endif533+ align_up(debug_info->data_size() , oopSize);534535nm = new (nmethod_size, comp_level)536nmethod(method(), compiler->type(), nmethod_size, compile_id, entry_bci, offsets,537orig_pc_offset, debug_info, dependencies, code_buffer, frame_size,538oop_maps,539handler_table,540nul_chk_table,541compiler,542comp_level,543native_invokers544#if INCLUDE_JVMCI545, speculations,546speculations_len,547jvmci_data_size548#endif549);550551if (nm != NULL) {552#if INCLUDE_JVMCI553if (compiler->is_jvmci()) {554// Initialize the JVMCINMethodData object inlined into nm555nm->jvmci_nmethod_data()->initialize(nmethod_mirror_index, nmethod_mirror_name, failed_speculations);556}557#endif558// To make dependency checking during class loading fast, record559// the nmethod dependencies in the classes it is dependent on.560// This allows the dependency checking code to simply walk the561// class hierarchy above the loaded class, checking only nmethods562// which are dependent on those classes. The slow way is to563// check every nmethod for dependencies which makes it linear in564// the number of methods compiled. For applications with a lot565// classes the slow way is too slow.566for (Dependencies::DepStream deps(nm); deps.next(); ) {567if (deps.type() == Dependencies::call_site_target_value) {568// CallSite dependencies are managed on per-CallSite instance basis.569oop call_site = deps.argument_oop(0);570MethodHandles::add_dependent_nmethod(call_site, nm);571} else {572Klass* klass = deps.context_type();573if (klass == NULL) {574continue; // ignore things like evol_method575}576// record this nmethod as dependent on this klass577InstanceKlass::cast(klass)->add_dependent_nmethod(nm);578}579}580NOT_PRODUCT(if (nm != NULL) note_java_nmethod(nm));581}582}583// Do verification and logging outside CodeCache_lock.584if (nm != NULL) {585// Safepoints in nmethod::verify aren't allowed because nm hasn't been installed yet.586DEBUG_ONLY(nm->verify();)587nm->log_new_nmethod();588}589return nm;590}591592// For native wrappers593nmethod::nmethod(594Method* method,595CompilerType type,596int nmethod_size,597int compile_id,598CodeOffsets* offsets,599CodeBuffer* code_buffer,600int frame_size,601ByteSize basic_lock_owner_sp_offset,602ByteSize basic_lock_sp_offset,603OopMapSet* oop_maps )604: CompiledMethod(method, "native nmethod", type, nmethod_size, sizeof(nmethod), code_buffer, offsets->value(CodeOffsets::Frame_Complete), frame_size, oop_maps, false),605_is_unloading_state(0),606_native_receiver_sp_offset(basic_lock_owner_sp_offset),607_native_basic_lock_sp_offset(basic_lock_sp_offset)608{609{610int scopes_data_offset = 0;611int deoptimize_offset = 0;612int deoptimize_mh_offset = 0;613614debug_only(NoSafepointVerifier nsv;)615assert_locked_or_safepoint(CodeCache_lock);616617init_defaults();618_entry_bci = InvocationEntryBci;619// We have no exception handler or deopt handler make the620// values something that will never match a pc like the nmethod vtable entry621_exception_offset = 0;622_orig_pc_offset = 0;623624_consts_offset = data_offset();625_stub_offset = data_offset();626_oops_offset = data_offset();627_metadata_offset = _oops_offset + align_up(code_buffer->total_oop_size(), oopSize);628scopes_data_offset = _metadata_offset + align_up(code_buffer->total_metadata_size(), wordSize);629_scopes_pcs_offset = scopes_data_offset;630_dependencies_offset = _scopes_pcs_offset;631_native_invokers_offset = _dependencies_offset;632_handler_table_offset = _native_invokers_offset;633_nul_chk_table_offset = _handler_table_offset;634#if INCLUDE_JVMCI635_speculations_offset = _nul_chk_table_offset;636_jvmci_data_offset = _speculations_offset;637_nmethod_end_offset = _jvmci_data_offset;638#else639_nmethod_end_offset = _nul_chk_table_offset;640#endif641_compile_id = compile_id;642_comp_level = CompLevel_none;643_entry_point = code_begin() + offsets->value(CodeOffsets::Entry);644_verified_entry_point = code_begin() + offsets->value(CodeOffsets::Verified_Entry);645_osr_entry_point = NULL;646_exception_cache = NULL;647_pc_desc_container.reset_to(NULL);648_hotness_counter = NMethodSweeper::hotness_counter_reset_val();649650_scopes_data_begin = (address) this + scopes_data_offset;651_deopt_handler_begin = (address) this + deoptimize_offset;652_deopt_mh_handler_begin = (address) this + deoptimize_mh_offset;653654code_buffer->copy_code_and_locs_to(this);655code_buffer->copy_values_to(this);656657clear_unloading_state();658659Universe::heap()->register_nmethod(this);660debug_only(Universe::heap()->verify_nmethod(this));661662CodeCache::commit(this);663}664665if (PrintNativeNMethods || PrintDebugInfo || PrintRelocations || PrintDependencies) {666ttyLocker ttyl; // keep the following output all in one block667// This output goes directly to the tty, not the compiler log.668// To enable tools to match it up with the compilation activity,669// be sure to tag this tty output with the compile ID.670if (xtty != NULL) {671xtty->begin_head("print_native_nmethod");672xtty->method(_method);673xtty->stamp();674xtty->end_head(" address='" INTPTR_FORMAT "'", (intptr_t) this);675}676// Print the header part, then print the requested information.677// This is both handled in decode2(), called via print_code() -> decode()678if (PrintNativeNMethods) {679tty->print_cr("-------------------------- Assembly (native nmethod) ---------------------------");680print_code();681tty->print_cr("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ");682#if defined(SUPPORT_DATA_STRUCTS)683if (AbstractDisassembler::show_structs()) {684if (oop_maps != NULL) {685tty->print("oop maps:"); // oop_maps->print_on(tty) outputs a cr() at the beginning686oop_maps->print_on(tty);687tty->print_cr("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ");688}689}690#endif691} else {692print(); // print the header part only.693}694#if defined(SUPPORT_DATA_STRUCTS)695if (AbstractDisassembler::show_structs()) {696if (PrintRelocations) {697print_relocations();698tty->print_cr("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ");699}700}701#endif702if (xtty != NULL) {703xtty->tail("print_native_nmethod");704}705}706}707708void* nmethod::operator new(size_t size, int nmethod_size, int comp_level) throw () {709return CodeCache::allocate(nmethod_size, CodeCache::get_code_blob_type(comp_level));710}711712nmethod::nmethod(713Method* method,714CompilerType type,715int nmethod_size,716int compile_id,717int entry_bci,718CodeOffsets* offsets,719int orig_pc_offset,720DebugInformationRecorder* debug_info,721Dependencies* dependencies,722CodeBuffer *code_buffer,723int frame_size,724OopMapSet* oop_maps,725ExceptionHandlerTable* handler_table,726ImplicitExceptionTable* nul_chk_table,727AbstractCompiler* compiler,728int comp_level,729const GrowableArrayView<RuntimeStub*>& native_invokers730#if INCLUDE_JVMCI731, char* speculations,732int speculations_len,733int jvmci_data_size734#endif735)736: CompiledMethod(method, "nmethod", type, nmethod_size, sizeof(nmethod), code_buffer, offsets->value(CodeOffsets::Frame_Complete), frame_size, oop_maps, false),737_is_unloading_state(0),738_native_receiver_sp_offset(in_ByteSize(-1)),739_native_basic_lock_sp_offset(in_ByteSize(-1))740{741assert(debug_info->oop_recorder() == code_buffer->oop_recorder(), "shared OR");742{743debug_only(NoSafepointVerifier nsv;)744assert_locked_or_safepoint(CodeCache_lock);745746_deopt_handler_begin = (address) this;747_deopt_mh_handler_begin = (address) this;748749init_defaults();750_entry_bci = entry_bci;751_compile_id = compile_id;752_comp_level = comp_level;753_orig_pc_offset = orig_pc_offset;754_hotness_counter = NMethodSweeper::hotness_counter_reset_val();755756// Section offsets757_consts_offset = content_offset() + code_buffer->total_offset_of(code_buffer->consts());758_stub_offset = content_offset() + code_buffer->total_offset_of(code_buffer->stubs());759set_ctable_begin(header_begin() + _consts_offset);760761#if INCLUDE_JVMCI762if (compiler->is_jvmci()) {763// JVMCI might not produce any stub sections764if (offsets->value(CodeOffsets::Exceptions) != -1) {765_exception_offset = code_offset() + offsets->value(CodeOffsets::Exceptions);766} else {767_exception_offset = -1;768}769if (offsets->value(CodeOffsets::Deopt) != -1) {770_deopt_handler_begin = (address) this + code_offset() + offsets->value(CodeOffsets::Deopt);771} else {772_deopt_handler_begin = NULL;773}774if (offsets->value(CodeOffsets::DeoptMH) != -1) {775_deopt_mh_handler_begin = (address) this + code_offset() + offsets->value(CodeOffsets::DeoptMH);776} else {777_deopt_mh_handler_begin = NULL;778}779} else780#endif781{782// Exception handler and deopt handler are in the stub section783assert(offsets->value(CodeOffsets::Exceptions) != -1, "must be set");784assert(offsets->value(CodeOffsets::Deopt ) != -1, "must be set");785786_exception_offset = _stub_offset + offsets->value(CodeOffsets::Exceptions);787_deopt_handler_begin = (address) this + _stub_offset + offsets->value(CodeOffsets::Deopt);788if (offsets->value(CodeOffsets::DeoptMH) != -1) {789_deopt_mh_handler_begin = (address) this + _stub_offset + offsets->value(CodeOffsets::DeoptMH);790} else {791_deopt_mh_handler_begin = NULL;792}793}794if (offsets->value(CodeOffsets::UnwindHandler) != -1) {795_unwind_handler_offset = code_offset() + offsets->value(CodeOffsets::UnwindHandler);796} else {797_unwind_handler_offset = -1;798}799800_oops_offset = data_offset();801_metadata_offset = _oops_offset + align_up(code_buffer->total_oop_size(), oopSize);802int scopes_data_offset = _metadata_offset + align_up(code_buffer->total_metadata_size(), wordSize);803804_scopes_pcs_offset = scopes_data_offset + align_up(debug_info->data_size (), oopSize);805_dependencies_offset = _scopes_pcs_offset + adjust_pcs_size(debug_info->pcs_size());806_native_invokers_offset = _dependencies_offset + align_up((int)dependencies->size_in_bytes(), oopSize);807_handler_table_offset = _native_invokers_offset + align_up(checked_cast<int>(native_invokers.data_size_in_bytes()), oopSize);808_nul_chk_table_offset = _handler_table_offset + align_up(handler_table->size_in_bytes(), oopSize);809#if INCLUDE_JVMCI810_speculations_offset = _nul_chk_table_offset + align_up(nul_chk_table->size_in_bytes(), oopSize);811_jvmci_data_offset = _speculations_offset + align_up(speculations_len, oopSize);812_nmethod_end_offset = _jvmci_data_offset + align_up(jvmci_data_size, oopSize);813#else814_nmethod_end_offset = _nul_chk_table_offset + align_up(nul_chk_table->size_in_bytes(), oopSize);815#endif816_entry_point = code_begin() + offsets->value(CodeOffsets::Entry);817_verified_entry_point = code_begin() + offsets->value(CodeOffsets::Verified_Entry);818_osr_entry_point = code_begin() + offsets->value(CodeOffsets::OSR_Entry);819_exception_cache = NULL;820_scopes_data_begin = (address) this + scopes_data_offset;821822_pc_desc_container.reset_to(scopes_pcs_begin());823824code_buffer->copy_code_and_locs_to(this);825// Copy contents of ScopeDescRecorder to nmethod826code_buffer->copy_values_to(this);827debug_info->copy_to(this);828dependencies->copy_to(this);829if (native_invokers.is_nonempty()) { // can not get address of zero-length array830// Copy native stubs831memcpy(native_invokers_begin(), native_invokers.adr_at(0), native_invokers.data_size_in_bytes());832}833clear_unloading_state();834835Universe::heap()->register_nmethod(this);836debug_only(Universe::heap()->verify_nmethod(this));837838CodeCache::commit(this);839840// Copy contents of ExceptionHandlerTable to nmethod841handler_table->copy_to(this);842nul_chk_table->copy_to(this);843844#if INCLUDE_JVMCI845// Copy speculations to nmethod846if (speculations_size() != 0) {847memcpy(speculations_begin(), speculations, speculations_len);848}849#endif850851// we use the information of entry points to find out if a method is852// static or non static853assert(compiler->is_c2() || compiler->is_jvmci() ||854_method->is_static() == (entry_point() == _verified_entry_point),855" entry points must be same for static methods and vice versa");856}857}858859// Print a short set of xml attributes to identify this nmethod. The860// output should be embedded in some other element.861void nmethod::log_identity(xmlStream* log) const {862log->print(" compile_id='%d'", compile_id());863const char* nm_kind = compile_kind();864if (nm_kind != NULL) log->print(" compile_kind='%s'", nm_kind);865log->print(" compiler='%s'", compiler_name());866if (TieredCompilation) {867log->print(" level='%d'", comp_level());868}869#if INCLUDE_JVMCI870if (jvmci_nmethod_data() != NULL) {871const char* jvmci_name = jvmci_nmethod_data()->name();872if (jvmci_name != NULL) {873log->print(" jvmci_mirror_name='");874log->text("%s", jvmci_name);875log->print("'");876}877}878#endif879}880881882#define LOG_OFFSET(log, name) \883if (p2i(name##_end()) - p2i(name##_begin())) \884log->print(" " XSTR(name) "_offset='" INTX_FORMAT "'" , \885p2i(name##_begin()) - p2i(this))886887888void nmethod::log_new_nmethod() const {889if (LogCompilation && xtty != NULL) {890ttyLocker ttyl;891xtty->begin_elem("nmethod");892log_identity(xtty);893xtty->print(" entry='" INTPTR_FORMAT "' size='%d'", p2i(code_begin()), size());894xtty->print(" address='" INTPTR_FORMAT "'", p2i(this));895896LOG_OFFSET(xtty, relocation);897LOG_OFFSET(xtty, consts);898LOG_OFFSET(xtty, insts);899LOG_OFFSET(xtty, stub);900LOG_OFFSET(xtty, scopes_data);901LOG_OFFSET(xtty, scopes_pcs);902LOG_OFFSET(xtty, dependencies);903LOG_OFFSET(xtty, handler_table);904LOG_OFFSET(xtty, nul_chk_table);905LOG_OFFSET(xtty, oops);906LOG_OFFSET(xtty, metadata);907908xtty->method(method());909xtty->stamp();910xtty->end_elem();911}912}913914#undef LOG_OFFSET915916917// Print out more verbose output usually for a newly created nmethod.918void nmethod::print_on(outputStream* st, const char* msg) const {919if (st != NULL) {920ttyLocker ttyl;921if (WizardMode) {922CompileTask::print(st, this, msg, /*short_form:*/ true);923st->print_cr(" (" INTPTR_FORMAT ")", p2i(this));924} else {925CompileTask::print(st, this, msg, /*short_form:*/ false);926}927}928}929930void nmethod::maybe_print_nmethod(DirectiveSet* directive) {931bool printnmethods = directive->PrintAssemblyOption || directive->PrintNMethodsOption;932if (printnmethods || PrintDebugInfo || PrintRelocations || PrintDependencies || PrintExceptionHandlers) {933print_nmethod(printnmethods);934}935}936937void nmethod::print_nmethod(bool printmethod) {938run_nmethod_entry_barrier(); // ensure all embedded OOPs are valid before printing939940ttyLocker ttyl; // keep the following output all in one block941if (xtty != NULL) {942xtty->begin_head("print_nmethod");943log_identity(xtty);944xtty->stamp();945xtty->end_head();946}947// Print the header part, then print the requested information.948// This is both handled in decode2().949if (printmethod) {950ResourceMark m;951if (is_compiled_by_c1()) {952tty->cr();953tty->print_cr("============================= C1-compiled nmethod ==============================");954}955if (is_compiled_by_jvmci()) {956tty->cr();957tty->print_cr("=========================== JVMCI-compiled nmethod =============================");958}959tty->print_cr("----------------------------------- Assembly -----------------------------------");960decode2(tty);961#if defined(SUPPORT_DATA_STRUCTS)962if (AbstractDisassembler::show_structs()) {963// Print the oops from the underlying CodeBlob as well.964tty->print_cr("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ");965print_oops(tty);966tty->print_cr("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ");967print_metadata(tty);968tty->print_cr("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ");969print_pcs();970tty->print_cr("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ");971if (oop_maps() != NULL) {972tty->print("oop maps:"); // oop_maps()->print_on(tty) outputs a cr() at the beginning973oop_maps()->print_on(tty);974tty->print_cr("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ");975}976}977#endif978} else {979print(); // print the header part only.980}981982#if defined(SUPPORT_DATA_STRUCTS)983if (AbstractDisassembler::show_structs()) {984methodHandle mh(Thread::current(), _method);985if (printmethod || PrintDebugInfo || CompilerOracle::has_option(mh, CompileCommand::PrintDebugInfo)) {986print_scopes();987tty->print_cr("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ");988}989if (printmethod || PrintRelocations || CompilerOracle::has_option(mh, CompileCommand::PrintRelocations)) {990print_relocations();991tty->print_cr("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ");992}993if (printmethod || PrintDependencies || CompilerOracle::has_option(mh, CompileCommand::PrintDependencies)) {994print_dependencies();995tty->print_cr("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ");996}997if (printmethod && native_invokers_begin() < native_invokers_end()) {998print_native_invokers();999tty->print_cr("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ");1000}1001if (printmethod || PrintExceptionHandlers) {1002print_handler_table();1003tty->print_cr("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ");1004print_nul_chk_table();1005tty->print_cr("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ");1006}10071008if (printmethod) {1009print_recorded_oops();1010tty->print_cr("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ");1011print_recorded_metadata();1012tty->print_cr("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ");1013}1014}1015#endif10161017if (xtty != NULL) {1018xtty->tail("print_nmethod");1019}1020}102110221023// Promote one word from an assembly-time handle to a live embedded oop.1024inline void nmethod::initialize_immediate_oop(oop* dest, jobject handle) {1025if (handle == NULL ||1026// As a special case, IC oops are initialized to 1 or -1.1027handle == (jobject) Universe::non_oop_word()) {1028*(void**)dest = handle;1029} else {1030*dest = JNIHandles::resolve_non_null(handle);1031}1032}103310341035// Have to have the same name because it's called by a template1036void nmethod::copy_values(GrowableArray<jobject>* array) {1037int length = array->length();1038assert((address)(oops_begin() + length) <= (address)oops_end(), "oops big enough");1039oop* dest = oops_begin();1040for (int index = 0 ; index < length; index++) {1041initialize_immediate_oop(&dest[index], array->at(index));1042}10431044// Now we can fix up all the oops in the code. We need to do this1045// in the code because the assembler uses jobjects as placeholders.1046// The code and relocations have already been initialized by the1047// CodeBlob constructor, so it is valid even at this early point to1048// iterate over relocations and patch the code.1049fix_oop_relocations(NULL, NULL, /*initialize_immediates=*/ true);1050}10511052void nmethod::copy_values(GrowableArray<Metadata*>* array) {1053int length = array->length();1054assert((address)(metadata_begin() + length) <= (address)metadata_end(), "big enough");1055Metadata** dest = metadata_begin();1056for (int index = 0 ; index < length; index++) {1057dest[index] = array->at(index);1058}1059}10601061void nmethod::free_native_invokers() {1062for (RuntimeStub** it = native_invokers_begin(); it < native_invokers_end(); it++) {1063CodeCache::free(*it);1064}1065}10661067void nmethod::fix_oop_relocations(address begin, address end, bool initialize_immediates) {1068// re-patch all oop-bearing instructions, just in case some oops moved1069RelocIterator iter(this, begin, end);1070while (iter.next()) {1071if (iter.type() == relocInfo::oop_type) {1072oop_Relocation* reloc = iter.oop_reloc();1073if (initialize_immediates && reloc->oop_is_immediate()) {1074oop* dest = reloc->oop_addr();1075initialize_immediate_oop(dest, cast_from_oop<jobject>(*dest));1076}1077// Refresh the oop-related bits of this instruction.1078reloc->fix_oop_relocation();1079} else if (iter.type() == relocInfo::metadata_type) {1080metadata_Relocation* reloc = iter.metadata_reloc();1081reloc->fix_metadata_relocation();1082}1083}1084}108510861087void nmethod::verify_clean_inline_caches() {1088assert(CompiledICLocker::is_safe(this), "mt unsafe call");10891090ResourceMark rm;1091RelocIterator iter(this, oops_reloc_begin());1092while(iter.next()) {1093switch(iter.type()) {1094case relocInfo::virtual_call_type:1095case relocInfo::opt_virtual_call_type: {1096CompiledIC *ic = CompiledIC_at(&iter);1097// Ok, to lookup references to zombies here1098CodeBlob *cb = CodeCache::find_blob_unsafe(ic->ic_destination());1099assert(cb != NULL, "destination not in CodeBlob?");1100nmethod* nm = cb->as_nmethod_or_null();1101if( nm != NULL ) {1102// Verify that inline caches pointing to both zombie and not_entrant methods are clean1103if (!nm->is_in_use() || (nm->method()->code() != nm)) {1104assert(ic->is_clean(), "IC should be clean");1105}1106}1107break;1108}1109case relocInfo::static_call_type: {1110CompiledStaticCall *csc = compiledStaticCall_at(iter.reloc());1111CodeBlob *cb = CodeCache::find_blob_unsafe(csc->destination());1112assert(cb != NULL, "destination not in CodeBlob?");1113nmethod* nm = cb->as_nmethod_or_null();1114if( nm != NULL ) {1115// Verify that inline caches pointing to both zombie and not_entrant methods are clean1116if (!nm->is_in_use() || (nm->method()->code() != nm)) {1117assert(csc->is_clean(), "IC should be clean");1118}1119}1120break;1121}1122default:1123break;1124}1125}1126}11271128// This is a private interface with the sweeper.1129void nmethod::mark_as_seen_on_stack() {1130assert(is_alive(), "Must be an alive method");1131// Set the traversal mark to ensure that the sweeper does 21132// cleaning passes before moving to zombie.1133set_stack_traversal_mark(NMethodSweeper::traversal_count());1134}11351136// Tell if a non-entrant method can be converted to a zombie (i.e.,1137// there are no activations on the stack, not in use by the VM,1138// and not in use by the ServiceThread)1139bool nmethod::can_convert_to_zombie() {1140// Note that this is called when the sweeper has observed the nmethod to be1141// not_entrant. However, with concurrent code cache unloading, the state1142// might have moved on to unloaded if it is_unloading(), due to racing1143// concurrent GC threads.1144assert(is_not_entrant() || is_unloading() ||1145!Thread::current()->is_Code_cache_sweeper_thread(),1146"must be a non-entrant method if called from sweeper");11471148// Since the nmethod sweeper only does partial sweep the sweeper's traversal1149// count can be greater than the stack traversal count before it hits the1150// nmethod for the second time.1151// If an is_unloading() nmethod is still not_entrant, then it is not safe to1152// convert it to zombie due to GC unloading interactions. However, if it1153// has become unloaded, then it is okay to convert such nmethods to zombie.1154return stack_traversal_mark() + 1 < NMethodSweeper::traversal_count() &&1155!is_locked_by_vm() && (!is_unloading() || is_unloaded());1156}11571158void nmethod::inc_decompile_count() {1159if (!is_compiled_by_c2() && !is_compiled_by_jvmci()) return;1160// Could be gated by ProfileTraps, but do not bother...1161Method* m = method();1162if (m == NULL) return;1163MethodData* mdo = m->method_data();1164if (mdo == NULL) return;1165// There is a benign race here. See comments in methodData.hpp.1166mdo->inc_decompile_count();1167}11681169bool nmethod::try_transition(int new_state_int) {1170signed char new_state = new_state_int;1171#ifdef ASSERT1172if (new_state != unloaded) {1173assert_lock_strong(CompiledMethod_lock);1174}1175#endif1176for (;;) {1177signed char old_state = Atomic::load(&_state);1178if (old_state >= new_state) {1179// Ensure monotonicity of transitions.1180return false;1181}1182if (Atomic::cmpxchg(&_state, old_state, new_state) == old_state) {1183return true;1184}1185}1186}11871188void nmethod::make_unloaded() {1189post_compiled_method_unload();11901191// This nmethod is being unloaded, make sure that dependencies1192// recorded in instanceKlasses get flushed.1193// Since this work is being done during a GC, defer deleting dependencies from the1194// InstanceKlass.1195assert(Universe::heap()->is_gc_active() || Thread::current()->is_ConcurrentGC_thread(),1196"should only be called during gc");1197flush_dependencies(/*delete_immediately*/false);11981199// Break cycle between nmethod & method1200LogTarget(Trace, class, unload, nmethod) lt;1201if (lt.is_enabled()) {1202LogStream ls(lt);1203ls.print("making nmethod " INTPTR_FORMAT1204" unloadable, Method*(" INTPTR_FORMAT1205") ",1206p2i(this), p2i(_method));1207ls.cr();1208}1209// Unlink the osr method, so we do not look this up again1210if (is_osr_method()) {1211// Invalidate the osr nmethod only once. Note that with concurrent1212// code cache unloading, OSR nmethods are invalidated before they1213// are made unloaded. Therefore, this becomes a no-op then.1214if (is_in_use()) {1215invalidate_osr_method();1216}1217#ifdef ASSERT1218if (method() != NULL) {1219// Make sure osr nmethod is invalidated, i.e. not on the list1220bool found = method()->method_holder()->remove_osr_nmethod(this);1221assert(!found, "osr nmethod should have been invalidated");1222}1223#endif1224}12251226// If _method is already NULL the Method* is about to be unloaded,1227// so we don't have to break the cycle. Note that it is possible to1228// have the Method* live here, in case we unload the nmethod because1229// it is pointing to some oop (other than the Method*) being unloaded.1230if (_method != NULL) {1231_method->unlink_code(this);1232}12331234// Make the class unloaded - i.e., change state and notify sweeper1235assert(SafepointSynchronize::is_at_safepoint() || Thread::current()->is_ConcurrentGC_thread(),1236"must be at safepoint");12371238{1239// Clear ICStubs and release any CompiledICHolders.1240CompiledICLocker ml(this);1241clear_ic_callsites();1242}12431244// Unregister must be done before the state change1245{1246MutexLocker ml(SafepointSynchronize::is_at_safepoint() ? NULL : CodeCache_lock,1247Mutex::_no_safepoint_check_flag);1248Universe::heap()->unregister_nmethod(this);1249}12501251// Clear the method of this dead nmethod1252set_method(NULL);12531254// Log the unloading.1255log_state_change();12561257// The Method* is gone at this point1258assert(_method == NULL, "Tautology");12591260set_osr_link(NULL);1261NMethodSweeper::report_state_change(this);12621263bool transition_success = try_transition(unloaded);12641265// It is an important invariant that there exists no race between1266// the sweeper and GC thread competing for making the same nmethod1267// zombie and unloaded respectively. This is ensured by1268// can_convert_to_zombie() returning false for any is_unloading()1269// nmethod, informing the sweeper not to step on any GC toes.1270assert(transition_success, "Invalid nmethod transition to unloaded");12711272#if INCLUDE_JVMCI1273// Clear the link between this nmethod and a HotSpotNmethod mirror1274JVMCINMethodData* nmethod_data = jvmci_nmethod_data();1275if (nmethod_data != NULL) {1276nmethod_data->invalidate_nmethod_mirror(this);1277}1278#endif1279}12801281void nmethod::invalidate_osr_method() {1282assert(_entry_bci != InvocationEntryBci, "wrong kind of nmethod");1283// Remove from list of active nmethods1284if (method() != NULL) {1285method()->method_holder()->remove_osr_nmethod(this);1286}1287}12881289void nmethod::log_state_change() const {1290if (LogCompilation) {1291if (xtty != NULL) {1292ttyLocker ttyl; // keep the following output all in one block1293if (_state == unloaded) {1294xtty->begin_elem("make_unloaded thread='" UINTX_FORMAT "'",1295os::current_thread_id());1296} else {1297xtty->begin_elem("make_not_entrant thread='" UINTX_FORMAT "'%s",1298os::current_thread_id(),1299(_state == zombie ? " zombie='1'" : ""));1300}1301log_identity(xtty);1302xtty->stamp();1303xtty->end_elem();1304}1305}13061307const char *state_msg = _state == zombie ? "made zombie" : "made not entrant";1308CompileTask::print_ul(this, state_msg);1309if (PrintCompilation && _state != unloaded) {1310print_on(tty, state_msg);1311}1312}13131314void nmethod::unlink_from_method() {1315if (method() != NULL) {1316method()->unlink_code(this);1317}1318}13191320/**1321* Common functionality for both make_not_entrant and make_zombie1322*/1323bool nmethod::make_not_entrant_or_zombie(int state) {1324assert(state == zombie || state == not_entrant, "must be zombie or not_entrant");13251326if (Atomic::load(&_state) >= state) {1327// Avoid taking the lock if already in required state.1328// This is safe from races because the state is an end-state,1329// which the nmethod cannot back out of once entered.1330// No need for fencing either.1331return false;1332}13331334// Make sure the nmethod is not flushed.1335nmethodLocker nml(this);1336// This can be called while the system is already at a safepoint which is ok1337NoSafepointVerifier nsv;13381339// during patching, depending on the nmethod state we must notify the GC that1340// code has been unloaded, unregistering it. We cannot do this right while1341// holding the CompiledMethod_lock because we need to use the CodeCache_lock. This1342// would be prone to deadlocks.1343// This flag is used to remember whether we need to later lock and unregister.1344bool nmethod_needs_unregister = false;13451346{1347// Enter critical section. Does not block for safepoint.1348MutexLocker ml(CompiledMethod_lock->owned_by_self() ? NULL : CompiledMethod_lock, Mutex::_no_safepoint_check_flag);13491350// This logic is equivalent to the logic below for patching the1351// verified entry point of regular methods. We check that the1352// nmethod is in use to ensure that it is invalidated only once.1353if (is_osr_method() && is_in_use()) {1354// this effectively makes the osr nmethod not entrant1355invalidate_osr_method();1356}13571358if (Atomic::load(&_state) >= state) {1359// another thread already performed this transition so nothing1360// to do, but return false to indicate this.1361return false;1362}13631364// The caller can be calling the method statically or through an inline1365// cache call.1366if (!is_osr_method() && !is_not_entrant()) {1367NativeJump::patch_verified_entry(entry_point(), verified_entry_point(),1368SharedRuntime::get_handle_wrong_method_stub());1369}13701371if (is_in_use() && update_recompile_counts()) {1372// It's a true state change, so mark the method as decompiled.1373// Do it only for transition from alive.1374inc_decompile_count();1375}13761377// If the state is becoming a zombie, signal to unregister the nmethod with1378// the heap.1379// This nmethod may have already been unloaded during a full GC.1380if ((state == zombie) && !is_unloaded()) {1381nmethod_needs_unregister = true;1382}13831384// Must happen before state change. Otherwise we have a race condition in1385// nmethod::can_convert_to_zombie(). I.e., a method can immediately1386// transition its state from 'not_entrant' to 'zombie' without having to wait1387// for stack scanning.1388if (state == not_entrant) {1389mark_as_seen_on_stack();1390OrderAccess::storestore(); // _stack_traversal_mark and _state1391}13921393// Change state1394if (!try_transition(state)) {1395// If the transition fails, it is due to another thread making the nmethod more1396// dead. In particular, one thread might be making the nmethod unloaded concurrently.1397// If so, having patched in the jump in the verified entry unnecessarily is fine.1398// The nmethod is no longer possible to call by Java threads.1399// Incrementing the decompile count is also fine as the caller of make_not_entrant()1400// had a valid reason to deoptimize the nmethod.1401// Marking the nmethod as seen on stack also has no effect, as the nmethod is now1402// !is_alive(), and the seen on stack value is only used to convert not_entrant1403// nmethods to zombie in can_convert_to_zombie().1404return false;1405}14061407// Log the transition once1408log_state_change();14091410// Remove nmethod from method.1411unlink_from_method();14121413} // leave critical region under CompiledMethod_lock14141415#if INCLUDE_JVMCI1416// Invalidate can't occur while holding the Patching lock1417JVMCINMethodData* nmethod_data = jvmci_nmethod_data();1418if (nmethod_data != NULL) {1419nmethod_data->invalidate_nmethod_mirror(this);1420}1421#endif14221423#ifdef ASSERT1424if (is_osr_method() && method() != NULL) {1425// Make sure osr nmethod is invalidated, i.e. not on the list1426bool found = method()->method_holder()->remove_osr_nmethod(this);1427assert(!found, "osr nmethod should have been invalidated");1428}1429#endif14301431// When the nmethod becomes zombie it is no longer alive so the1432// dependencies must be flushed. nmethods in the not_entrant1433// state will be flushed later when the transition to zombie1434// happens or they get unloaded.1435if (state == zombie) {1436{1437// Flushing dependencies must be done before any possible1438// safepoint can sneak in, otherwise the oops used by the1439// dependency logic could have become stale.1440MutexLocker mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);1441if (nmethod_needs_unregister) {1442Universe::heap()->unregister_nmethod(this);1443}1444flush_dependencies(/*delete_immediately*/true);1445}14461447#if INCLUDE_JVMCI1448// Now that the nmethod has been unregistered, it's1449// safe to clear the HotSpotNmethod mirror oop.1450if (nmethod_data != NULL) {1451nmethod_data->clear_nmethod_mirror(this);1452}1453#endif14541455// Clear ICStubs to prevent back patching stubs of zombie or flushed1456// nmethods during the next safepoint (see ICStub::finalize), as well1457// as to free up CompiledICHolder resources.1458{1459CompiledICLocker ml(this);1460clear_ic_callsites();1461}14621463// zombie only - if a JVMTI agent has enabled the CompiledMethodUnload1464// event and it hasn't already been reported for this nmethod then1465// report it now. The event may have been reported earlier if the GC1466// marked it for unloading). JvmtiDeferredEventQueue support means1467// we no longer go to a safepoint here.1468post_compiled_method_unload();14691470#ifdef ASSERT1471// It's no longer safe to access the oops section since zombie1472// nmethods aren't scanned for GC.1473_oops_are_stale = true;1474#endif1475// the Method may be reclaimed by class unloading now that the1476// nmethod is in zombie state1477set_method(NULL);1478} else {1479assert(state == not_entrant, "other cases may need to be handled differently");1480}14811482if (TraceCreateZombies && state == zombie) {1483ResourceMark m;1484tty->print_cr("nmethod <" INTPTR_FORMAT "> %s code made %s", p2i(this), this->method() ? this->method()->name_and_sig_as_C_string() : "null", (state == not_entrant) ? "not entrant" : "zombie");1485}14861487NMethodSweeper::report_state_change(this);1488return true;1489}14901491void nmethod::flush() {1492MutexLocker mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);1493// Note that there are no valid oops in the nmethod anymore.1494assert(!is_osr_method() || is_unloaded() || is_zombie(),1495"osr nmethod must be unloaded or zombie before flushing");1496assert(is_zombie() || is_osr_method(), "must be a zombie method");1497assert (!is_locked_by_vm(), "locked methods shouldn't be flushed");1498assert_locked_or_safepoint(CodeCache_lock);14991500// completely deallocate this method1501Events::log(JavaThread::current(), "flushing nmethod " INTPTR_FORMAT, p2i(this));1502if (PrintMethodFlushing) {1503tty->print_cr("*flushing %s nmethod %3d/" INTPTR_FORMAT ". Live blobs:" UINT32_FORMAT1504"/Free CodeCache:" SIZE_FORMAT "Kb",1505is_osr_method() ? "osr" : "",_compile_id, p2i(this), CodeCache::blob_count(),1506CodeCache::unallocated_capacity(CodeCache::get_code_blob_type(this))/1024);1507}15081509// We need to deallocate any ExceptionCache data.1510// Note that we do not need to grab the nmethod lock for this, it1511// better be thread safe if we're disposing of it!1512ExceptionCache* ec = exception_cache();1513set_exception_cache(NULL);1514while(ec != NULL) {1515ExceptionCache* next = ec->next();1516delete ec;1517ec = next;1518}15191520Universe::heap()->flush_nmethod(this);1521CodeCache::unregister_old_nmethod(this);15221523CodeBlob::flush();1524CodeCache::free(this);1525}15261527oop nmethod::oop_at(int index) const {1528if (index == 0) {1529return NULL;1530}1531return NativeAccess<AS_NO_KEEPALIVE>::oop_load(oop_addr_at(index));1532}15331534oop nmethod::oop_at_phantom(int index) const {1535if (index == 0) {1536return NULL;1537}1538return NativeAccess<ON_PHANTOM_OOP_REF>::oop_load(oop_addr_at(index));1539}15401541//1542// Notify all classes this nmethod is dependent on that it is no1543// longer dependent. This should only be called in two situations.1544// First, when a nmethod transitions to a zombie all dependents need1545// to be clear. Since zombification happens at a safepoint there's no1546// synchronization issues. The second place is a little more tricky.1547// During phase 1 of mark sweep class unloading may happen and as a1548// result some nmethods may get unloaded. In this case the flushing1549// of dependencies must happen during phase 1 since after GC any1550// dependencies in the unloaded nmethod won't be updated, so1551// traversing the dependency information in unsafe. In that case this1552// function is called with a boolean argument and this function only1553// notifies instanceKlasses that are reachable15541555void nmethod::flush_dependencies(bool delete_immediately) {1556DEBUG_ONLY(bool called_by_gc = Universe::heap()->is_gc_active() || Thread::current()->is_ConcurrentGC_thread();)1557assert(called_by_gc != delete_immediately,1558"delete_immediately is false if and only if we are called during GC");1559if (!has_flushed_dependencies()) {1560set_has_flushed_dependencies();1561for (Dependencies::DepStream deps(this); deps.next(); ) {1562if (deps.type() == Dependencies::call_site_target_value) {1563// CallSite dependencies are managed on per-CallSite instance basis.1564oop call_site = deps.argument_oop(0);1565if (delete_immediately) {1566assert_locked_or_safepoint(CodeCache_lock);1567MethodHandles::remove_dependent_nmethod(call_site, this);1568} else {1569MethodHandles::clean_dependency_context(call_site);1570}1571} else {1572Klass* klass = deps.context_type();1573if (klass == NULL) {1574continue; // ignore things like evol_method1575}1576// During GC delete_immediately is false, and liveness1577// of dependee determines class that needs to be updated.1578if (delete_immediately) {1579assert_locked_or_safepoint(CodeCache_lock);1580InstanceKlass::cast(klass)->remove_dependent_nmethod(this);1581} else if (klass->is_loader_alive()) {1582// The GC may clean dependency contexts concurrently and in parallel.1583InstanceKlass::cast(klass)->clean_dependency_context();1584}1585}1586}1587}1588}15891590// ------------------------------------------------------------------1591// post_compiled_method_load_event1592// new method for install_code() path1593// Transfer information from compilation to jvmti1594void nmethod::post_compiled_method_load_event(JvmtiThreadState* state) {15951596// Don't post this nmethod load event if it is already dying1597// because the sweeper might already be deleting this nmethod.1598{1599MutexLocker ml(CompiledMethod_lock, Mutex::_no_safepoint_check_flag);1600// When the nmethod is acquired from the CodeCache iterator, it can racingly become zombie1601// before this code is called. Filter them out here under the CompiledMethod_lock.1602if (!is_alive()) {1603return;1604}1605// As for is_alive() nmethods, we also don't want them to racingly become zombie once we1606// release this lock, so we check that this is not going to be the case.1607if (is_not_entrant() && can_convert_to_zombie()) {1608return;1609}1610}16111612// This is a bad time for a safepoint. We don't want1613// this nmethod to get unloaded while we're queueing the event.1614NoSafepointVerifier nsv;16151616Method* m = method();1617HOTSPOT_COMPILED_METHOD_LOAD(1618(char *) m->klass_name()->bytes(),1619m->klass_name()->utf8_length(),1620(char *) m->name()->bytes(),1621m->name()->utf8_length(),1622(char *) m->signature()->bytes(),1623m->signature()->utf8_length(),1624insts_begin(), insts_size());162516261627if (JvmtiExport::should_post_compiled_method_load()) {1628// Only post unload events if load events are found.1629set_load_reported();1630// If a JavaThread hasn't been passed in, let the Service thread1631// (which is a real Java thread) post the event1632JvmtiDeferredEvent event = JvmtiDeferredEvent::compiled_method_load_event(this);1633if (state == NULL) {1634// Execute any barrier code for this nmethod as if it's called, since1635// keeping it alive looks like stack walking.1636run_nmethod_entry_barrier();1637ServiceThread::enqueue_deferred_event(&event);1638} else {1639// This enters the nmethod barrier outside in the caller.1640state->enqueue_event(&event);1641}1642}1643}16441645void nmethod::post_compiled_method_unload() {1646if (unload_reported()) {1647// During unloading we transition to unloaded and then to zombie1648// and the unloading is reported during the first transition.1649return;1650}16511652assert(_method != NULL && !is_unloaded(), "just checking");1653DTRACE_METHOD_UNLOAD_PROBE(method());16541655// If a JVMTI agent has enabled the CompiledMethodUnload event then1656// post the event. Sometime later this nmethod will be made a zombie1657// by the sweeper but the Method* will not be valid at that point.1658// The jmethodID is a weak reference to the Method* so if1659// it's being unloaded there's no way to look it up since the weak1660// ref will have been cleared.16611662// Don't bother posting the unload if the load event wasn't posted.1663if (load_reported() && JvmtiExport::should_post_compiled_method_unload()) {1664assert(!unload_reported(), "already unloaded");1665JvmtiDeferredEvent event =1666JvmtiDeferredEvent::compiled_method_unload_event(1667method()->jmethod_id(), insts_begin());1668ServiceThread::enqueue_deferred_event(&event);1669}16701671// The JVMTI CompiledMethodUnload event can be enabled or disabled at1672// any time. As the nmethod is being unloaded now we mark it has1673// having the unload event reported - this will ensure that we don't1674// attempt to report the event in the unlikely scenario where the1675// event is enabled at the time the nmethod is made a zombie.1676set_unload_reported();1677}16781679// Iterate over metadata calling this function. Used by RedefineClasses1680void nmethod::metadata_do(MetadataClosure* f) {1681{1682// Visit all immediate references that are embedded in the instruction stream.1683RelocIterator iter(this, oops_reloc_begin());1684while (iter.next()) {1685if (iter.type() == relocInfo::metadata_type) {1686metadata_Relocation* r = iter.metadata_reloc();1687// In this metadata, we must only follow those metadatas directly embedded in1688// the code. Other metadatas (oop_index>0) are seen as part of1689// the metadata section below.1690assert(1 == (r->metadata_is_immediate()) +1691(r->metadata_addr() >= metadata_begin() && r->metadata_addr() < metadata_end()),1692"metadata must be found in exactly one place");1693if (r->metadata_is_immediate() && r->metadata_value() != NULL) {1694Metadata* md = r->metadata_value();1695if (md != _method) f->do_metadata(md);1696}1697} else if (iter.type() == relocInfo::virtual_call_type) {1698// Check compiledIC holders associated with this nmethod1699ResourceMark rm;1700CompiledIC *ic = CompiledIC_at(&iter);1701if (ic->is_icholder_call()) {1702CompiledICHolder* cichk = ic->cached_icholder();1703f->do_metadata(cichk->holder_metadata());1704f->do_metadata(cichk->holder_klass());1705} else {1706Metadata* ic_oop = ic->cached_metadata();1707if (ic_oop != NULL) {1708f->do_metadata(ic_oop);1709}1710}1711}1712}1713}17141715// Visit the metadata section1716for (Metadata** p = metadata_begin(); p < metadata_end(); p++) {1717if (*p == Universe::non_oop_word() || *p == NULL) continue; // skip non-oops1718Metadata* md = *p;1719f->do_metadata(md);1720}17211722// Visit metadata not embedded in the other places.1723if (_method != NULL) f->do_metadata(_method);1724}17251726// The _is_unloading_state encodes a tuple comprising the unloading cycle1727// and the result of IsUnloadingBehaviour::is_unloading() fpr that cycle.1728// This is the bit layout of the _is_unloading_state byte: 00000CCU1729// CC refers to the cycle, which has 2 bits, and U refers to the result of1730// IsUnloadingBehaviour::is_unloading() for that unloading cycle.17311732class IsUnloadingState: public AllStatic {1733static const uint8_t _is_unloading_mask = 1;1734static const uint8_t _is_unloading_shift = 0;1735static const uint8_t _unloading_cycle_mask = 6;1736static const uint8_t _unloading_cycle_shift = 1;17371738static uint8_t set_is_unloading(uint8_t state, bool value) {1739state &= ~_is_unloading_mask;1740if (value) {1741state |= 1 << _is_unloading_shift;1742}1743assert(is_unloading(state) == value, "unexpected unloading cycle overflow");1744return state;1745}17461747static uint8_t set_unloading_cycle(uint8_t state, uint8_t value) {1748state &= ~_unloading_cycle_mask;1749state |= value << _unloading_cycle_shift;1750assert(unloading_cycle(state) == value, "unexpected unloading cycle overflow");1751return state;1752}17531754public:1755static bool is_unloading(uint8_t state) { return (state & _is_unloading_mask) >> _is_unloading_shift == 1; }1756static uint8_t unloading_cycle(uint8_t state) { return (state & _unloading_cycle_mask) >> _unloading_cycle_shift; }17571758static uint8_t create(bool is_unloading, uint8_t unloading_cycle) {1759uint8_t state = 0;1760state = set_is_unloading(state, is_unloading);1761state = set_unloading_cycle(state, unloading_cycle);1762return state;1763}1764};17651766bool nmethod::is_unloading() {1767uint8_t state = RawAccess<MO_RELAXED>::load(&_is_unloading_state);1768bool state_is_unloading = IsUnloadingState::is_unloading(state);1769if (state_is_unloading) {1770return true;1771}1772uint8_t state_unloading_cycle = IsUnloadingState::unloading_cycle(state);1773uint8_t current_cycle = CodeCache::unloading_cycle();1774if (state_unloading_cycle == current_cycle) {1775return false;1776}17771778// The IsUnloadingBehaviour is responsible for checking if there are any dead1779// oops in the CompiledMethod, by calling oops_do on it.1780state_unloading_cycle = current_cycle;17811782if (is_zombie()) {1783// Zombies without calculated unloading epoch are never unloading due to GC.17841785// There are no races where a previously observed is_unloading() nmethod1786// suddenly becomes not is_unloading() due to here being observed as zombie.17871788// With STW unloading, all is_alive() && is_unloading() nmethods are unlinked1789// and unloaded in the safepoint. That makes races where an nmethod is first1790// observed as is_alive() && is_unloading() and subsequently observed as1791// is_zombie() impossible.17921793// With concurrent unloading, all references to is_unloading() nmethods are1794// first unlinked (e.g. IC caches and dependency contexts). Then a global1795// handshake operation is performed with all JavaThreads before finally1796// unloading the nmethods. The sweeper never converts is_alive() && is_unloading()1797// nmethods to zombies; it waits for them to become is_unloaded(). So before1798// the global handshake, it is impossible for is_unloading() nmethods to1799// racingly become is_zombie(). And is_unloading() is calculated for all is_alive()1800// nmethods before taking that global handshake, meaning that it will never1801// be recalculated after the handshake.18021803// After that global handshake, is_unloading() nmethods are only observable1804// to the iterators, and they will never trigger recomputation of the cached1805// is_unloading_state, and hence may not suffer from such races.18061807state_is_unloading = false;1808} else {1809state_is_unloading = IsUnloadingBehaviour::current()->is_unloading(this);1810}18111812state = IsUnloadingState::create(state_is_unloading, state_unloading_cycle);18131814RawAccess<MO_RELAXED>::store(&_is_unloading_state, state);18151816return state_is_unloading;1817}18181819void nmethod::clear_unloading_state() {1820uint8_t state = IsUnloadingState::create(false, CodeCache::unloading_cycle());1821RawAccess<MO_RELAXED>::store(&_is_unloading_state, state);1822}182318241825// This is called at the end of the strong tracing/marking phase of a1826// GC to unload an nmethod if it contains otherwise unreachable1827// oops.18281829void nmethod::do_unloading(bool unloading_occurred) {1830// Make sure the oop's ready to receive visitors1831assert(!is_zombie() && !is_unloaded(),1832"should not call follow on zombie or unloaded nmethod");18331834if (is_unloading()) {1835make_unloaded();1836} else {1837guarantee(unload_nmethod_caches(unloading_occurred),1838"Should not need transition stubs");1839}1840}18411842void nmethod::oops_do(OopClosure* f, bool allow_dead) {1843// make sure the oops ready to receive visitors1844assert(allow_dead || is_alive(), "should not call follow on dead nmethod");18451846// Prevent extra code cache walk for platforms that don't have immediate oops.1847if (relocInfo::mustIterateImmediateOopsInCode()) {1848RelocIterator iter(this, oops_reloc_begin());18491850while (iter.next()) {1851if (iter.type() == relocInfo::oop_type ) {1852oop_Relocation* r = iter.oop_reloc();1853// In this loop, we must only follow those oops directly embedded in1854// the code. Other oops (oop_index>0) are seen as part of scopes_oops.1855assert(1 == (r->oop_is_immediate()) +1856(r->oop_addr() >= oops_begin() && r->oop_addr() < oops_end()),1857"oop must be found in exactly one place");1858if (r->oop_is_immediate() && r->oop_value() != NULL) {1859f->do_oop(r->oop_addr());1860}1861}1862}1863}18641865// Scopes1866// This includes oop constants not inlined in the code stream.1867for (oop* p = oops_begin(); p < oops_end(); p++) {1868if (*p == Universe::non_oop_word()) continue; // skip non-oops1869f->do_oop(p);1870}1871}18721873nmethod* volatile nmethod::_oops_do_mark_nmethods;18741875void nmethod::oops_do_log_change(const char* state) {1876LogTarget(Trace, gc, nmethod) lt;1877if (lt.is_enabled()) {1878LogStream ls(lt);1879CompileTask::print(&ls, this, state, true /* short_form */);1880}1881}18821883bool nmethod::oops_do_try_claim() {1884if (oops_do_try_claim_weak_request()) {1885nmethod* result = oops_do_try_add_to_list_as_weak_done();1886assert(result == NULL, "adding to global list as weak done must always succeed.");1887return true;1888}1889return false;1890}18911892bool nmethod::oops_do_try_claim_weak_request() {1893assert(SafepointSynchronize::is_at_safepoint(), "only at safepoint");18941895if ((_oops_do_mark_link == NULL) &&1896(Atomic::replace_if_null(&_oops_do_mark_link, mark_link(this, claim_weak_request_tag)))) {1897oops_do_log_change("oops_do, mark weak request");1898return true;1899}1900return false;1901}19021903void nmethod::oops_do_set_strong_done(nmethod* old_head) {1904_oops_do_mark_link = mark_link(old_head, claim_strong_done_tag);1905}19061907nmethod::oops_do_mark_link* nmethod::oops_do_try_claim_strong_done() {1908assert(SafepointSynchronize::is_at_safepoint(), "only at safepoint");19091910oops_do_mark_link* old_next = Atomic::cmpxchg(&_oops_do_mark_link, mark_link(NULL, claim_weak_request_tag), mark_link(this, claim_strong_done_tag));1911if (old_next == NULL) {1912oops_do_log_change("oops_do, mark strong done");1913}1914return old_next;1915}19161917nmethod::oops_do_mark_link* nmethod::oops_do_try_add_strong_request(nmethod::oops_do_mark_link* next) {1918assert(SafepointSynchronize::is_at_safepoint(), "only at safepoint");1919assert(next == mark_link(this, claim_weak_request_tag), "Should be claimed as weak");19201921oops_do_mark_link* old_next = Atomic::cmpxchg(&_oops_do_mark_link, next, mark_link(this, claim_strong_request_tag));1922if (old_next == next) {1923oops_do_log_change("oops_do, mark strong request");1924}1925return old_next;1926}19271928bool nmethod::oops_do_try_claim_weak_done_as_strong_done(nmethod::oops_do_mark_link* next) {1929assert(SafepointSynchronize::is_at_safepoint(), "only at safepoint");1930assert(extract_state(next) == claim_weak_done_tag, "Should be claimed as weak done");19311932oops_do_mark_link* old_next = Atomic::cmpxchg(&_oops_do_mark_link, next, mark_link(extract_nmethod(next), claim_strong_done_tag));1933if (old_next == next) {1934oops_do_log_change("oops_do, mark weak done -> mark strong done");1935return true;1936}1937return false;1938}19391940nmethod* nmethod::oops_do_try_add_to_list_as_weak_done() {1941assert(SafepointSynchronize::is_at_safepoint(), "only at safepoint");19421943assert(extract_state(_oops_do_mark_link) == claim_weak_request_tag ||1944extract_state(_oops_do_mark_link) == claim_strong_request_tag,1945"must be but is nmethod " PTR_FORMAT " %u", p2i(extract_nmethod(_oops_do_mark_link)), extract_state(_oops_do_mark_link));19461947nmethod* old_head = Atomic::xchg(&_oops_do_mark_nmethods, this);1948// Self-loop if needed.1949if (old_head == NULL) {1950old_head = this;1951}1952// Try to install end of list and weak done tag.1953if (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)) {1954oops_do_log_change("oops_do, mark weak done");1955return NULL;1956} else {1957return old_head;1958}1959}19601961void nmethod::oops_do_add_to_list_as_strong_done() {1962assert(SafepointSynchronize::is_at_safepoint(), "only at safepoint");19631964nmethod* old_head = Atomic::xchg(&_oops_do_mark_nmethods, this);1965// Self-loop if needed.1966if (old_head == NULL) {1967old_head = this;1968}1969assert(_oops_do_mark_link == mark_link(this, claim_strong_done_tag), "must be but is nmethod " PTR_FORMAT " state %u",1970p2i(extract_nmethod(_oops_do_mark_link)), extract_state(_oops_do_mark_link));19711972oops_do_set_strong_done(old_head);1973}19741975void nmethod::oops_do_process_weak(OopsDoProcessor* p) {1976if (!oops_do_try_claim_weak_request()) {1977// Failed to claim for weak processing.1978oops_do_log_change("oops_do, mark weak request fail");1979return;1980}19811982p->do_regular_processing(this);19831984nmethod* old_head = oops_do_try_add_to_list_as_weak_done();1985if (old_head == NULL) {1986return;1987}1988oops_do_log_change("oops_do, mark weak done fail");1989// Adding to global list failed, another thread added a strong request.1990assert(extract_state(_oops_do_mark_link) == claim_strong_request_tag,1991"must be but is %u", extract_state(_oops_do_mark_link));19921993oops_do_log_change("oops_do, mark weak request -> mark strong done");19941995oops_do_set_strong_done(old_head);1996// Do missing strong processing.1997p->do_remaining_strong_processing(this);1998}19992000void nmethod::oops_do_process_strong(OopsDoProcessor* p) {2001oops_do_mark_link* next_raw = oops_do_try_claim_strong_done();2002if (next_raw == NULL) {2003p->do_regular_processing(this);2004oops_do_add_to_list_as_strong_done();2005return;2006}2007// Claim failed. Figure out why and handle it.2008if (oops_do_has_weak_request(next_raw)) {2009oops_do_mark_link* old = next_raw;2010// Claim failed because being weak processed (state == "weak request").2011// Try to request deferred strong processing.2012next_raw = oops_do_try_add_strong_request(old);2013if (next_raw == old) {2014// Successfully requested deferred strong processing.2015return;2016}2017// Failed because of a concurrent transition. No longer in "weak request" state.2018}2019if (oops_do_has_any_strong_state(next_raw)) {2020// Already claimed for strong processing or requested for such.2021return;2022}2023if (oops_do_try_claim_weak_done_as_strong_done(next_raw)) {2024// Successfully claimed "weak done" as "strong done". Do the missing marking.2025p->do_remaining_strong_processing(this);2026return;2027}2028// Claim failed, some other thread got it.2029}20302031void nmethod::oops_do_marking_prologue() {2032assert_at_safepoint();20332034log_trace(gc, nmethod)("oops_do_marking_prologue");2035assert(_oops_do_mark_nmethods == NULL, "must be empty");2036}20372038void nmethod::oops_do_marking_epilogue() {2039assert_at_safepoint();20402041nmethod* next = _oops_do_mark_nmethods;2042_oops_do_mark_nmethods = NULL;2043if (next != NULL) {2044nmethod* cur;2045do {2046cur = next;2047next = extract_nmethod(cur->_oops_do_mark_link);2048cur->_oops_do_mark_link = NULL;2049DEBUG_ONLY(cur->verify_oop_relocations());20502051LogTarget(Trace, gc, nmethod) lt;2052if (lt.is_enabled()) {2053LogStream ls(lt);2054CompileTask::print(&ls, cur, "oops_do, unmark", /*short_form:*/ true);2055}2056// End if self-loop has been detected.2057} while (cur != next);2058}2059log_trace(gc, nmethod)("oops_do_marking_epilogue");2060}20612062inline bool includes(void* p, void* from, void* to) {2063return from <= p && p < to;2064}206520662067void nmethod::copy_scopes_pcs(PcDesc* pcs, int count) {2068assert(count >= 2, "must be sentinel values, at least");20692070#ifdef ASSERT2071// must be sorted and unique; we do a binary search in find_pc_desc()2072int prev_offset = pcs[0].pc_offset();2073assert(prev_offset == PcDesc::lower_offset_limit,2074"must start with a sentinel");2075for (int i = 1; i < count; i++) {2076int this_offset = pcs[i].pc_offset();2077assert(this_offset > prev_offset, "offsets must be sorted");2078prev_offset = this_offset;2079}2080assert(prev_offset == PcDesc::upper_offset_limit,2081"must end with a sentinel");2082#endif //ASSERT20832084// Search for MethodHandle invokes and tag the nmethod.2085for (int i = 0; i < count; i++) {2086if (pcs[i].is_method_handle_invoke()) {2087set_has_method_handle_invokes(true);2088break;2089}2090}2091assert(has_method_handle_invokes() == (_deopt_mh_handler_begin != NULL), "must have deopt mh handler");20922093int size = count * sizeof(PcDesc);2094assert(scopes_pcs_size() >= size, "oob");2095memcpy(scopes_pcs_begin(), pcs, size);20962097// Adjust the final sentinel downward.2098PcDesc* last_pc = &scopes_pcs_begin()[count-1];2099assert(last_pc->pc_offset() == PcDesc::upper_offset_limit, "sanity");2100last_pc->set_pc_offset(content_size() + 1);2101for (; last_pc + 1 < scopes_pcs_end(); last_pc += 1) {2102// Fill any rounding gaps with copies of the last record.2103last_pc[1] = last_pc[0];2104}2105// The following assert could fail if sizeof(PcDesc) is not2106// an integral multiple of oopSize (the rounding term).2107// If it fails, change the logic to always allocate a multiple2108// of sizeof(PcDesc), and fill unused words with copies of *last_pc.2109assert(last_pc + 1 == scopes_pcs_end(), "must match exactly");2110}21112112void nmethod::copy_scopes_data(u_char* buffer, int size) {2113assert(scopes_data_size() >= size, "oob");2114memcpy(scopes_data_begin(), buffer, size);2115}21162117#ifdef ASSERT2118static PcDesc* linear_search(const PcDescSearch& search, int pc_offset, bool approximate) {2119PcDesc* lower = search.scopes_pcs_begin();2120PcDesc* upper = search.scopes_pcs_end();2121lower += 1; // exclude initial sentinel2122PcDesc* res = NULL;2123for (PcDesc* p = lower; p < upper; p++) {2124NOT_PRODUCT(--pc_nmethod_stats.pc_desc_tests); // don't count this call to match_desc2125if (match_desc(p, pc_offset, approximate)) {2126if (res == NULL)2127res = p;2128else2129res = (PcDesc*) badAddress;2130}2131}2132return res;2133}2134#endif213521362137// Finds a PcDesc with real-pc equal to "pc"2138PcDesc* PcDescContainer::find_pc_desc_internal(address pc, bool approximate, const PcDescSearch& search) {2139address base_address = search.code_begin();2140if ((pc < base_address) ||2141(pc - base_address) >= (ptrdiff_t) PcDesc::upper_offset_limit) {2142return NULL; // PC is wildly out of range2143}2144int pc_offset = (int) (pc - base_address);21452146// Check the PcDesc cache if it contains the desired PcDesc2147// (This as an almost 100% hit rate.)2148PcDesc* res = _pc_desc_cache.find_pc_desc(pc_offset, approximate);2149if (res != NULL) {2150assert(res == linear_search(search, pc_offset, approximate), "cache ok");2151return res;2152}21532154// Fallback algorithm: quasi-linear search for the PcDesc2155// Find the last pc_offset less than the given offset.2156// The successor must be the required match, if there is a match at all.2157// (Use a fixed radix to avoid expensive affine pointer arithmetic.)2158PcDesc* lower = search.scopes_pcs_begin();2159PcDesc* upper = search.scopes_pcs_end();2160upper -= 1; // exclude final sentinel2161if (lower >= upper) return NULL; // native method; no PcDescs at all21622163#define assert_LU_OK \2164/* invariant on lower..upper during the following search: */ \2165assert(lower->pc_offset() < pc_offset, "sanity"); \2166assert(upper->pc_offset() >= pc_offset, "sanity")2167assert_LU_OK;21682169// Use the last successful return as a split point.2170PcDesc* mid = _pc_desc_cache.last_pc_desc();2171NOT_PRODUCT(++pc_nmethod_stats.pc_desc_searches);2172if (mid->pc_offset() < pc_offset) {2173lower = mid;2174} else {2175upper = mid;2176}21772178// Take giant steps at first (4096, then 256, then 16, then 1)2179const int LOG2_RADIX = 4 /*smaller steps in debug mode:*/ debug_only(-1);2180const int RADIX = (1 << LOG2_RADIX);2181for (int step = (1 << (LOG2_RADIX*3)); step > 1; step >>= LOG2_RADIX) {2182while ((mid = lower + step) < upper) {2183assert_LU_OK;2184NOT_PRODUCT(++pc_nmethod_stats.pc_desc_searches);2185if (mid->pc_offset() < pc_offset) {2186lower = mid;2187} else {2188upper = mid;2189break;2190}2191}2192assert_LU_OK;2193}21942195// Sneak up on the value with a linear search of length ~16.2196while (true) {2197assert_LU_OK;2198mid = lower + 1;2199NOT_PRODUCT(++pc_nmethod_stats.pc_desc_searches);2200if (mid->pc_offset() < pc_offset) {2201lower = mid;2202} else {2203upper = mid;2204break;2205}2206}2207#undef assert_LU_OK22082209if (match_desc(upper, pc_offset, approximate)) {2210assert(upper == linear_search(search, pc_offset, approximate), "search ok");2211_pc_desc_cache.add_pc_desc(upper);2212return upper;2213} else {2214assert(NULL == linear_search(search, pc_offset, approximate), "search ok");2215return NULL;2216}2217}221822192220void nmethod::check_all_dependencies(DepChange& changes) {2221// Checked dependencies are allocated into this ResourceMark2222ResourceMark rm;22232224// Turn off dependency tracing while actually testing dependencies.2225NOT_PRODUCT( FlagSetting fs(TraceDependencies, false) );22262227typedef ResourceHashtable<DependencySignature, int, &DependencySignature::hash,2228&DependencySignature::equals, 11027> DepTable;22292230DepTable* table = new DepTable();22312232// Iterate over live nmethods and check dependencies of all nmethods that are not2233// marked for deoptimization. A particular dependency is only checked once.2234NMethodIterator iter(NMethodIterator::only_alive_and_not_unloading);2235while(iter.next()) {2236nmethod* nm = iter.method();2237// Only notify for live nmethods2238if (!nm->is_marked_for_deoptimization()) {2239for (Dependencies::DepStream deps(nm); deps.next(); ) {2240// Construct abstraction of a dependency.2241DependencySignature* current_sig = new DependencySignature(deps);22422243// Determine if dependency is already checked. table->put(...) returns2244// 'true' if the dependency is added (i.e., was not in the hashtable).2245if (table->put(*current_sig, 1)) {2246if (deps.check_dependency() != NULL) {2247// Dependency checking failed. Print out information about the failed2248// dependency and finally fail with an assert. We can fail here, since2249// dependency checking is never done in a product build.2250tty->print_cr("Failed dependency:");2251changes.print();2252nm->print();2253nm->print_dependencies();2254assert(false, "Should have been marked for deoptimization");2255}2256}2257}2258}2259}2260}22612262bool nmethod::check_dependency_on(DepChange& changes) {2263// What has happened:2264// 1) a new class dependee has been added2265// 2) dependee and all its super classes have been marked2266bool found_check = false; // set true if we are upset2267for (Dependencies::DepStream deps(this); deps.next(); ) {2268// Evaluate only relevant dependencies.2269if (deps.spot_check_dependency_at(changes) != NULL) {2270found_check = true;2271NOT_DEBUG(break);2272}2273}2274return found_check;2275}22762277// Called from mark_for_deoptimization, when dependee is invalidated.2278bool nmethod::is_dependent_on_method(Method* dependee) {2279for (Dependencies::DepStream deps(this); deps.next(); ) {2280if (deps.type() != Dependencies::evol_method)2281continue;2282Method* method = deps.method_argument(0);2283if (method == dependee) return true;2284}2285return false;2286}228722882289bool nmethod::is_patchable_at(address instr_addr) {2290assert(insts_contains(instr_addr), "wrong nmethod used");2291if (is_zombie()) {2292// a zombie may never be patched2293return false;2294}2295return true;2296}229722982299void nmethod_init() {2300// make sure you didn't forget to adjust the filler fields2301assert(sizeof(nmethod) % oopSize == 0, "nmethod size must be multiple of a word");2302}230323042305//-------------------------------------------------------------------------------------------230623072308// QQQ might we make this work from a frame??2309nmethodLocker::nmethodLocker(address pc) {2310CodeBlob* cb = CodeCache::find_blob(pc);2311guarantee(cb != NULL && cb->is_compiled(), "bad pc for a nmethod found");2312_nm = cb->as_compiled_method();2313lock_nmethod(_nm);2314}23152316// Only JvmtiDeferredEvent::compiled_method_unload_event()2317// should pass zombie_ok == true.2318void nmethodLocker::lock_nmethod(CompiledMethod* cm, bool zombie_ok) {2319if (cm == NULL) return;2320nmethod* nm = cm->as_nmethod();2321Atomic::inc(&nm->_lock_count);2322assert(zombie_ok || !nm->is_zombie(), "cannot lock a zombie method: %p", nm);2323}23242325void nmethodLocker::unlock_nmethod(CompiledMethod* cm) {2326if (cm == NULL) return;2327nmethod* nm = cm->as_nmethod();2328Atomic::dec(&nm->_lock_count);2329assert(nm->_lock_count >= 0, "unmatched nmethod lock/unlock");2330}233123322333// -----------------------------------------------------------------------------2334// Verification23352336class VerifyOopsClosure: public OopClosure {2337nmethod* _nm;2338bool _ok;2339public:2340VerifyOopsClosure(nmethod* nm) : _nm(nm), _ok(true) { }2341bool ok() { return _ok; }2342virtual void do_oop(oop* p) {2343if (oopDesc::is_oop_or_null(*p)) return;2344// Print diagnostic information before calling print_nmethod().2345// Assertions therein might prevent call from returning.2346tty->print_cr("*** non-oop " PTR_FORMAT " found at " PTR_FORMAT " (offset %d)",2347p2i(*p), p2i(p), (int)((intptr_t)p - (intptr_t)_nm));2348if (_ok) {2349_nm->print_nmethod(true);2350_ok = false;2351}2352}2353virtual void do_oop(narrowOop* p) { ShouldNotReachHere(); }2354};23552356class VerifyMetadataClosure: public MetadataClosure {2357public:2358void do_metadata(Metadata* md) {2359if (md->is_method()) {2360Method* method = (Method*)md;2361assert(!method->is_old(), "Should not be installing old methods");2362}2363}2364};236523662367void nmethod::verify() {23682369// Hmm. OSR methods can be deopted but not marked as zombie or not_entrant2370// seems odd.23712372if (is_zombie() || is_not_entrant() || is_unloaded())2373return;23742375// Make sure all the entry points are correctly aligned for patching.2376NativeJump::check_verified_entry_alignment(entry_point(), verified_entry_point());23772378// assert(oopDesc::is_oop(method()), "must be valid");23792380ResourceMark rm;23812382if (!CodeCache::contains(this)) {2383fatal("nmethod at " INTPTR_FORMAT " not in zone", p2i(this));2384}23852386if(is_native_method() )2387return;23882389nmethod* nm = CodeCache::find_nmethod(verified_entry_point());2390if (nm != this) {2391fatal("findNMethod did not find this nmethod (" INTPTR_FORMAT ")", p2i(this));2392}23932394for (PcDesc* p = scopes_pcs_begin(); p < scopes_pcs_end(); p++) {2395if (! p->verify(this)) {2396tty->print_cr("\t\tin nmethod at " INTPTR_FORMAT " (pcs)", p2i(this));2397}2398}23992400#ifdef ASSERT2401#if INCLUDE_JVMCI2402{2403// Verify that implicit exceptions that deoptimize have a PcDesc and OopMap2404ImmutableOopMapSet* oms = oop_maps();2405ImplicitExceptionTable implicit_table(this);2406for (uint i = 0; i < implicit_table.len(); i++) {2407int exec_offset = (int) implicit_table.get_exec_offset(i);2408if (implicit_table.get_exec_offset(i) == implicit_table.get_cont_offset(i)) {2409assert(pc_desc_at(code_begin() + exec_offset) != NULL, "missing PcDesc");2410bool found = false;2411for (int i = 0, imax = oms->count(); i < imax; i++) {2412if (oms->pair_at(i)->pc_offset() == exec_offset) {2413found = true;2414break;2415}2416}2417assert(found, "missing oopmap");2418}2419}2420}2421#endif2422#endif24232424VerifyOopsClosure voc(this);2425oops_do(&voc);2426assert(voc.ok(), "embedded oops must be OK");2427Universe::heap()->verify_nmethod(this);24282429assert(_oops_do_mark_link == NULL, "_oops_do_mark_link for %s should be NULL but is " PTR_FORMAT,2430nm->method()->external_name(), p2i(_oops_do_mark_link));2431verify_scopes();24322433CompiledICLocker nm_verify(this);2434VerifyMetadataClosure vmc;2435metadata_do(&vmc);2436}243724382439void nmethod::verify_interrupt_point(address call_site) {24402441// Verify IC only when nmethod installation is finished.2442if (!is_not_installed()) {2443if (CompiledICLocker::is_safe(this)) {2444CompiledIC_at(this, call_site);2445} else {2446CompiledICLocker ml_verify(this);2447CompiledIC_at(this, call_site);2448}2449}24502451HandleMark hm(Thread::current());24522453PcDesc* pd = pc_desc_at(nativeCall_at(call_site)->return_address());2454assert(pd != NULL, "PcDesc must exist");2455for (ScopeDesc* sd = new ScopeDesc(this, pd);2456!sd->is_top(); sd = sd->sender()) {2457sd->verify();2458}2459}24602461void nmethod::verify_scopes() {2462if( !method() ) return; // Runtime stubs have no scope2463if (method()->is_native()) return; // Ignore stub methods.2464// iterate through all interrupt point2465// and verify the debug information is valid.2466RelocIterator iter((nmethod*)this);2467while (iter.next()) {2468address stub = NULL;2469switch (iter.type()) {2470case relocInfo::virtual_call_type:2471verify_interrupt_point(iter.addr());2472break;2473case relocInfo::opt_virtual_call_type:2474stub = iter.opt_virtual_call_reloc()->static_stub();2475verify_interrupt_point(iter.addr());2476break;2477case relocInfo::static_call_type:2478stub = iter.static_call_reloc()->static_stub();2479//verify_interrupt_point(iter.addr());2480break;2481case relocInfo::runtime_call_type:2482case relocInfo::runtime_call_w_cp_type: {2483address destination = iter.reloc()->value();2484// Right now there is no way to find out which entries support2485// an interrupt point. It would be nice if we had this2486// information in a table.2487break;2488}2489default:2490break;2491}2492assert(stub == NULL || stub_contains(stub), "static call stub outside stub section");2493}2494}249524962497// -----------------------------------------------------------------------------2498// Printing operations24992500void nmethod::print() const {2501ttyLocker ttyl; // keep the following output all in one block2502print(tty);2503}25042505void nmethod::print(outputStream* st) const {2506ResourceMark rm;25072508st->print("Compiled method ");25092510if (is_compiled_by_c1()) {2511st->print("(c1) ");2512} else if (is_compiled_by_c2()) {2513st->print("(c2) ");2514} else if (is_compiled_by_jvmci()) {2515st->print("(JVMCI) ");2516} else {2517st->print("(n/a) ");2518}25192520print_on(tty, NULL);25212522if (WizardMode) {2523st->print("((nmethod*) " INTPTR_FORMAT ") ", p2i(this));2524st->print(" for method " INTPTR_FORMAT , p2i(method()));2525st->print(" { ");2526st->print_cr("%s ", state());2527st->print_cr("}:");2528}2529if (size () > 0) st->print_cr(" total in heap [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",2530p2i(this),2531p2i(this) + size(),2532size());2533if (relocation_size () > 0) st->print_cr(" relocation [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",2534p2i(relocation_begin()),2535p2i(relocation_end()),2536relocation_size());2537if (consts_size () > 0) st->print_cr(" constants [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",2538p2i(consts_begin()),2539p2i(consts_end()),2540consts_size());2541if (insts_size () > 0) st->print_cr(" main code [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",2542p2i(insts_begin()),2543p2i(insts_end()),2544insts_size());2545if (stub_size () > 0) st->print_cr(" stub code [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",2546p2i(stub_begin()),2547p2i(stub_end()),2548stub_size());2549if (oops_size () > 0) st->print_cr(" oops [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",2550p2i(oops_begin()),2551p2i(oops_end()),2552oops_size());2553if (metadata_size () > 0) st->print_cr(" metadata [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",2554p2i(metadata_begin()),2555p2i(metadata_end()),2556metadata_size());2557if (scopes_data_size () > 0) st->print_cr(" scopes data [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",2558p2i(scopes_data_begin()),2559p2i(scopes_data_end()),2560scopes_data_size());2561if (scopes_pcs_size () > 0) st->print_cr(" scopes pcs [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",2562p2i(scopes_pcs_begin()),2563p2i(scopes_pcs_end()),2564scopes_pcs_size());2565if (dependencies_size () > 0) st->print_cr(" dependencies [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",2566p2i(dependencies_begin()),2567p2i(dependencies_end()),2568dependencies_size());2569if (handler_table_size() > 0) st->print_cr(" handler table [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",2570p2i(handler_table_begin()),2571p2i(handler_table_end()),2572handler_table_size());2573if (nul_chk_table_size() > 0) st->print_cr(" nul chk table [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",2574p2i(nul_chk_table_begin()),2575p2i(nul_chk_table_end()),2576nul_chk_table_size());2577#if INCLUDE_JVMCI2578if (speculations_size () > 0) st->print_cr(" speculations [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",2579p2i(speculations_begin()),2580p2i(speculations_end()),2581speculations_size());2582if (jvmci_data_size () > 0) st->print_cr(" JVMCI data [" INTPTR_FORMAT "," INTPTR_FORMAT "] = %d",2583p2i(jvmci_data_begin()),2584p2i(jvmci_data_end()),2585jvmci_data_size());2586#endif2587}25882589void nmethod::print_code() {2590ResourceMark m;2591ttyLocker ttyl;2592// Call the specialized decode method of this class.2593decode(tty);2594}25952596#ifndef PRODUCT // called InstanceKlass methods are available only then. Declared as PRODUCT_RETURN25972598void nmethod::print_dependencies() {2599ResourceMark rm;2600ttyLocker ttyl; // keep the following output all in one block2601tty->print_cr("Dependencies:");2602for (Dependencies::DepStream deps(this); deps.next(); ) {2603deps.print_dependency();2604Klass* ctxk = deps.context_type();2605if (ctxk != NULL) {2606if (ctxk->is_instance_klass() && InstanceKlass::cast(ctxk)->is_dependent_nmethod(this)) {2607tty->print_cr(" [nmethod<=klass]%s", ctxk->external_name());2608}2609}2610deps.log_dependency(); // put it into the xml log also2611}2612}2613#endif26142615#if defined(SUPPORT_DATA_STRUCTS)26162617// Print the oops from the underlying CodeBlob.2618void nmethod::print_oops(outputStream* st) {2619ResourceMark m;2620st->print("Oops:");2621if (oops_begin() < oops_end()) {2622st->cr();2623for (oop* p = oops_begin(); p < oops_end(); p++) {2624Disassembler::print_location((unsigned char*)p, (unsigned char*)oops_begin(), (unsigned char*)oops_end(), st, true, false);2625st->print(PTR_FORMAT " ", *((uintptr_t*)p));2626if (Universe::contains_non_oop_word(p)) {2627st->print_cr("NON_OOP");2628continue; // skip non-oops2629}2630if (*p == NULL) {2631st->print_cr("NULL-oop");2632continue; // skip non-oops2633}2634(*p)->print_value_on(st);2635st->cr();2636}2637} else {2638st->print_cr(" <list empty>");2639}2640}26412642// Print metadata pool.2643void nmethod::print_metadata(outputStream* st) {2644ResourceMark m;2645st->print("Metadata:");2646if (metadata_begin() < metadata_end()) {2647st->cr();2648for (Metadata** p = metadata_begin(); p < metadata_end(); p++) {2649Disassembler::print_location((unsigned char*)p, (unsigned char*)metadata_begin(), (unsigned char*)metadata_end(), st, true, false);2650st->print(PTR_FORMAT " ", *((uintptr_t*)p));2651if (*p && *p != Universe::non_oop_word()) {2652(*p)->print_value_on(st);2653}2654st->cr();2655}2656} else {2657st->print_cr(" <list empty>");2658}2659}26602661#ifndef PRODUCT // ScopeDesc::print_on() is available only then. Declared as PRODUCT_RETURN2662void nmethod::print_scopes_on(outputStream* st) {2663// Find the first pc desc for all scopes in the code and print it.2664ResourceMark rm;2665st->print("scopes:");2666if (scopes_pcs_begin() < scopes_pcs_end()) {2667st->cr();2668for (PcDesc* p = scopes_pcs_begin(); p < scopes_pcs_end(); p++) {2669if (p->scope_decode_offset() == DebugInformationRecorder::serialized_null)2670continue;26712672ScopeDesc* sd = scope_desc_at(p->real_pc(this));2673while (sd != NULL) {2674sd->print_on(st, p); // print output ends with a newline2675sd = sd->sender();2676}2677}2678} else {2679st->print_cr(" <list empty>");2680}2681}2682#endif26832684#ifndef PRODUCT // RelocIterator does support printing only then.2685void nmethod::print_relocations() {2686ResourceMark m; // in case methods get printed via the debugger2687tty->print_cr("relocations:");2688RelocIterator iter(this);2689iter.print();2690}2691#endif26922693void nmethod::print_pcs_on(outputStream* st) {2694ResourceMark m; // in case methods get printed via debugger2695st->print("pc-bytecode offsets:");2696if (scopes_pcs_begin() < scopes_pcs_end()) {2697st->cr();2698for (PcDesc* p = scopes_pcs_begin(); p < scopes_pcs_end(); p++) {2699p->print_on(st, this); // print output ends with a newline2700}2701} else {2702st->print_cr(" <list empty>");2703}2704}27052706void nmethod::print_native_invokers() {2707ResourceMark m; // in case methods get printed via debugger2708tty->print_cr("Native invokers:");2709for (RuntimeStub** itt = native_invokers_begin(); itt < native_invokers_end(); itt++) {2710(*itt)->print_on(tty);2711}2712}27132714void nmethod::print_handler_table() {2715ExceptionHandlerTable(this).print(code_begin());2716}27172718void nmethod::print_nul_chk_table() {2719ImplicitExceptionTable(this).print(code_begin());2720}27212722void nmethod::print_recorded_oop(int log_n, int i) {2723void* value;27242725if (i == 0) {2726value = NULL;2727} else {2728// Be careful around non-oop words. Don't create an oop2729// with that value, or it will assert in verification code.2730if (Universe::contains_non_oop_word(oop_addr_at(i))) {2731value = Universe::non_oop_word();2732} else {2733value = oop_at(i);2734}2735}27362737tty->print("#%*d: " INTPTR_FORMAT " ", log_n, i, p2i(value));27382739if (value == Universe::non_oop_word()) {2740tty->print("non-oop word");2741} else {2742if (value == 0) {2743tty->print("NULL-oop");2744} else {2745oop_at(i)->print_value_on(tty);2746}2747}27482749tty->cr();2750}27512752void nmethod::print_recorded_oops() {2753const int n = oops_count();2754const int log_n = (n<10) ? 1 : (n<100) ? 2 : (n<1000) ? 3 : (n<10000) ? 4 : 6;2755tty->print("Recorded oops:");2756if (n > 0) {2757tty->cr();2758for (int i = 0; i < n; i++) {2759print_recorded_oop(log_n, i);2760}2761} else {2762tty->print_cr(" <list empty>");2763}2764}27652766void nmethod::print_recorded_metadata() {2767const int n = metadata_count();2768const int log_n = (n<10) ? 1 : (n<100) ? 2 : (n<1000) ? 3 : (n<10000) ? 4 : 6;2769tty->print("Recorded metadata:");2770if (n > 0) {2771tty->cr();2772for (int i = 0; i < n; i++) {2773Metadata* m = metadata_at(i);2774tty->print("#%*d: " INTPTR_FORMAT " ", log_n, i, p2i(m));2775if (m == (Metadata*)Universe::non_oop_word()) {2776tty->print("non-metadata word");2777} else if (m == NULL) {2778tty->print("NULL-oop");2779} else {2780Metadata::print_value_on_maybe_null(tty, m);2781}2782tty->cr();2783}2784} else {2785tty->print_cr(" <list empty>");2786}2787}2788#endif27892790#if defined(SUPPORT_ASSEMBLY) || defined(SUPPORT_ABSTRACT_ASSEMBLY)27912792void nmethod::print_constant_pool(outputStream* st) {2793//-----------------------------------2794//---< Print the constant pool >---2795//-----------------------------------2796int consts_size = this->consts_size();2797if ( consts_size > 0 ) {2798unsigned char* cstart = this->consts_begin();2799unsigned char* cp = cstart;2800unsigned char* cend = cp + consts_size;2801unsigned int bytes_per_line = 4;2802unsigned int CP_alignment = 8;2803unsigned int n;28042805st->cr();28062807//---< print CP header to make clear what's printed >---2808if( ((uintptr_t)cp&(CP_alignment-1)) == 0 ) {2809n = bytes_per_line;2810st->print_cr("[Constant Pool]");2811Disassembler::print_location(cp, cstart, cend, st, true, true);2812Disassembler::print_hexdata(cp, n, st, true);2813st->cr();2814} else {2815n = (uintptr_t)cp&(bytes_per_line-1);2816st->print_cr("[Constant Pool (unaligned)]");2817}28182819//---< print CP contents, bytes_per_line at a time >---2820while (cp < cend) {2821Disassembler::print_location(cp, cstart, cend, st, true, false);2822Disassembler::print_hexdata(cp, n, st, false);2823cp += n;2824n = bytes_per_line;2825st->cr();2826}28272828//---< Show potential alignment gap between constant pool and code >---2829cend = code_begin();2830if( cp < cend ) {2831n = 4;2832st->print_cr("[Code entry alignment]");2833while (cp < cend) {2834Disassembler::print_location(cp, cstart, cend, st, false, false);2835cp += n;2836st->cr();2837}2838}2839} else {2840st->print_cr("[Constant Pool (empty)]");2841}2842st->cr();2843}28442845#endif28462847// Disassemble this nmethod.2848// Print additional debug information, if requested. This could be code2849// comments, block comments, profiling counters, etc.2850// The undisassembled format is useful no disassembler library is available.2851// The resulting hex dump (with markers) can be disassembled later, or on2852// another system, when/where a disassembler library is available.2853void nmethod::decode2(outputStream* ost) const {28542855// Called from frame::back_trace_with_decode without ResourceMark.2856ResourceMark rm;28572858// Make sure we have a valid stream to print on.2859outputStream* st = ost ? ost : tty;28602861#if defined(SUPPORT_ABSTRACT_ASSEMBLY) && ! defined(SUPPORT_ASSEMBLY)2862const bool use_compressed_format = true;2863const bool compressed_with_comments = use_compressed_format && (AbstractDisassembler::show_comment() ||2864AbstractDisassembler::show_block_comment());2865#else2866const bool use_compressed_format = Disassembler::is_abstract();2867const bool compressed_with_comments = use_compressed_format && (AbstractDisassembler::show_comment() ||2868AbstractDisassembler::show_block_comment());2869#endif28702871st->cr();2872this->print(st);2873st->cr();28742875#if defined(SUPPORT_ASSEMBLY)2876//----------------------------------2877//---< Print real disassembly >---2878//----------------------------------2879if (! use_compressed_format) {2880Disassembler::decode(const_cast<nmethod*>(this), st);2881return;2882}2883#endif28842885#if defined(SUPPORT_ABSTRACT_ASSEMBLY)28862887// Compressed undisassembled disassembly format.2888// The following stati are defined/supported:2889// = 0 - currently at bol() position, nothing printed yet on current line.2890// = 1 - currently at position after print_location().2891// > 1 - in the midst of printing instruction stream bytes.2892int compressed_format_idx = 0;2893int code_comment_column = 0;2894const int instr_maxlen = Assembler::instr_maxlen();2895const uint tabspacing = 8;2896unsigned char* start = this->code_begin();2897unsigned char* p = this->code_begin();2898unsigned char* end = this->code_end();2899unsigned char* pss = p; // start of a code section (used for offsets)29002901if ((start == NULL) || (end == NULL)) {2902st->print_cr("PrintAssembly not possible due to uninitialized section pointers");2903return;2904}2905#endif29062907#if defined(SUPPORT_ABSTRACT_ASSEMBLY)2908//---< plain abstract disassembly, no comments or anything, just section headers >---2909if (use_compressed_format && ! compressed_with_comments) {2910const_cast<nmethod*>(this)->print_constant_pool(st);29112912//---< Open the output (Marker for post-mortem disassembler) >---2913st->print_cr("[MachCode]");2914const char* header = NULL;2915address p0 = p;2916while (p < end) {2917address pp = p;2918while ((p < end) && (header == NULL)) {2919header = nmethod_section_label(p);2920pp = p;2921p += Assembler::instr_len(p);2922}2923if (pp > p0) {2924AbstractDisassembler::decode_range_abstract(p0, pp, start, end, st, Assembler::instr_maxlen());2925p0 = pp;2926p = pp;2927header = NULL;2928} else if (header != NULL) {2929st->bol();2930st->print_cr("%s", header);2931header = NULL;2932}2933}2934//---< Close the output (Marker for post-mortem disassembler) >---2935st->bol();2936st->print_cr("[/MachCode]");2937return;2938}2939#endif29402941#if defined(SUPPORT_ABSTRACT_ASSEMBLY)2942//---< abstract disassembly with comments and section headers merged in >---2943if (compressed_with_comments) {2944const_cast<nmethod*>(this)->print_constant_pool(st);29452946//---< Open the output (Marker for post-mortem disassembler) >---2947st->print_cr("[MachCode]");2948while ((p < end) && (p != NULL)) {2949const int instruction_size_in_bytes = Assembler::instr_len(p);29502951//---< Block comments for nmethod. Interrupts instruction stream, if any. >---2952// Outputs a bol() before and a cr() after, but only if a comment is printed.2953// Prints nmethod_section_label as well.2954if (AbstractDisassembler::show_block_comment()) {2955print_block_comment(st, p);2956if (st->position() == 0) {2957compressed_format_idx = 0;2958}2959}29602961//---< New location information after line break >---2962if (compressed_format_idx == 0) {2963code_comment_column = Disassembler::print_location(p, pss, end, st, false, false);2964compressed_format_idx = 1;2965}29662967//---< Code comment for current instruction. Address range [p..(p+len)) >---2968unsigned char* p_end = p + (ssize_t)instruction_size_in_bytes;2969S390_ONLY(if (p_end > end) p_end = end;) // avoid getting past the end29702971if (AbstractDisassembler::show_comment() && const_cast<nmethod*>(this)->has_code_comment(p, p_end)) {2972//---< interrupt instruction byte stream for code comment >---2973if (compressed_format_idx > 1) {2974st->cr(); // interrupt byte stream2975st->cr(); // add an empty line2976code_comment_column = Disassembler::print_location(p, pss, end, st, false, false);2977}2978const_cast<nmethod*>(this)->print_code_comment_on(st, code_comment_column, p, p_end );2979st->bol();2980compressed_format_idx = 0;2981}29822983//---< New location information after line break >---2984if (compressed_format_idx == 0) {2985code_comment_column = Disassembler::print_location(p, pss, end, st, false, false);2986compressed_format_idx = 1;2987}29882989//---< Nicely align instructions for readability >---2990if (compressed_format_idx > 1) {2991Disassembler::print_delimiter(st);2992}29932994//---< Now, finally, print the actual instruction bytes >---2995unsigned char* p0 = p;2996p = Disassembler::decode_instruction_abstract(p, st, instruction_size_in_bytes, instr_maxlen);2997compressed_format_idx += p - p0;29982999if (Disassembler::start_newline(compressed_format_idx-1)) {3000st->cr();3001compressed_format_idx = 0;3002}3003}3004//---< Close the output (Marker for post-mortem disassembler) >---3005st->bol();3006st->print_cr("[/MachCode]");3007return;3008}3009#endif3010}30113012#if defined(SUPPORT_ASSEMBLY) || defined(SUPPORT_ABSTRACT_ASSEMBLY)30133014const char* nmethod::reloc_string_for(u_char* begin, u_char* end) {3015RelocIterator iter(this, begin, end);3016bool have_one = false;3017while (iter.next()) {3018have_one = true;3019switch (iter.type()) {3020case relocInfo::none: return "no_reloc";3021case relocInfo::oop_type: {3022// Get a non-resizable resource-allocated stringStream.3023// Our callees make use of (nested) ResourceMarks.3024stringStream st(NEW_RESOURCE_ARRAY(char, 1024), 1024);3025oop_Relocation* r = iter.oop_reloc();3026oop obj = r->oop_value();3027st.print("oop(");3028if (obj == NULL) st.print("NULL");3029else obj->print_value_on(&st);3030st.print(")");3031return st.as_string();3032}3033case relocInfo::metadata_type: {3034stringStream st;3035metadata_Relocation* r = iter.metadata_reloc();3036Metadata* obj = r->metadata_value();3037st.print("metadata(");3038if (obj == NULL) st.print("NULL");3039else obj->print_value_on(&st);3040st.print(")");3041return st.as_string();3042}3043case relocInfo::runtime_call_type:3044case relocInfo::runtime_call_w_cp_type: {3045stringStream st;3046st.print("runtime_call");3047CallRelocation* r = (CallRelocation*)iter.reloc();3048address dest = r->destination();3049CodeBlob* cb = CodeCache::find_blob(dest);3050if (cb != NULL) {3051st.print(" %s", cb->name());3052} else {3053ResourceMark rm;3054const int buflen = 1024;3055char* buf = NEW_RESOURCE_ARRAY(char, buflen);3056int offset;3057if (os::dll_address_to_function_name(dest, buf, buflen, &offset)) {3058st.print(" %s", buf);3059if (offset != 0) {3060st.print("+%d", offset);3061}3062}3063}3064return st.as_string();3065}3066case relocInfo::virtual_call_type: {3067stringStream st;3068st.print_raw("virtual_call");3069virtual_call_Relocation* r = iter.virtual_call_reloc();3070Method* m = r->method_value();3071if (m != NULL) {3072assert(m->is_method(), "");3073m->print_short_name(&st);3074}3075return st.as_string();3076}3077case relocInfo::opt_virtual_call_type: {3078stringStream st;3079st.print_raw("optimized virtual_call");3080opt_virtual_call_Relocation* r = iter.opt_virtual_call_reloc();3081Method* m = r->method_value();3082if (m != NULL) {3083assert(m->is_method(), "");3084m->print_short_name(&st);3085}3086return st.as_string();3087}3088case relocInfo::static_call_type: {3089stringStream st;3090st.print_raw("static_call");3091static_call_Relocation* r = iter.static_call_reloc();3092Method* m = r->method_value();3093if (m != NULL) {3094assert(m->is_method(), "");3095m->print_short_name(&st);3096}3097return st.as_string();3098}3099case relocInfo::static_stub_type: return "static_stub";3100case relocInfo::external_word_type: return "external_word";3101case relocInfo::internal_word_type: return "internal_word";3102case relocInfo::section_word_type: return "section_word";3103case relocInfo::poll_type: return "poll";3104case relocInfo::poll_return_type: return "poll_return";3105case relocInfo::trampoline_stub_type: return "trampoline_stub";3106case relocInfo::type_mask: return "type_bit_mask";31073108default:3109break;3110}3111}3112return have_one ? "other" : NULL;3113}31143115// Return a the last scope in (begin..end]3116ScopeDesc* nmethod::scope_desc_in(address begin, address end) {3117PcDesc* p = pc_desc_near(begin+1);3118if (p != NULL && p->real_pc(this) <= end) {3119return new ScopeDesc(this, p);3120}3121return NULL;3122}31233124const char* nmethod::nmethod_section_label(address pos) const {3125const char* label = NULL;3126if (pos == code_begin()) label = "[Instructions begin]";3127if (pos == entry_point()) label = "[Entry Point]";3128if (pos == verified_entry_point()) label = "[Verified Entry Point]";3129if (has_method_handle_invokes() && (pos == deopt_mh_handler_begin())) label = "[Deopt MH Handler Code]";3130if (pos == consts_begin() && pos != insts_begin()) label = "[Constants]";3131// Check stub_code before checking exception_handler or deopt_handler.3132if (pos == this->stub_begin()) label = "[Stub Code]";3133if (JVMCI_ONLY(_exception_offset >= 0 &&) pos == exception_begin()) label = "[Exception Handler]";3134if (JVMCI_ONLY(_deopt_handler_begin != NULL &&) pos == deopt_handler_begin()) label = "[Deopt Handler Code]";3135return label;3136}31373138void nmethod::print_nmethod_labels(outputStream* stream, address block_begin, bool print_section_labels) const {3139if (print_section_labels) {3140const char* label = nmethod_section_label(block_begin);3141if (label != NULL) {3142stream->bol();3143stream->print_cr("%s", label);3144}3145}31463147if (block_begin == entry_point()) {3148Method* m = method();3149if (m != NULL) {3150stream->print(" # ");3151m->print_value_on(stream);3152stream->cr();3153}3154if (m != NULL && !is_osr_method()) {3155ResourceMark rm;3156int sizeargs = m->size_of_parameters();3157BasicType* sig_bt = NEW_RESOURCE_ARRAY(BasicType, sizeargs);3158VMRegPair* regs = NEW_RESOURCE_ARRAY(VMRegPair, sizeargs);3159{3160int sig_index = 0;3161if (!m->is_static())3162sig_bt[sig_index++] = T_OBJECT; // 'this'3163for (SignatureStream ss(m->signature()); !ss.at_return_type(); ss.next()) {3164BasicType t = ss.type();3165sig_bt[sig_index++] = t;3166if (type2size[t] == 2) {3167sig_bt[sig_index++] = T_VOID;3168} else {3169assert(type2size[t] == 1, "size is 1 or 2");3170}3171}3172assert(sig_index == sizeargs, "");3173}3174const char* spname = "sp"; // make arch-specific?3175intptr_t out_preserve = SharedRuntime::java_calling_convention(sig_bt, regs, sizeargs);3176int stack_slot_offset = this->frame_size() * wordSize;3177int tab1 = 14, tab2 = 24;3178int sig_index = 0;3179int arg_index = (m->is_static() ? 0 : -1);3180bool did_old_sp = false;3181for (SignatureStream ss(m->signature()); !ss.at_return_type(); ) {3182bool at_this = (arg_index == -1);3183bool at_old_sp = false;3184BasicType t = (at_this ? T_OBJECT : ss.type());3185assert(t == sig_bt[sig_index], "sigs in sync");3186if (at_this)3187stream->print(" # this: ");3188else3189stream->print(" # parm%d: ", arg_index);3190stream->move_to(tab1);3191VMReg fst = regs[sig_index].first();3192VMReg snd = regs[sig_index].second();3193if (fst->is_reg()) {3194stream->print("%s", fst->name());3195if (snd->is_valid()) {3196stream->print(":%s", snd->name());3197}3198} else if (fst->is_stack()) {3199int offset = fst->reg2stack() * VMRegImpl::stack_slot_size + stack_slot_offset;3200if (offset == stack_slot_offset) at_old_sp = true;3201stream->print("[%s+0x%x]", spname, offset);3202} else {3203stream->print("reg%d:%d??", (int)(intptr_t)fst, (int)(intptr_t)snd);3204}3205stream->print(" ");3206stream->move_to(tab2);3207stream->print("= ");3208if (at_this) {3209m->method_holder()->print_value_on(stream);3210} else {3211bool did_name = false;3212if (!at_this && ss.is_reference()) {3213Symbol* name = ss.as_symbol();3214name->print_value_on(stream);3215did_name = true;3216}3217if (!did_name)3218stream->print("%s", type2name(t));3219}3220if (at_old_sp) {3221stream->print(" (%s of caller)", spname);3222did_old_sp = true;3223}3224stream->cr();3225sig_index += type2size[t];3226arg_index += 1;3227if (!at_this) ss.next();3228}3229if (!did_old_sp) {3230stream->print(" # ");3231stream->move_to(tab1);3232stream->print("[%s+0x%x]", spname, stack_slot_offset);3233stream->print(" (%s of caller)", spname);3234stream->cr();3235}3236}3237}3238}32393240// Returns whether this nmethod has code comments.3241bool nmethod::has_code_comment(address begin, address end) {3242// scopes?3243ScopeDesc* sd = scope_desc_in(begin, end);3244if (sd != NULL) return true;32453246// relocations?3247const char* str = reloc_string_for(begin, end);3248if (str != NULL) return true;32493250// implicit exceptions?3251int cont_offset = ImplicitExceptionTable(this).continuation_offset(begin - code_begin());3252if (cont_offset != 0) return true;32533254return false;3255}32563257void nmethod::print_code_comment_on(outputStream* st, int column, address begin, address end) {3258ImplicitExceptionTable implicit_table(this);3259int pc_offset = begin - code_begin();3260int cont_offset = implicit_table.continuation_offset(pc_offset);3261bool oop_map_required = false;3262if (cont_offset != 0) {3263st->move_to(column, 6, 0);3264if (pc_offset == cont_offset) {3265st->print("; implicit exception: deoptimizes");3266oop_map_required = true;3267} else {3268st->print("; implicit exception: dispatches to " INTPTR_FORMAT, p2i(code_begin() + cont_offset));3269}3270}32713272// Find an oopmap in (begin, end]. We use the odd half-closed3273// interval so that oop maps and scope descs which are tied to the3274// byte after a call are printed with the call itself. OopMaps3275// associated with implicit exceptions are printed with the implicit3276// instruction.3277address base = code_begin();3278ImmutableOopMapSet* oms = oop_maps();3279if (oms != NULL) {3280for (int i = 0, imax = oms->count(); i < imax; i++) {3281const ImmutableOopMapPair* pair = oms->pair_at(i);3282const ImmutableOopMap* om = pair->get_from(oms);3283address pc = base + pair->pc_offset();3284if (pc >= begin) {3285#if INCLUDE_JVMCI3286bool is_implicit_deopt = implicit_table.continuation_offset(pair->pc_offset()) == (uint) pair->pc_offset();3287#else3288bool is_implicit_deopt = false;3289#endif3290if (is_implicit_deopt ? pc == begin : pc > begin && pc <= end) {3291st->move_to(column, 6, 0);3292st->print("; ");3293om->print_on(st);3294oop_map_required = false;3295}3296}3297if (pc > end) {3298break;3299}3300}3301}3302assert(!oop_map_required, "missed oopmap");33033304Thread* thread = Thread::current();33053306// Print any debug info present at this pc.3307ScopeDesc* sd = scope_desc_in(begin, end);3308if (sd != NULL) {3309st->move_to(column, 6, 0);3310if (sd->bci() == SynchronizationEntryBCI) {3311st->print(";*synchronization entry");3312} else if (sd->bci() == AfterBci) {3313st->print(";* method exit (unlocked if synchronized)");3314} else if (sd->bci() == UnwindBci) {3315st->print(";* unwind (locked if synchronized)");3316} else if (sd->bci() == AfterExceptionBci) {3317st->print(";* unwind (unlocked if synchronized)");3318} else if (sd->bci() == UnknownBci) {3319st->print(";* unknown");3320} else if (sd->bci() == InvalidFrameStateBci) {3321st->print(";* invalid frame state");3322} else {3323if (sd->method() == NULL) {3324st->print("method is NULL");3325} else if (sd->method()->is_native()) {3326st->print("method is native");3327} else {3328Bytecodes::Code bc = sd->method()->java_code_at(sd->bci());3329st->print(";*%s", Bytecodes::name(bc));3330switch (bc) {3331case Bytecodes::_invokevirtual:3332case Bytecodes::_invokespecial:3333case Bytecodes::_invokestatic:3334case Bytecodes::_invokeinterface:3335{3336Bytecode_invoke invoke(methodHandle(thread, sd->method()), sd->bci());3337st->print(" ");3338if (invoke.name() != NULL)3339invoke.name()->print_symbol_on(st);3340else3341st->print("<UNKNOWN>");3342break;3343}3344case Bytecodes::_getfield:3345case Bytecodes::_putfield:3346case Bytecodes::_getstatic:3347case Bytecodes::_putstatic:3348{3349Bytecode_field field(methodHandle(thread, sd->method()), sd->bci());3350st->print(" ");3351if (field.name() != NULL)3352field.name()->print_symbol_on(st);3353else3354st->print("<UNKNOWN>");3355}3356default:3357break;3358}3359}3360st->print(" {reexecute=%d rethrow=%d return_oop=%d}", sd->should_reexecute(), sd->rethrow_exception(), sd->return_oop());3361}33623363// Print all scopes3364for (;sd != NULL; sd = sd->sender()) {3365st->move_to(column, 6, 0);3366st->print("; -");3367if (sd->should_reexecute()) {3368st->print(" (reexecute)");3369}3370if (sd->method() == NULL) {3371st->print("method is NULL");3372} else {3373sd->method()->print_short_name(st);3374}3375int lineno = sd->method()->line_number_from_bci(sd->bci());3376if (lineno != -1) {3377st->print("@%d (line %d)", sd->bci(), lineno);3378} else {3379st->print("@%d", sd->bci());3380}3381st->cr();3382}3383}33843385// Print relocation information3386// Prevent memory leak: allocating without ResourceMark.3387ResourceMark rm;3388const char* str = reloc_string_for(begin, end);3389if (str != NULL) {3390if (sd != NULL) st->cr();3391st->move_to(column, 6, 0);3392st->print("; {%s}", str);3393}3394}33953396#endif33973398class DirectNativeCallWrapper: public NativeCallWrapper {3399private:3400NativeCall* _call;34013402public:3403DirectNativeCallWrapper(NativeCall* call) : _call(call) {}34043405virtual address destination() const { return _call->destination(); }3406virtual address instruction_address() const { return _call->instruction_address(); }3407virtual address next_instruction_address() const { return _call->next_instruction_address(); }3408virtual address return_address() const { return _call->return_address(); }34093410virtual address get_resolve_call_stub(bool is_optimized) const {3411if (is_optimized) {3412return SharedRuntime::get_resolve_opt_virtual_call_stub();3413}3414return SharedRuntime::get_resolve_virtual_call_stub();3415}34163417virtual void set_destination_mt_safe(address dest) {3418_call->set_destination_mt_safe(dest);3419}34203421virtual void set_to_interpreted(const methodHandle& method, CompiledICInfo& info) {3422CompiledDirectStaticCall* csc = CompiledDirectStaticCall::at(instruction_address());3423{3424csc->set_to_interpreted(method, info.entry());3425}3426}34273428virtual void verify() const {3429// make sure code pattern is actually a call imm32 instruction3430_call->verify();3431_call->verify_alignment();3432}34333434virtual void verify_resolve_call(address dest) const {3435CodeBlob* db = CodeCache::find_blob_unsafe(dest);3436assert(db != NULL && !db->is_adapter_blob(), "must use stub!");3437}34383439virtual bool is_call_to_interpreted(address dest) const {3440CodeBlob* cb = CodeCache::find_blob(_call->instruction_address());3441return cb->contains(dest);3442}34433444virtual bool is_safe_for_patching() const { return false; }34453446virtual NativeInstruction* get_load_instruction(virtual_call_Relocation* r) const {3447return nativeMovConstReg_at(r->cached_value());3448}34493450virtual void *get_data(NativeInstruction* instruction) const {3451return (void*)((NativeMovConstReg*) instruction)->data();3452}34533454virtual void set_data(NativeInstruction* instruction, intptr_t data) {3455((NativeMovConstReg*) instruction)->set_data(data);3456}3457};34583459NativeCallWrapper* nmethod::call_wrapper_at(address call) const {3460return new DirectNativeCallWrapper((NativeCall*) call);3461}34623463NativeCallWrapper* nmethod::call_wrapper_before(address return_pc) const {3464return new DirectNativeCallWrapper(nativeCall_before(return_pc));3465}34663467address nmethod::call_instruction_address(address pc) const {3468if (NativeCall::is_call_before(pc)) {3469NativeCall *ncall = nativeCall_before(pc);3470return ncall->instruction_address();3471}3472return NULL;3473}34743475CompiledStaticCall* nmethod::compiledStaticCall_at(Relocation* call_site) const {3476return CompiledDirectStaticCall::at(call_site);3477}34783479CompiledStaticCall* nmethod::compiledStaticCall_at(address call_site) const {3480return CompiledDirectStaticCall::at(call_site);3481}34823483CompiledStaticCall* nmethod::compiledStaticCall_before(address return_addr) const {3484return CompiledDirectStaticCall::before(return_addr);3485}34863487#if defined(SUPPORT_DATA_STRUCTS)3488void nmethod::print_value_on(outputStream* st) const {3489st->print("nmethod");3490print_on(st, NULL);3491}3492#endif34933494#ifndef PRODUCT34953496void nmethod::print_calls(outputStream* st) {3497RelocIterator iter(this);3498while (iter.next()) {3499switch (iter.type()) {3500case relocInfo::virtual_call_type:3501case relocInfo::opt_virtual_call_type: {3502CompiledICLocker ml_verify(this);3503CompiledIC_at(&iter)->print();3504break;3505}3506case relocInfo::static_call_type:3507st->print_cr("Static call at " INTPTR_FORMAT, p2i(iter.reloc()->addr()));3508CompiledDirectStaticCall::at(iter.reloc())->print();3509break;3510default:3511break;3512}3513}3514}35153516void nmethod::print_statistics() {3517ttyLocker ttyl;3518if (xtty != NULL) xtty->head("statistics type='nmethod'");3519native_nmethod_stats.print_native_nmethod_stats();3520#ifdef COMPILER13521c1_java_nmethod_stats.print_nmethod_stats("C1");3522#endif3523#ifdef COMPILER23524c2_java_nmethod_stats.print_nmethod_stats("C2");3525#endif3526#if INCLUDE_JVMCI3527jvmci_java_nmethod_stats.print_nmethod_stats("JVMCI");3528#endif3529unknown_java_nmethod_stats.print_nmethod_stats("Unknown");3530DebugInformationRecorder::print_statistics();3531#ifndef PRODUCT3532pc_nmethod_stats.print_pc_stats();3533#endif3534Dependencies::print_statistics();3535if (xtty != NULL) xtty->tail("statistics");3536}35373538#endif // !PRODUCT35393540#if INCLUDE_JVMCI3541void nmethod::update_speculation(JavaThread* thread) {3542jlong speculation = thread->pending_failed_speculation();3543if (speculation != 0) {3544guarantee(jvmci_nmethod_data() != NULL, "failed speculation in nmethod without failed speculation list");3545jvmci_nmethod_data()->add_failed_speculation(this, speculation);3546thread->set_pending_failed_speculation(0);3547}3548}35493550const char* nmethod::jvmci_name() {3551if (jvmci_nmethod_data() != NULL) {3552return jvmci_nmethod_data()->name();3553}3554return NULL;3555}3556#endif355735583559