Path: blob/master/src/hotspot/share/runtime/deoptimization.cpp
40951 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 "classfile/javaClasses.inline.hpp"27#include "classfile/symbolTable.hpp"28#include "classfile/systemDictionary.hpp"29#include "classfile/vmClasses.hpp"30#include "code/codeCache.hpp"31#include "code/debugInfoRec.hpp"32#include "code/nmethod.hpp"33#include "code/pcDesc.hpp"34#include "code/scopeDesc.hpp"35#include "compiler/compilationPolicy.hpp"36#include "gc/shared/collectedHeap.hpp"37#include "interpreter/bytecode.hpp"38#include "interpreter/interpreter.hpp"39#include "interpreter/oopMapCache.hpp"40#include "memory/allocation.inline.hpp"41#include "memory/oopFactory.hpp"42#include "memory/resourceArea.hpp"43#include "memory/universe.hpp"44#include "oops/constantPool.hpp"45#include "oops/method.hpp"46#include "oops/objArrayKlass.hpp"47#include "oops/objArrayOop.inline.hpp"48#include "oops/oop.inline.hpp"49#include "oops/fieldStreams.inline.hpp"50#include "oops/typeArrayOop.inline.hpp"51#include "oops/verifyOopClosure.hpp"52#include "prims/jvmtiDeferredUpdates.hpp"53#include "prims/jvmtiExport.hpp"54#include "prims/jvmtiThreadState.hpp"55#include "prims/vectorSupport.hpp"56#include "prims/methodHandles.hpp"57#include "runtime/atomic.hpp"58#include "runtime/biasedLocking.hpp"59#include "runtime/deoptimization.hpp"60#include "runtime/escapeBarrier.hpp"61#include "runtime/fieldDescriptor.hpp"62#include "runtime/fieldDescriptor.inline.hpp"63#include "runtime/frame.inline.hpp"64#include "runtime/handles.inline.hpp"65#include "runtime/interfaceSupport.inline.hpp"66#include "runtime/jniHandles.inline.hpp"67#include "runtime/keepStackGCProcessed.hpp"68#include "runtime/objectMonitor.inline.hpp"69#include "runtime/osThread.hpp"70#include "runtime/safepointVerifiers.hpp"71#include "runtime/sharedRuntime.hpp"72#include "runtime/signature.hpp"73#include "runtime/stackFrameStream.inline.hpp"74#include "runtime/stackWatermarkSet.hpp"75#include "runtime/stubRoutines.hpp"76#include "runtime/thread.hpp"77#include "runtime/threadSMR.hpp"78#include "runtime/threadWXSetters.inline.hpp"79#include "runtime/vframe.hpp"80#include "runtime/vframeArray.hpp"81#include "runtime/vframe_hp.hpp"82#include "runtime/vmOperations.hpp"83#include "utilities/events.hpp"84#include "utilities/macros.hpp"85#include "utilities/preserveException.hpp"86#include "utilities/xmlstream.hpp"87#if INCLUDE_JFR88#include "jfr/jfrEvents.hpp"89#include "jfr/metadata/jfrSerializer.hpp"90#endif9192bool DeoptimizationMarker::_is_active = false;9394Deoptimization::UnrollBlock::UnrollBlock(int size_of_deoptimized_frame,95int caller_adjustment,96int caller_actual_parameters,97int number_of_frames,98intptr_t* frame_sizes,99address* frame_pcs,100BasicType return_type,101int exec_mode) {102_size_of_deoptimized_frame = size_of_deoptimized_frame;103_caller_adjustment = caller_adjustment;104_caller_actual_parameters = caller_actual_parameters;105_number_of_frames = number_of_frames;106_frame_sizes = frame_sizes;107_frame_pcs = frame_pcs;108_register_block = NEW_C_HEAP_ARRAY(intptr_t, RegisterMap::reg_count * 2, mtCompiler);109_return_type = return_type;110_initial_info = 0;111// PD (x86 only)112_counter_temp = 0;113_unpack_kind = exec_mode;114_sender_sp_temp = 0;115116_total_frame_sizes = size_of_frames();117assert(exec_mode >= 0 && exec_mode < Unpack_LIMIT, "Unexpected exec_mode");118}119120121Deoptimization::UnrollBlock::~UnrollBlock() {122FREE_C_HEAP_ARRAY(intptr_t, _frame_sizes);123FREE_C_HEAP_ARRAY(intptr_t, _frame_pcs);124FREE_C_HEAP_ARRAY(intptr_t, _register_block);125}126127128intptr_t* Deoptimization::UnrollBlock::value_addr_at(int register_number) const {129assert(register_number < RegisterMap::reg_count, "checking register number");130return &_register_block[register_number * 2];131}132133134135int Deoptimization::UnrollBlock::size_of_frames() const {136// Acount first for the adjustment of the initial frame137int result = _caller_adjustment;138for (int index = 0; index < number_of_frames(); index++) {139result += frame_sizes()[index];140}141return result;142}143144145void Deoptimization::UnrollBlock::print() {146ttyLocker ttyl;147tty->print_cr("UnrollBlock");148tty->print_cr(" size_of_deoptimized_frame = %d", _size_of_deoptimized_frame);149tty->print( " frame_sizes: ");150for (int index = 0; index < number_of_frames(); index++) {151tty->print(INTX_FORMAT " ", frame_sizes()[index]);152}153tty->cr();154}155156157// In order to make fetch_unroll_info work properly with escape158// analysis, the method was changed from JRT_LEAF to JRT_BLOCK_ENTRY.159// The actual reallocation of previously eliminated objects occurs in realloc_objects,160// which is called from the method fetch_unroll_info_helper below.161JRT_BLOCK_ENTRY(Deoptimization::UnrollBlock*, Deoptimization::fetch_unroll_info(JavaThread* current, int exec_mode))162// fetch_unroll_info() is called at the beginning of the deoptimization163// handler. Note this fact before we start generating temporary frames164// that can confuse an asynchronous stack walker. This counter is165// decremented at the end of unpack_frames().166if (TraceDeoptimization) {167tty->print_cr("Deoptimizing thread " INTPTR_FORMAT, p2i(current));168}169current->inc_in_deopt_handler();170171if (exec_mode == Unpack_exception) {172// When we get here, a callee has thrown an exception into a deoptimized173// frame. That throw might have deferred stack watermark checking until174// after unwinding. So we deal with such deferred requests here.175StackWatermarkSet::after_unwind(current);176}177178return fetch_unroll_info_helper(current, exec_mode);179JRT_END180181#if COMPILER2_OR_JVMCI182static bool rematerialize_objects(JavaThread* thread, int exec_mode, CompiledMethod* compiled_method,183frame& deoptee, RegisterMap& map, GrowableArray<compiledVFrame*>* chunk,184bool& deoptimized_objects) {185bool realloc_failures = false;186assert (chunk->at(0)->scope() != NULL,"expect only compiled java frames");187188JavaThread* deoptee_thread = chunk->at(0)->thread();189assert(exec_mode == Deoptimization::Unpack_none || (deoptee_thread == thread),190"a frame can only be deoptimized by the owner thread");191192GrowableArray<ScopeValue*>* objects = chunk->at(0)->scope()->objects();193194// The flag return_oop() indicates call sites which return oop195// in compiled code. Such sites include java method calls,196// runtime calls (for example, used to allocate new objects/arrays197// on slow code path) and any other calls generated in compiled code.198// It is not guaranteed that we can get such information here only199// by analyzing bytecode in deoptimized frames. This is why this flag200// is set during method compilation (see Compile::Process_OopMap_Node()).201// If the previous frame was popped or if we are dispatching an exception,202// we don't have an oop result.203bool save_oop_result = chunk->at(0)->scope()->return_oop() && !thread->popframe_forcing_deopt_reexecution() && (exec_mode == Deoptimization::Unpack_deopt);204Handle return_value;205if (save_oop_result) {206// Reallocation may trigger GC. If deoptimization happened on return from207// call which returns oop we need to save it since it is not in oopmap.208oop result = deoptee.saved_oop_result(&map);209assert(oopDesc::is_oop_or_null(result), "must be oop");210return_value = Handle(thread, result);211assert(Universe::heap()->is_in_or_null(result), "must be heap pointer");212if (TraceDeoptimization) {213ttyLocker ttyl;214tty->print_cr("SAVED OOP RESULT " INTPTR_FORMAT " in thread " INTPTR_FORMAT, p2i(result), p2i(thread));215}216}217if (objects != NULL) {218if (exec_mode == Deoptimization::Unpack_none) {219assert(thread->thread_state() == _thread_in_vm, "assumption");220JavaThread* THREAD = thread; // For exception macros.221// Clear pending OOM if reallocation fails and return true indicating allocation failure222realloc_failures = Deoptimization::realloc_objects(thread, &deoptee, &map, objects, CHECK_AND_CLEAR_(true));223deoptimized_objects = true;224} else {225JavaThread* current = thread; // For JRT_BLOCK226JRT_BLOCK227realloc_failures = Deoptimization::realloc_objects(thread, &deoptee, &map, objects, THREAD);228JRT_END229}230bool skip_internal = (compiled_method != NULL) && !compiled_method->is_compiled_by_jvmci();231Deoptimization::reassign_fields(&deoptee, &map, objects, realloc_failures, skip_internal);232#ifndef PRODUCT233if (TraceDeoptimization) {234ttyLocker ttyl;235tty->print_cr("REALLOC OBJECTS in thread " INTPTR_FORMAT, p2i(deoptee_thread));236Deoptimization::print_objects(objects, realloc_failures);237}238#endif239}240if (save_oop_result) {241// Restore result.242deoptee.set_saved_oop_result(&map, return_value());243}244return realloc_failures;245}246247static void restore_eliminated_locks(JavaThread* thread, GrowableArray<compiledVFrame*>* chunk, bool realloc_failures,248frame& deoptee, int exec_mode, bool& deoptimized_objects) {249JavaThread* deoptee_thread = chunk->at(0)->thread();250assert(!EscapeBarrier::objs_are_deoptimized(deoptee_thread, deoptee.id()), "must relock just once");251assert(thread == Thread::current(), "should be");252HandleMark hm(thread);253#ifndef PRODUCT254bool first = true;255#endif256for (int i = 0; i < chunk->length(); i++) {257compiledVFrame* cvf = chunk->at(i);258assert (cvf->scope() != NULL,"expect only compiled java frames");259GrowableArray<MonitorInfo*>* monitors = cvf->monitors();260if (monitors->is_nonempty()) {261bool relocked = Deoptimization::relock_objects(thread, monitors, deoptee_thread, deoptee,262exec_mode, realloc_failures);263deoptimized_objects = deoptimized_objects || relocked;264#ifndef PRODUCT265if (PrintDeoptimizationDetails) {266ttyLocker ttyl;267for (int j = 0; j < monitors->length(); j++) {268MonitorInfo* mi = monitors->at(j);269if (mi->eliminated()) {270if (first) {271first = false;272tty->print_cr("RELOCK OBJECTS in thread " INTPTR_FORMAT, p2i(thread));273}274if (exec_mode == Deoptimization::Unpack_none) {275ObjectMonitor* monitor = deoptee_thread->current_waiting_monitor();276if (monitor != NULL && monitor->object() == mi->owner()) {277tty->print_cr(" object <" INTPTR_FORMAT "> DEFERRED relocking after wait", p2i(mi->owner()));278continue;279}280}281if (mi->owner_is_scalar_replaced()) {282Klass* k = java_lang_Class::as_Klass(mi->owner_klass());283tty->print_cr(" failed reallocation for klass %s", k->external_name());284} else {285tty->print_cr(" object <" INTPTR_FORMAT "> locked", p2i(mi->owner()));286}287}288}289}290#endif // !PRODUCT291}292}293}294295// Deoptimize objects, that is reallocate and relock them, just before they escape through JVMTI.296// The given vframes cover one physical frame.297bool Deoptimization::deoptimize_objects_internal(JavaThread* thread, GrowableArray<compiledVFrame*>* chunk,298bool& realloc_failures) {299frame deoptee = chunk->at(0)->fr();300JavaThread* deoptee_thread = chunk->at(0)->thread();301CompiledMethod* cm = deoptee.cb()->as_compiled_method_or_null();302RegisterMap map(chunk->at(0)->register_map());303bool deoptimized_objects = false;304305bool const jvmci_enabled = JVMCI_ONLY(UseJVMCICompiler) NOT_JVMCI(false);306307// Reallocate the non-escaping objects and restore their fields.308if (jvmci_enabled COMPILER2_PRESENT(|| (DoEscapeAnalysis && EliminateAllocations)309|| EliminateAutoBox || EnableVectorAggressiveReboxing)) {310realloc_failures = rematerialize_objects(thread, Unpack_none, cm, deoptee, map, chunk, deoptimized_objects);311}312313// Revoke biases of objects with eliminated locks in the given frame.314Deoptimization::revoke_for_object_deoptimization(deoptee_thread, deoptee, &map, thread);315316// MonitorInfo structures used in eliminate_locks are not GC safe.317NoSafepointVerifier no_safepoint;318319// Now relock objects if synchronization on them was eliminated.320if (jvmci_enabled COMPILER2_PRESENT(|| ((DoEscapeAnalysis || EliminateNestedLocks) && EliminateLocks))) {321restore_eliminated_locks(thread, chunk, realloc_failures, deoptee, Unpack_none, deoptimized_objects);322}323return deoptimized_objects;324}325#endif // COMPILER2_OR_JVMCI326327// This is factored, since it is both called from a JRT_LEAF (deoptimization) and a JRT_ENTRY (uncommon_trap)328Deoptimization::UnrollBlock* Deoptimization::fetch_unroll_info_helper(JavaThread* current, int exec_mode) {329// When we get here we are about to unwind the deoptee frame. In order to330// catch not yet safe to use frames, the following stack watermark barrier331// poll will make such frames safe to use.332StackWatermarkSet::before_unwind(current);333334// Note: there is a safepoint safety issue here. No matter whether we enter335// via vanilla deopt or uncommon trap we MUST NOT stop at a safepoint once336// the vframeArray is created.337//338339// Allocate our special deoptimization ResourceMark340DeoptResourceMark* dmark = new DeoptResourceMark(current);341assert(current->deopt_mark() == NULL, "Pending deopt!");342current->set_deopt_mark(dmark);343344frame stub_frame = current->last_frame(); // Makes stack walkable as side effect345RegisterMap map(current, true);346RegisterMap dummy_map(current, false);347// Now get the deoptee with a valid map348frame deoptee = stub_frame.sender(&map);349// Set the deoptee nmethod350assert(current->deopt_compiled_method() == NULL, "Pending deopt!");351CompiledMethod* cm = deoptee.cb()->as_compiled_method_or_null();352current->set_deopt_compiled_method(cm);353354if (VerifyStack) {355current->validate_frame_layout();356}357358// Create a growable array of VFrames where each VFrame represents an inlined359// Java frame. This storage is allocated with the usual system arena.360assert(deoptee.is_compiled_frame(), "Wrong frame type");361GrowableArray<compiledVFrame*>* chunk = new GrowableArray<compiledVFrame*>(10);362vframe* vf = vframe::new_vframe(&deoptee, &map, current);363while (!vf->is_top()) {364assert(vf->is_compiled_frame(), "Wrong frame type");365chunk->push(compiledVFrame::cast(vf));366vf = vf->sender();367}368assert(vf->is_compiled_frame(), "Wrong frame type");369chunk->push(compiledVFrame::cast(vf));370371bool realloc_failures = false;372373#if COMPILER2_OR_JVMCI374bool const jvmci_enabled = JVMCI_ONLY(EnableJVMCI) NOT_JVMCI(false);375376// Reallocate the non-escaping objects and restore their fields. Then377// relock objects if synchronization on them was eliminated.378if (jvmci_enabled COMPILER2_PRESENT( || (DoEscapeAnalysis && EliminateAllocations)379|| EliminateAutoBox || EnableVectorAggressiveReboxing )) {380bool unused;381realloc_failures = rematerialize_objects(current, exec_mode, cm, deoptee, map, chunk, unused);382}383#endif // COMPILER2_OR_JVMCI384385// Revoke biases, done with in java state.386// No safepoints allowed after this387revoke_from_deopt_handler(current, deoptee, &map);388389// Ensure that no safepoint is taken after pointers have been stored390// in fields of rematerialized objects. If a safepoint occurs from here on391// out the java state residing in the vframeArray will be missed.392// Locks may be rebaised in a safepoint.393NoSafepointVerifier no_safepoint;394395#if COMPILER2_OR_JVMCI396if ((jvmci_enabled COMPILER2_PRESENT( || ((DoEscapeAnalysis || EliminateNestedLocks) && EliminateLocks) ))397&& !EscapeBarrier::objs_are_deoptimized(current, deoptee.id())) {398bool unused;399restore_eliminated_locks(current, chunk, realloc_failures, deoptee, exec_mode, unused);400}401#endif // COMPILER2_OR_JVMCI402403ScopeDesc* trap_scope = chunk->at(0)->scope();404Handle exceptionObject;405if (trap_scope->rethrow_exception()) {406if (PrintDeoptimizationDetails) {407tty->print_cr("Exception to be rethrown in the interpreter for method %s::%s at bci %d", trap_scope->method()->method_holder()->name()->as_C_string(), trap_scope->method()->name()->as_C_string(), trap_scope->bci());408}409GrowableArray<ScopeValue*>* expressions = trap_scope->expressions();410guarantee(expressions != NULL && expressions->length() > 0, "must have exception to throw");411ScopeValue* topOfStack = expressions->top();412exceptionObject = StackValue::create_stack_value(&deoptee, &map, topOfStack)->get_obj();413guarantee(exceptionObject() != NULL, "exception oop can not be null");414}415416vframeArray* array = create_vframeArray(current, deoptee, &map, chunk, realloc_failures);417#if COMPILER2_OR_JVMCI418if (realloc_failures) {419pop_frames_failed_reallocs(current, array);420}421#endif422423assert(current->vframe_array_head() == NULL, "Pending deopt!");424current->set_vframe_array_head(array);425426// Now that the vframeArray has been created if we have any deferred local writes427// added by jvmti then we can free up that structure as the data is now in the428// vframeArray429430JvmtiDeferredUpdates::delete_updates_for_frame(current, array->original().id());431432// Compute the caller frame based on the sender sp of stub_frame and stored frame sizes info.433CodeBlob* cb = stub_frame.cb();434// Verify we have the right vframeArray435assert(cb->frame_size() >= 0, "Unexpected frame size");436intptr_t* unpack_sp = stub_frame.sp() + cb->frame_size();437438// If the deopt call site is a MethodHandle invoke call site we have439// to adjust the unpack_sp.440nmethod* deoptee_nm = deoptee.cb()->as_nmethod_or_null();441if (deoptee_nm != NULL && deoptee_nm->is_method_handle_return(deoptee.pc()))442unpack_sp = deoptee.unextended_sp();443444#ifdef ASSERT445assert(cb->is_deoptimization_stub() ||446cb->is_uncommon_trap_stub() ||447strcmp("Stub<DeoptimizationStub.deoptimizationHandler>", cb->name()) == 0 ||448strcmp("Stub<UncommonTrapStub.uncommonTrapHandler>", cb->name()) == 0,449"unexpected code blob: %s", cb->name());450#endif451452// This is a guarantee instead of an assert because if vframe doesn't match453// we will unpack the wrong deoptimized frame and wind up in strange places454// where it will be very difficult to figure out what went wrong. Better455// to die an early death here than some very obscure death later when the456// trail is cold.457// Note: on ia64 this guarantee can be fooled by frames with no memory stack458// in that it will fail to detect a problem when there is one. This needs459// more work in tiger timeframe.460guarantee(array->unextended_sp() == unpack_sp, "vframe_array_head must contain the vframeArray to unpack");461462int number_of_frames = array->frames();463464// Compute the vframes' sizes. Note that frame_sizes[] entries are ordered from outermost to innermost465// virtual activation, which is the reverse of the elements in the vframes array.466intptr_t* frame_sizes = NEW_C_HEAP_ARRAY(intptr_t, number_of_frames, mtCompiler);467// +1 because we always have an interpreter return address for the final slot.468address* frame_pcs = NEW_C_HEAP_ARRAY(address, number_of_frames + 1, mtCompiler);469int popframe_extra_args = 0;470// Create an interpreter return address for the stub to use as its return471// address so the skeletal frames are perfectly walkable472frame_pcs[number_of_frames] = Interpreter::deopt_entry(vtos, 0);473474// PopFrame requires that the preserved incoming arguments from the recently-popped topmost475// activation be put back on the expression stack of the caller for reexecution476if (JvmtiExport::can_pop_frame() && current->popframe_forcing_deopt_reexecution()) {477popframe_extra_args = in_words(current->popframe_preserved_args_size_in_words());478}479480// Find the current pc for sender of the deoptee. Since the sender may have been deoptimized481// itself since the deoptee vframeArray was created we must get a fresh value of the pc rather482// than simply use array->sender.pc(). This requires us to walk the current set of frames483//484frame deopt_sender = stub_frame.sender(&dummy_map); // First is the deoptee frame485deopt_sender = deopt_sender.sender(&dummy_map); // Now deoptee caller486487// It's possible that the number of parameters at the call site is488// different than number of arguments in the callee when method489// handles are used. If the caller is interpreted get the real490// value so that the proper amount of space can be added to it's491// frame.492bool caller_was_method_handle = false;493if (deopt_sender.is_interpreted_frame()) {494methodHandle method(current, deopt_sender.interpreter_frame_method());495Bytecode_invoke cur = Bytecode_invoke_check(method, deopt_sender.interpreter_frame_bci());496if (cur.is_invokedynamic() || cur.is_invokehandle()) {497// Method handle invokes may involve fairly arbitrary chains of498// calls so it's impossible to know how much actual space the499// caller has for locals.500caller_was_method_handle = true;501}502}503504//505// frame_sizes/frame_pcs[0] oldest frame (int or c2i)506// frame_sizes/frame_pcs[1] next oldest frame (int)507// frame_sizes/frame_pcs[n] youngest frame (int)508//509// Now a pc in frame_pcs is actually the return address to the frame's caller (a frame510// owns the space for the return address to it's caller). Confusing ain't it.511//512// The vframe array can address vframes with indices running from513// 0.._frames-1. Index 0 is the youngest frame and _frame - 1 is the oldest (root) frame.514// When we create the skeletal frames we need the oldest frame to be in the zero slot515// in the frame_sizes/frame_pcs so the assembly code can do a trivial walk.516// so things look a little strange in this loop.517//518int callee_parameters = 0;519int callee_locals = 0;520for (int index = 0; index < array->frames(); index++ ) {521// frame[number_of_frames - 1 ] = on_stack_size(youngest)522// frame[number_of_frames - 2 ] = on_stack_size(sender(youngest))523// frame[number_of_frames - 3 ] = on_stack_size(sender(sender(youngest)))524frame_sizes[number_of_frames - 1 - index] = BytesPerWord * array->element(index)->on_stack_size(callee_parameters,525callee_locals,526index == 0,527popframe_extra_args);528// This pc doesn't have to be perfect just good enough to identify the frame529// as interpreted so the skeleton frame will be walkable530// The correct pc will be set when the skeleton frame is completely filled out531// The final pc we store in the loop is wrong and will be overwritten below532frame_pcs[number_of_frames - 1 - index ] = Interpreter::deopt_entry(vtos, 0) - frame::pc_return_offset;533534callee_parameters = array->element(index)->method()->size_of_parameters();535callee_locals = array->element(index)->method()->max_locals();536popframe_extra_args = 0;537}538539// Compute whether the root vframe returns a float or double value.540BasicType return_type;541{542methodHandle method(current, array->element(0)->method());543Bytecode_invoke invoke = Bytecode_invoke_check(method, array->element(0)->bci());544return_type = invoke.is_valid() ? invoke.result_type() : T_ILLEGAL;545}546547// Compute information for handling adapters and adjusting the frame size of the caller.548int caller_adjustment = 0;549550// Compute the amount the oldest interpreter frame will have to adjust551// its caller's stack by. If the caller is a compiled frame then552// we pretend that the callee has no parameters so that the553// extension counts for the full amount of locals and not just554// locals-parms. This is because without a c2i adapter the parm555// area as created by the compiled frame will not be usable by556// the interpreter. (Depending on the calling convention there557// may not even be enough space).558559// QQQ I'd rather see this pushed down into last_frame_adjust560// and have it take the sender (aka caller).561562if (deopt_sender.is_compiled_frame() || caller_was_method_handle) {563caller_adjustment = last_frame_adjust(0, callee_locals);564} else if (callee_locals > callee_parameters) {565// The caller frame may need extending to accommodate566// non-parameter locals of the first unpacked interpreted frame.567// Compute that adjustment.568caller_adjustment = last_frame_adjust(callee_parameters, callee_locals);569}570571// If the sender is deoptimized the we must retrieve the address of the handler572// since the frame will "magically" show the original pc before the deopt573// and we'd undo the deopt.574575frame_pcs[0] = deopt_sender.raw_pc();576577assert(CodeCache::find_blob_unsafe(frame_pcs[0]) != NULL, "bad pc");578579#if INCLUDE_JVMCI580if (exceptionObject() != NULL) {581current->set_exception_oop(exceptionObject());582exec_mode = Unpack_exception;583}584#endif585586if (current->frames_to_pop_failed_realloc() > 0 && exec_mode != Unpack_uncommon_trap) {587assert(current->has_pending_exception(), "should have thrown OOME");588current->set_exception_oop(current->pending_exception());589current->clear_pending_exception();590exec_mode = Unpack_exception;591}592593#if INCLUDE_JVMCI594if (current->frames_to_pop_failed_realloc() > 0) {595current->set_pending_monitorenter(false);596}597#endif598599UnrollBlock* info = new UnrollBlock(array->frame_size() * BytesPerWord,600caller_adjustment * BytesPerWord,601caller_was_method_handle ? 0 : callee_parameters,602number_of_frames,603frame_sizes,604frame_pcs,605return_type,606exec_mode);607// On some platforms, we need a way to pass some platform dependent608// information to the unpacking code so the skeletal frames come out609// correct (initial fp value, unextended sp, ...)610info->set_initial_info((intptr_t) array->sender().initial_deoptimization_info());611612if (array->frames() > 1) {613if (VerifyStack && TraceDeoptimization) {614ttyLocker ttyl;615tty->print_cr("Deoptimizing method containing inlining");616}617}618619array->set_unroll_block(info);620return info;621}622623// Called to cleanup deoptimization data structures in normal case624// after unpacking to stack and when stack overflow error occurs625void Deoptimization::cleanup_deopt_info(JavaThread *thread,626vframeArray *array) {627628// Get array if coming from exception629if (array == NULL) {630array = thread->vframe_array_head();631}632thread->set_vframe_array_head(NULL);633634// Free the previous UnrollBlock635vframeArray* old_array = thread->vframe_array_last();636thread->set_vframe_array_last(array);637638if (old_array != NULL) {639UnrollBlock* old_info = old_array->unroll_block();640old_array->set_unroll_block(NULL);641delete old_info;642delete old_array;643}644645// Deallocate any resource creating in this routine and any ResourceObjs allocated646// inside the vframeArray (StackValueCollections)647648delete thread->deopt_mark();649thread->set_deopt_mark(NULL);650thread->set_deopt_compiled_method(NULL);651652653if (JvmtiExport::can_pop_frame()) {654// Regardless of whether we entered this routine with the pending655// popframe condition bit set, we should always clear it now656thread->clear_popframe_condition();657}658659// unpack_frames() is called at the end of the deoptimization handler660// and (in C2) at the end of the uncommon trap handler. Note this fact661// so that an asynchronous stack walker can work again. This counter is662// incremented at the beginning of fetch_unroll_info() and (in C2) at663// the beginning of uncommon_trap().664thread->dec_in_deopt_handler();665}666667// Moved from cpu directories because none of the cpus has callee save values.668// If a cpu implements callee save values, move this to deoptimization_<cpu>.cpp.669void Deoptimization::unwind_callee_save_values(frame* f, vframeArray* vframe_array) {670671// This code is sort of the equivalent of C2IAdapter::setup_stack_frame back in672// the days we had adapter frames. When we deoptimize a situation where a673// compiled caller calls a compiled caller will have registers it expects674// to survive the call to the callee. If we deoptimize the callee the only675// way we can restore these registers is to have the oldest interpreter676// frame that we create restore these values. That is what this routine677// will accomplish.678679// At the moment we have modified c2 to not have any callee save registers680// so this problem does not exist and this routine is just a place holder.681682assert(f->is_interpreted_frame(), "must be interpreted");683}684685// Return BasicType of value being returned686JRT_LEAF(BasicType, Deoptimization::unpack_frames(JavaThread* thread, int exec_mode))687688// We are already active in the special DeoptResourceMark any ResourceObj's we689// allocate will be freed at the end of the routine.690691// JRT_LEAF methods don't normally allocate handles and there is a692// NoHandleMark to enforce that. It is actually safe to use Handles693// in a JRT_LEAF method, and sometimes desirable, but to do so we694// must use ResetNoHandleMark to bypass the NoHandleMark, and695// then use a HandleMark to ensure any Handles we do create are696// cleaned up in this scope.697ResetNoHandleMark rnhm;698HandleMark hm(thread);699700frame stub_frame = thread->last_frame();701702// Since the frame to unpack is the top frame of this thread, the vframe_array_head703// must point to the vframeArray for the unpack frame.704vframeArray* array = thread->vframe_array_head();705706#ifndef PRODUCT707if (TraceDeoptimization) {708ttyLocker ttyl;709tty->print_cr("DEOPT UNPACKING thread " INTPTR_FORMAT " vframeArray " INTPTR_FORMAT " mode %d",710p2i(thread), p2i(array), exec_mode);711}712#endif713Events::log_deopt_message(thread, "DEOPT UNPACKING pc=" INTPTR_FORMAT " sp=" INTPTR_FORMAT " mode %d",714p2i(stub_frame.pc()), p2i(stub_frame.sp()), exec_mode);715716UnrollBlock* info = array->unroll_block();717718// We set the last_Java frame. But the stack isn't really parsable here. So we719// clear it to make sure JFR understands not to try and walk stacks from events720// in here.721intptr_t* sp = thread->frame_anchor()->last_Java_sp();722thread->frame_anchor()->set_last_Java_sp(NULL);723724// Unpack the interpreter frames and any adapter frame (c2 only) we might create.725array->unpack_to_stack(stub_frame, exec_mode, info->caller_actual_parameters());726727thread->frame_anchor()->set_last_Java_sp(sp);728729BasicType bt = info->return_type();730731// If we have an exception pending, claim that the return type is an oop732// so the deopt_blob does not overwrite the exception_oop.733734if (exec_mode == Unpack_exception)735bt = T_OBJECT;736737// Cleanup thread deopt data738cleanup_deopt_info(thread, array);739740#ifndef PRODUCT741if (VerifyStack) {742ResourceMark res_mark;743// Clear pending exception to not break verification code (restored afterwards)744PreserveExceptionMark pm(thread);745746thread->validate_frame_layout();747748// Verify that the just-unpacked frames match the interpreter's749// notions of expression stack and locals750vframeArray* cur_array = thread->vframe_array_last();751RegisterMap rm(thread, false);752rm.set_include_argument_oops(false);753bool is_top_frame = true;754int callee_size_of_parameters = 0;755int callee_max_locals = 0;756for (int i = 0; i < cur_array->frames(); i++) {757vframeArrayElement* el = cur_array->element(i);758frame* iframe = el->iframe();759guarantee(iframe->is_interpreted_frame(), "Wrong frame type");760761// Get the oop map for this bci762InterpreterOopMap mask;763int cur_invoke_parameter_size = 0;764bool try_next_mask = false;765int next_mask_expression_stack_size = -1;766int top_frame_expression_stack_adjustment = 0;767methodHandle mh(thread, iframe->interpreter_frame_method());768OopMapCache::compute_one_oop_map(mh, iframe->interpreter_frame_bci(), &mask);769BytecodeStream str(mh, iframe->interpreter_frame_bci());770int max_bci = mh->code_size();771// Get to the next bytecode if possible772assert(str.bci() < max_bci, "bci in interpreter frame out of bounds");773// Check to see if we can grab the number of outgoing arguments774// at an uncommon trap for an invoke (where the compiler775// generates debug info before the invoke has executed)776Bytecodes::Code cur_code = str.next();777if (Bytecodes::is_invoke(cur_code)) {778Bytecode_invoke invoke(mh, iframe->interpreter_frame_bci());779cur_invoke_parameter_size = invoke.size_of_parameters();780if (i != 0 && !invoke.is_invokedynamic() && MethodHandles::has_member_arg(invoke.klass(), invoke.name())) {781callee_size_of_parameters++;782}783}784if (str.bci() < max_bci) {785Bytecodes::Code next_code = str.next();786if (next_code >= 0) {787// The interpreter oop map generator reports results before788// the current bytecode has executed except in the case of789// calls. It seems to be hard to tell whether the compiler790// has emitted debug information matching the "state before"791// a given bytecode or the state after, so we try both792if (!Bytecodes::is_invoke(cur_code) && cur_code != Bytecodes::_athrow) {793// Get expression stack size for the next bytecode794InterpreterOopMap next_mask;795OopMapCache::compute_one_oop_map(mh, str.bci(), &next_mask);796next_mask_expression_stack_size = next_mask.expression_stack_size();797if (Bytecodes::is_invoke(next_code)) {798Bytecode_invoke invoke(mh, str.bci());799next_mask_expression_stack_size += invoke.size_of_parameters();800}801// Need to subtract off the size of the result type of802// the bytecode because this is not described in the803// debug info but returned to the interpreter in the TOS804// caching register805BasicType bytecode_result_type = Bytecodes::result_type(cur_code);806if (bytecode_result_type != T_ILLEGAL) {807top_frame_expression_stack_adjustment = type2size[bytecode_result_type];808}809assert(top_frame_expression_stack_adjustment >= 0, "stack adjustment must be positive");810try_next_mask = true;811}812}813}814815// Verify stack depth and oops in frame816// This assertion may be dependent on the platform we're running on and may need modification (tested on x86 and sparc)817if (!(818/* SPARC */819(iframe->interpreter_frame_expression_stack_size() == mask.expression_stack_size() + callee_size_of_parameters) ||820/* x86 */821(iframe->interpreter_frame_expression_stack_size() == mask.expression_stack_size() + callee_max_locals) ||822(try_next_mask &&823(iframe->interpreter_frame_expression_stack_size() == (next_mask_expression_stack_size -824top_frame_expression_stack_adjustment))) ||825(is_top_frame && (exec_mode == Unpack_exception) && iframe->interpreter_frame_expression_stack_size() == 0) ||826(is_top_frame && (exec_mode == Unpack_uncommon_trap || exec_mode == Unpack_reexecute || el->should_reexecute()) &&827(iframe->interpreter_frame_expression_stack_size() == mask.expression_stack_size() + cur_invoke_parameter_size))828)) {829{830ttyLocker ttyl;831832// Print out some information that will help us debug the problem833tty->print_cr("Wrong number of expression stack elements during deoptimization");834tty->print_cr(" Error occurred while verifying frame %d (0..%d, 0 is topmost)", i, cur_array->frames() - 1);835tty->print_cr(" Fabricated interpreter frame had %d expression stack elements",836iframe->interpreter_frame_expression_stack_size());837tty->print_cr(" Interpreter oop map had %d expression stack elements", mask.expression_stack_size());838tty->print_cr(" try_next_mask = %d", try_next_mask);839tty->print_cr(" next_mask_expression_stack_size = %d", next_mask_expression_stack_size);840tty->print_cr(" callee_size_of_parameters = %d", callee_size_of_parameters);841tty->print_cr(" callee_max_locals = %d", callee_max_locals);842tty->print_cr(" top_frame_expression_stack_adjustment = %d", top_frame_expression_stack_adjustment);843tty->print_cr(" exec_mode = %d", exec_mode);844tty->print_cr(" cur_invoke_parameter_size = %d", cur_invoke_parameter_size);845tty->print_cr(" Thread = " INTPTR_FORMAT ", thread ID = %d", p2i(thread), thread->osthread()->thread_id());846tty->print_cr(" Interpreted frames:");847for (int k = 0; k < cur_array->frames(); k++) {848vframeArrayElement* el = cur_array->element(k);849tty->print_cr(" %s (bci %d)", el->method()->name_and_sig_as_C_string(), el->bci());850}851cur_array->print_on_2(tty);852} // release tty lock before calling guarantee853guarantee(false, "wrong number of expression stack elements during deopt");854}855VerifyOopClosure verify;856iframe->oops_interpreted_do(&verify, &rm, false);857callee_size_of_parameters = mh->size_of_parameters();858callee_max_locals = mh->max_locals();859is_top_frame = false;860}861}862#endif /* !PRODUCT */863864return bt;865JRT_END866867class DeoptimizeMarkedClosure : public HandshakeClosure {868public:869DeoptimizeMarkedClosure() : HandshakeClosure("Deoptimize") {}870void do_thread(Thread* thread) {871JavaThread* jt = thread->as_Java_thread();872jt->deoptimize_marked_methods();873}874};875876void Deoptimization::deoptimize_all_marked(nmethod* nmethod_only) {877ResourceMark rm;878DeoptimizationMarker dm;879880// Make the dependent methods not entrant881if (nmethod_only != NULL) {882nmethod_only->mark_for_deoptimization();883nmethod_only->make_not_entrant();884} else {885MutexLocker mu(SafepointSynchronize::is_at_safepoint() ? NULL : CodeCache_lock, Mutex::_no_safepoint_check_flag);886CodeCache::make_marked_nmethods_not_entrant();887}888889DeoptimizeMarkedClosure deopt;890if (SafepointSynchronize::is_at_safepoint()) {891Threads::java_threads_do(&deopt);892} else {893Handshake::execute(&deopt);894}895}896897Deoptimization::DeoptAction Deoptimization::_unloaded_action898= Deoptimization::Action_reinterpret;899900#if COMPILER2_OR_JVMCI901template<typename CacheType>902class BoxCacheBase : public CHeapObj<mtCompiler> {903protected:904static InstanceKlass* find_cache_klass(Symbol* klass_name) {905ResourceMark rm;906char* klass_name_str = klass_name->as_C_string();907InstanceKlass* ik = SystemDictionary::find_instance_klass(klass_name, Handle(), Handle());908guarantee(ik != NULL, "%s must be loaded", klass_name_str);909guarantee(ik->is_initialized(), "%s must be initialized", klass_name_str);910CacheType::compute_offsets(ik);911return ik;912}913};914915template<typename PrimitiveType, typename CacheType, typename BoxType> class BoxCache : public BoxCacheBase<CacheType> {916PrimitiveType _low;917PrimitiveType _high;918jobject _cache;919protected:920static BoxCache<PrimitiveType, CacheType, BoxType> *_singleton;921BoxCache(Thread* thread) {922InstanceKlass* ik = BoxCacheBase<CacheType>::find_cache_klass(CacheType::symbol());923objArrayOop cache = CacheType::cache(ik);924assert(cache->length() > 0, "Empty cache");925_low = BoxType::value(cache->obj_at(0));926_high = _low + cache->length() - 1;927_cache = JNIHandles::make_global(Handle(thread, cache));928}929~BoxCache() {930JNIHandles::destroy_global(_cache);931}932public:933static BoxCache<PrimitiveType, CacheType, BoxType>* singleton(Thread* thread) {934if (_singleton == NULL) {935BoxCache<PrimitiveType, CacheType, BoxType>* s = new BoxCache<PrimitiveType, CacheType, BoxType>(thread);936if (!Atomic::replace_if_null(&_singleton, s)) {937delete s;938}939}940return _singleton;941}942oop lookup(PrimitiveType value) {943if (_low <= value && value <= _high) {944int offset = value - _low;945return objArrayOop(JNIHandles::resolve_non_null(_cache))->obj_at(offset);946}947return NULL;948}949oop lookup_raw(intptr_t raw_value) {950// Have to cast to avoid little/big-endian problems.951if (sizeof(PrimitiveType) > sizeof(jint)) {952jlong value = (jlong)raw_value;953return lookup(value);954}955PrimitiveType value = (PrimitiveType)*((jint*)&raw_value);956return lookup(value);957}958};959960typedef BoxCache<jint, java_lang_Integer_IntegerCache, java_lang_Integer> IntegerBoxCache;961typedef BoxCache<jlong, java_lang_Long_LongCache, java_lang_Long> LongBoxCache;962typedef BoxCache<jchar, java_lang_Character_CharacterCache, java_lang_Character> CharacterBoxCache;963typedef BoxCache<jshort, java_lang_Short_ShortCache, java_lang_Short> ShortBoxCache;964typedef BoxCache<jbyte, java_lang_Byte_ByteCache, java_lang_Byte> ByteBoxCache;965966template<> BoxCache<jint, java_lang_Integer_IntegerCache, java_lang_Integer>* BoxCache<jint, java_lang_Integer_IntegerCache, java_lang_Integer>::_singleton = NULL;967template<> BoxCache<jlong, java_lang_Long_LongCache, java_lang_Long>* BoxCache<jlong, java_lang_Long_LongCache, java_lang_Long>::_singleton = NULL;968template<> BoxCache<jchar, java_lang_Character_CharacterCache, java_lang_Character>* BoxCache<jchar, java_lang_Character_CharacterCache, java_lang_Character>::_singleton = NULL;969template<> BoxCache<jshort, java_lang_Short_ShortCache, java_lang_Short>* BoxCache<jshort, java_lang_Short_ShortCache, java_lang_Short>::_singleton = NULL;970template<> BoxCache<jbyte, java_lang_Byte_ByteCache, java_lang_Byte>* BoxCache<jbyte, java_lang_Byte_ByteCache, java_lang_Byte>::_singleton = NULL;971972class BooleanBoxCache : public BoxCacheBase<java_lang_Boolean> {973jobject _true_cache;974jobject _false_cache;975protected:976static BooleanBoxCache *_singleton;977BooleanBoxCache(Thread *thread) {978InstanceKlass* ik = find_cache_klass(java_lang_Boolean::symbol());979_true_cache = JNIHandles::make_global(Handle(thread, java_lang_Boolean::get_TRUE(ik)));980_false_cache = JNIHandles::make_global(Handle(thread, java_lang_Boolean::get_FALSE(ik)));981}982~BooleanBoxCache() {983JNIHandles::destroy_global(_true_cache);984JNIHandles::destroy_global(_false_cache);985}986public:987static BooleanBoxCache* singleton(Thread* thread) {988if (_singleton == NULL) {989BooleanBoxCache* s = new BooleanBoxCache(thread);990if (!Atomic::replace_if_null(&_singleton, s)) {991delete s;992}993}994return _singleton;995}996oop lookup_raw(intptr_t raw_value) {997// Have to cast to avoid little/big-endian problems.998jboolean value = (jboolean)*((jint*)&raw_value);999return lookup(value);1000}1001oop lookup(jboolean value) {1002if (value != 0) {1003return JNIHandles::resolve_non_null(_true_cache);1004}1005return JNIHandles::resolve_non_null(_false_cache);1006}1007};10081009BooleanBoxCache* BooleanBoxCache::_singleton = NULL;10101011oop Deoptimization::get_cached_box(AutoBoxObjectValue* bv, frame* fr, RegisterMap* reg_map, TRAPS) {1012Klass* k = java_lang_Class::as_Klass(bv->klass()->as_ConstantOopReadValue()->value()());1013BasicType box_type = vmClasses::box_klass_type(k);1014if (box_type != T_OBJECT) {1015StackValue* value = StackValue::create_stack_value(fr, reg_map, bv->field_at(box_type == T_LONG ? 1 : 0));1016switch(box_type) {1017case T_INT: return IntegerBoxCache::singleton(THREAD)->lookup_raw(value->get_int());1018case T_CHAR: return CharacterBoxCache::singleton(THREAD)->lookup_raw(value->get_int());1019case T_SHORT: return ShortBoxCache::singleton(THREAD)->lookup_raw(value->get_int());1020case T_BYTE: return ByteBoxCache::singleton(THREAD)->lookup_raw(value->get_int());1021case T_BOOLEAN: return BooleanBoxCache::singleton(THREAD)->lookup_raw(value->get_int());1022case T_LONG: return LongBoxCache::singleton(THREAD)->lookup_raw(value->get_int());1023default:;1024}1025}1026return NULL;1027}10281029bool Deoptimization::realloc_objects(JavaThread* thread, frame* fr, RegisterMap* reg_map, GrowableArray<ScopeValue*>* objects, TRAPS) {1030Handle pending_exception(THREAD, thread->pending_exception());1031const char* exception_file = thread->exception_file();1032int exception_line = thread->exception_line();1033thread->clear_pending_exception();10341035bool failures = false;10361037for (int i = 0; i < objects->length(); i++) {1038assert(objects->at(i)->is_object(), "invalid debug information");1039ObjectValue* sv = (ObjectValue*) objects->at(i);10401041Klass* k = java_lang_Class::as_Klass(sv->klass()->as_ConstantOopReadValue()->value()());1042oop obj = NULL;10431044if (k->is_instance_klass()) {1045if (sv->is_auto_box()) {1046AutoBoxObjectValue* abv = (AutoBoxObjectValue*) sv;1047obj = get_cached_box(abv, fr, reg_map, THREAD);1048if (obj != NULL) {1049// Set the flag to indicate the box came from a cache, so that we can skip the field reassignment for it.1050abv->set_cached(true);1051}1052}10531054InstanceKlass* ik = InstanceKlass::cast(k);1055if (obj == NULL) {1056#ifdef COMPILER21057if (EnableVectorSupport && VectorSupport::is_vector(ik)) {1058obj = VectorSupport::allocate_vector(ik, fr, reg_map, sv, THREAD);1059} else {1060obj = ik->allocate_instance(THREAD);1061}1062#else1063obj = ik->allocate_instance(THREAD);1064#endif // COMPILER21065}1066} else if (k->is_typeArray_klass()) {1067TypeArrayKlass* ak = TypeArrayKlass::cast(k);1068assert(sv->field_size() % type2size[ak->element_type()] == 0, "non-integral array length");1069int len = sv->field_size() / type2size[ak->element_type()];1070obj = ak->allocate(len, THREAD);1071} else if (k->is_objArray_klass()) {1072ObjArrayKlass* ak = ObjArrayKlass::cast(k);1073obj = ak->allocate(sv->field_size(), THREAD);1074}10751076if (obj == NULL) {1077failures = true;1078}10791080assert(sv->value().is_null(), "redundant reallocation");1081assert(obj != NULL || HAS_PENDING_EXCEPTION, "allocation should succeed or we should get an exception");1082CLEAR_PENDING_EXCEPTION;1083sv->set_value(obj);1084}10851086if (failures) {1087THROW_OOP_(Universe::out_of_memory_error_realloc_objects(), failures);1088} else if (pending_exception.not_null()) {1089thread->set_pending_exception(pending_exception(), exception_file, exception_line);1090}10911092return failures;1093}10941095#if INCLUDE_JVMCI1096/**1097* For primitive types whose kind gets "erased" at runtime (shorts become stack ints),1098* we need to somehow be able to recover the actual kind to be able to write the correct1099* amount of bytes.1100* For that purpose, this method assumes that, for an entry spanning n bytes at index i,1101* the entries at index n + 1 to n + i are 'markers'.1102* For example, if we were writing a short at index 4 of a byte array of size 8, the1103* expected form of the array would be:1104*1105* {b0, b1, b2, b3, INT, marker, b6, b7}1106*1107* Thus, in order to get back the size of the entry, we simply need to count the number1108* of marked entries1109*1110* @param virtualArray the virtualized byte array1111* @param i index of the virtual entry we are recovering1112* @return The number of bytes the entry spans1113*/1114static int count_number_of_bytes_for_entry(ObjectValue *virtualArray, int i) {1115int index = i;1116while (++index < virtualArray->field_size() &&1117virtualArray->field_at(index)->is_marker()) {}1118return index - i;1119}11201121/**1122* If there was a guarantee for byte array to always start aligned to a long, we could1123* do a simple check on the parity of the index. Unfortunately, that is not always the1124* case. Thus, we check alignment of the actual address we are writing to.1125* In the unlikely case index 0 is 5-aligned for example, it would then be possible to1126* write a long to index 3.1127*/1128static jbyte* check_alignment_get_addr(typeArrayOop obj, int index, int expected_alignment) {1129jbyte* res = obj->byte_at_addr(index);1130assert((((intptr_t) res) % expected_alignment) == 0, "Non-aligned write");1131return res;1132}11331134static void byte_array_put(typeArrayOop obj, intptr_t val, int index, int byte_count) {1135switch (byte_count) {1136case 1:1137obj->byte_at_put(index, (jbyte) *((jint *) &val));1138break;1139case 2:1140*((jshort *) check_alignment_get_addr(obj, index, 2)) = (jshort) *((jint *) &val);1141break;1142case 4:1143*((jint *) check_alignment_get_addr(obj, index, 4)) = (jint) *((jint *) &val);1144break;1145case 8:1146*((jlong *) check_alignment_get_addr(obj, index, 8)) = (jlong) *((jlong *) &val);1147break;1148default:1149ShouldNotReachHere();1150}1151}1152#endif // INCLUDE_JVMCI115311541155// restore elements of an eliminated type array1156void Deoptimization::reassign_type_array_elements(frame* fr, RegisterMap* reg_map, ObjectValue* sv, typeArrayOop obj, BasicType type) {1157int index = 0;1158intptr_t val;11591160for (int i = 0; i < sv->field_size(); i++) {1161StackValue* value = StackValue::create_stack_value(fr, reg_map, sv->field_at(i));1162switch(type) {1163case T_LONG: case T_DOUBLE: {1164assert(value->type() == T_INT, "Agreement.");1165StackValue* low =1166StackValue::create_stack_value(fr, reg_map, sv->field_at(++i));1167#ifdef _LP641168jlong res = (jlong)low->get_int();1169#else1170jlong res = jlong_from((jint)value->get_int(), (jint)low->get_int());1171#endif1172obj->long_at_put(index, res);1173break;1174}11751176// Have to cast to INT (32 bits) pointer to avoid little/big-endian problem.1177case T_INT: case T_FLOAT: { // 4 bytes.1178assert(value->type() == T_INT, "Agreement.");1179bool big_value = false;1180if (i + 1 < sv->field_size() && type == T_INT) {1181if (sv->field_at(i)->is_location()) {1182Location::Type type = ((LocationValue*) sv->field_at(i))->location().type();1183if (type == Location::dbl || type == Location::lng) {1184big_value = true;1185}1186} else if (sv->field_at(i)->is_constant_int()) {1187ScopeValue* next_scope_field = sv->field_at(i + 1);1188if (next_scope_field->is_constant_long() || next_scope_field->is_constant_double()) {1189big_value = true;1190}1191}1192}11931194if (big_value) {1195StackValue* low = StackValue::create_stack_value(fr, reg_map, sv->field_at(++i));1196#ifdef _LP641197jlong res = (jlong)low->get_int();1198#else1199jlong res = jlong_from((jint)value->get_int(), (jint)low->get_int());1200#endif1201obj->int_at_put(index, (jint)*((jint*)&res));1202obj->int_at_put(++index, (jint)*(((jint*)&res) + 1));1203} else {1204val = value->get_int();1205obj->int_at_put(index, (jint)*((jint*)&val));1206}1207break;1208}12091210case T_SHORT:1211assert(value->type() == T_INT, "Agreement.");1212val = value->get_int();1213obj->short_at_put(index, (jshort)*((jint*)&val));1214break;12151216case T_CHAR:1217assert(value->type() == T_INT, "Agreement.");1218val = value->get_int();1219obj->char_at_put(index, (jchar)*((jint*)&val));1220break;12211222case T_BYTE: {1223assert(value->type() == T_INT, "Agreement.");1224// The value we get is erased as a regular int. We will need to find its actual byte count 'by hand'.1225val = value->get_int();1226#if INCLUDE_JVMCI1227int byte_count = count_number_of_bytes_for_entry(sv, i);1228byte_array_put(obj, val, index, byte_count);1229// According to byte_count contract, the values from i + 1 to i + byte_count are illegal values. Skip.1230i += byte_count - 1; // Balance the loop counter.1231index += byte_count;1232// index has been updated so continue at top of loop1233continue;1234#else1235obj->byte_at_put(index, (jbyte)*((jint*)&val));1236break;1237#endif // INCLUDE_JVMCI1238}12391240case T_BOOLEAN: {1241assert(value->type() == T_INT, "Agreement.");1242val = value->get_int();1243obj->bool_at_put(index, (jboolean)*((jint*)&val));1244break;1245}12461247default:1248ShouldNotReachHere();1249}1250index++;1251}1252}12531254// restore fields of an eliminated object array1255void Deoptimization::reassign_object_array_elements(frame* fr, RegisterMap* reg_map, ObjectValue* sv, objArrayOop obj) {1256for (int i = 0; i < sv->field_size(); i++) {1257StackValue* value = StackValue::create_stack_value(fr, reg_map, sv->field_at(i));1258assert(value->type() == T_OBJECT, "object element expected");1259obj->obj_at_put(i, value->get_obj()());1260}1261}12621263class ReassignedField {1264public:1265int _offset;1266BasicType _type;1267public:1268ReassignedField() {1269_offset = 0;1270_type = T_ILLEGAL;1271}1272};12731274int compare(ReassignedField* left, ReassignedField* right) {1275return left->_offset - right->_offset;1276}12771278// Restore fields of an eliminated instance object using the same field order1279// returned by HotSpotResolvedObjectTypeImpl.getInstanceFields(true)1280static int reassign_fields_by_klass(InstanceKlass* klass, frame* fr, RegisterMap* reg_map, ObjectValue* sv, int svIndex, oop obj, bool skip_internal) {1281GrowableArray<ReassignedField>* fields = new GrowableArray<ReassignedField>();1282InstanceKlass* ik = klass;1283while (ik != NULL) {1284for (AllFieldStream fs(ik); !fs.done(); fs.next()) {1285if (!fs.access_flags().is_static() && (!skip_internal || !fs.access_flags().is_internal())) {1286ReassignedField field;1287field._offset = fs.offset();1288field._type = Signature::basic_type(fs.signature());1289fields->append(field);1290}1291}1292ik = ik->superklass();1293}1294fields->sort(compare);1295for (int i = 0; i < fields->length(); i++) {1296intptr_t val;1297ScopeValue* scope_field = sv->field_at(svIndex);1298StackValue* value = StackValue::create_stack_value(fr, reg_map, scope_field);1299int offset = fields->at(i)._offset;1300BasicType type = fields->at(i)._type;1301switch (type) {1302case T_OBJECT: case T_ARRAY:1303assert(value->type() == T_OBJECT, "Agreement.");1304obj->obj_field_put(offset, value->get_obj()());1305break;13061307// Have to cast to INT (32 bits) pointer to avoid little/big-endian problem.1308case T_INT: case T_FLOAT: { // 4 bytes.1309assert(value->type() == T_INT, "Agreement.");1310bool big_value = false;1311if (i+1 < fields->length() && fields->at(i+1)._type == T_INT) {1312if (scope_field->is_location()) {1313Location::Type type = ((LocationValue*) scope_field)->location().type();1314if (type == Location::dbl || type == Location::lng) {1315big_value = true;1316}1317}1318if (scope_field->is_constant_int()) {1319ScopeValue* next_scope_field = sv->field_at(svIndex + 1);1320if (next_scope_field->is_constant_long() || next_scope_field->is_constant_double()) {1321big_value = true;1322}1323}1324}13251326if (big_value) {1327i++;1328assert(i < fields->length(), "second T_INT field needed");1329assert(fields->at(i)._type == T_INT, "T_INT field needed");1330} else {1331val = value->get_int();1332obj->int_field_put(offset, (jint)*((jint*)&val));1333break;1334}1335}1336/* no break */13371338case T_LONG: case T_DOUBLE: {1339assert(value->type() == T_INT, "Agreement.");1340StackValue* low = StackValue::create_stack_value(fr, reg_map, sv->field_at(++svIndex));1341#ifdef _LP641342jlong res = (jlong)low->get_int();1343#else1344jlong res = jlong_from((jint)value->get_int(), (jint)low->get_int());1345#endif1346obj->long_field_put(offset, res);1347break;1348}13491350case T_SHORT:1351assert(value->type() == T_INT, "Agreement.");1352val = value->get_int();1353obj->short_field_put(offset, (jshort)*((jint*)&val));1354break;13551356case T_CHAR:1357assert(value->type() == T_INT, "Agreement.");1358val = value->get_int();1359obj->char_field_put(offset, (jchar)*((jint*)&val));1360break;13611362case T_BYTE:1363assert(value->type() == T_INT, "Agreement.");1364val = value->get_int();1365obj->byte_field_put(offset, (jbyte)*((jint*)&val));1366break;13671368case T_BOOLEAN:1369assert(value->type() == T_INT, "Agreement.");1370val = value->get_int();1371obj->bool_field_put(offset, (jboolean)*((jint*)&val));1372break;13731374default:1375ShouldNotReachHere();1376}1377svIndex++;1378}1379return svIndex;1380}13811382// restore fields of all eliminated objects and arrays1383void Deoptimization::reassign_fields(frame* fr, RegisterMap* reg_map, GrowableArray<ScopeValue*>* objects, bool realloc_failures, bool skip_internal) {1384for (int i = 0; i < objects->length(); i++) {1385ObjectValue* sv = (ObjectValue*) objects->at(i);1386Klass* k = java_lang_Class::as_Klass(sv->klass()->as_ConstantOopReadValue()->value()());1387Handle obj = sv->value();1388assert(obj.not_null() || realloc_failures, "reallocation was missed");1389if (PrintDeoptimizationDetails) {1390tty->print_cr("reassign fields for object of type %s!", k->name()->as_C_string());1391}1392if (obj.is_null()) {1393continue;1394}13951396// Don't reassign fields of boxes that came from a cache. Caches may be in CDS.1397if (sv->is_auto_box() && ((AutoBoxObjectValue*) sv)->is_cached()) {1398continue;1399}1400#ifdef COMPILER21401if (EnableVectorSupport && VectorSupport::is_vector(k)) {1402assert(sv->field_size() == 1, "%s not a vector", k->name()->as_C_string());1403ScopeValue* payload = sv->field_at(0);1404if (payload->is_location() &&1405payload->as_LocationValue()->location().type() == Location::vector) {1406if (PrintDeoptimizationDetails) {1407tty->print_cr("skip field reassignment for this vector - it should be assigned already");1408if (Verbose) {1409Handle obj = sv->value();1410k->oop_print_on(obj(), tty);1411}1412}1413continue; // Such vector's value was already restored in VectorSupport::allocate_vector().1414}1415// Else fall-through to do assignment for scalar-replaced boxed vector representation1416// which could be restored after vector object allocation.1417}1418#endif1419if (k->is_instance_klass()) {1420InstanceKlass* ik = InstanceKlass::cast(k);1421reassign_fields_by_klass(ik, fr, reg_map, sv, 0, obj(), skip_internal);1422} else if (k->is_typeArray_klass()) {1423TypeArrayKlass* ak = TypeArrayKlass::cast(k);1424reassign_type_array_elements(fr, reg_map, sv, (typeArrayOop) obj(), ak->element_type());1425} else if (k->is_objArray_klass()) {1426reassign_object_array_elements(fr, reg_map, sv, (objArrayOop) obj());1427}1428}1429}143014311432// relock objects for which synchronization was eliminated1433bool Deoptimization::relock_objects(JavaThread* thread, GrowableArray<MonitorInfo*>* monitors,1434JavaThread* deoptee_thread, frame& fr, int exec_mode, bool realloc_failures) {1435bool relocked_objects = false;1436for (int i = 0; i < monitors->length(); i++) {1437MonitorInfo* mon_info = monitors->at(i);1438if (mon_info->eliminated()) {1439assert(!mon_info->owner_is_scalar_replaced() || realloc_failures, "reallocation was missed");1440relocked_objects = true;1441if (!mon_info->owner_is_scalar_replaced()) {1442Handle obj(thread, mon_info->owner());1443markWord mark = obj->mark();1444if (UseBiasedLocking && mark.has_bias_pattern()) {1445// New allocated objects may have the mark set to anonymously biased.1446// Also the deoptimized method may called methods with synchronization1447// where the thread-local object is bias locked to the current thread.1448assert(mark.is_biased_anonymously() ||1449mark.biased_locker() == deoptee_thread, "should be locked to current thread");1450// Reset mark word to unbiased prototype.1451markWord unbiased_prototype = markWord::prototype().set_age(mark.age());1452obj->set_mark(unbiased_prototype);1453} else if (exec_mode == Unpack_none) {1454if (mark.has_locker() && fr.sp() > (intptr_t*)mark.locker()) {1455// With exec_mode == Unpack_none obj may be thread local and locked in1456// a callee frame. In this case the bias was revoked before in revoke_for_object_deoptimization().1457// Make the lock in the callee a recursive lock and restore the displaced header.1458markWord dmw = mark.displaced_mark_helper();1459mark.locker()->set_displaced_header(markWord::encode((BasicLock*) NULL));1460obj->set_mark(dmw);1461}1462if (mark.has_monitor()) {1463// defer relocking if the deoptee thread is currently waiting for obj1464ObjectMonitor* waiting_monitor = deoptee_thread->current_waiting_monitor();1465if (waiting_monitor != NULL && waiting_monitor->object() == obj()) {1466assert(fr.is_deoptimized_frame(), "frame must be scheduled for deoptimization");1467mon_info->lock()->set_displaced_header(markWord::unused_mark());1468JvmtiDeferredUpdates::inc_relock_count_after_wait(deoptee_thread);1469continue;1470}1471}1472}1473BasicLock* lock = mon_info->lock();1474ObjectSynchronizer::enter(obj, lock, deoptee_thread);1475assert(mon_info->owner()->is_locked(), "object must be locked now");1476}1477}1478}1479return relocked_objects;1480}148114821483#ifndef PRODUCT1484// print information about reallocated objects1485void Deoptimization::print_objects(GrowableArray<ScopeValue*>* objects, bool realloc_failures) {1486fieldDescriptor fd;14871488for (int i = 0; i < objects->length(); i++) {1489ObjectValue* sv = (ObjectValue*) objects->at(i);1490Klass* k = java_lang_Class::as_Klass(sv->klass()->as_ConstantOopReadValue()->value()());1491Handle obj = sv->value();14921493tty->print(" object <" INTPTR_FORMAT "> of type ", p2i(sv->value()()));1494k->print_value();1495assert(obj.not_null() || realloc_failures, "reallocation was missed");1496if (obj.is_null()) {1497tty->print(" allocation failed");1498} else {1499tty->print(" allocated (%d bytes)", obj->size() * HeapWordSize);1500}1501tty->cr();15021503if (Verbose && !obj.is_null()) {1504k->oop_print_on(obj(), tty);1505}1506}1507}1508#endif1509#endif // COMPILER2_OR_JVMCI15101511vframeArray* Deoptimization::create_vframeArray(JavaThread* thread, frame fr, RegisterMap *reg_map, GrowableArray<compiledVFrame*>* chunk, bool realloc_failures) {1512Events::log_deopt_message(thread, "DEOPT PACKING pc=" INTPTR_FORMAT " sp=" INTPTR_FORMAT, p2i(fr.pc()), p2i(fr.sp()));15131514#ifndef PRODUCT1515if (PrintDeoptimizationDetails) {1516ttyLocker ttyl;1517tty->print("DEOPT PACKING thread " INTPTR_FORMAT " ", p2i(thread));1518fr.print_on(tty);1519tty->print_cr(" Virtual frames (innermost first):");1520for (int index = 0; index < chunk->length(); index++) {1521compiledVFrame* vf = chunk->at(index);1522tty->print(" %2d - ", index);1523vf->print_value();1524int bci = chunk->at(index)->raw_bci();1525const char* code_name;1526if (bci == SynchronizationEntryBCI) {1527code_name = "sync entry";1528} else {1529Bytecodes::Code code = vf->method()->code_at(bci);1530code_name = Bytecodes::name(code);1531}1532tty->print(" - %s", code_name);1533tty->print_cr(" @ bci %d ", bci);1534if (Verbose) {1535vf->print();1536tty->cr();1537}1538}1539}1540#endif15411542// Register map for next frame (used for stack crawl). We capture1543// the state of the deopt'ing frame's caller. Thus if we need to1544// stuff a C2I adapter we can properly fill in the callee-save1545// register locations.1546frame caller = fr.sender(reg_map);1547int frame_size = caller.sp() - fr.sp();15481549frame sender = caller;15501551// Since the Java thread being deoptimized will eventually adjust it's own stack,1552// the vframeArray containing the unpacking information is allocated in the C heap.1553// For Compiler1, the caller of the deoptimized frame is saved for use by unpack_frames().1554vframeArray* array = vframeArray::allocate(thread, frame_size, chunk, reg_map, sender, caller, fr, realloc_failures);15551556// Compare the vframeArray to the collected vframes1557assert(array->structural_compare(thread, chunk), "just checking");15581559#ifndef PRODUCT1560if (PrintDeoptimizationDetails) {1561ttyLocker ttyl;1562tty->print_cr(" Created vframeArray " INTPTR_FORMAT, p2i(array));1563}1564#endif // PRODUCT15651566return array;1567}15681569#if COMPILER2_OR_JVMCI1570void Deoptimization::pop_frames_failed_reallocs(JavaThread* thread, vframeArray* array) {1571// Reallocation of some scalar replaced objects failed. Record1572// that we need to pop all the interpreter frames for the1573// deoptimized compiled frame.1574assert(thread->frames_to_pop_failed_realloc() == 0, "missed frames to pop?");1575thread->set_frames_to_pop_failed_realloc(array->frames());1576// Unlock all monitors here otherwise the interpreter will see a1577// mix of locked and unlocked monitors (because of failed1578// reallocations of synchronized objects) and be confused.1579for (int i = 0; i < array->frames(); i++) {1580MonitorChunk* monitors = array->element(i)->monitors();1581if (monitors != NULL) {1582for (int j = 0; j < monitors->number_of_monitors(); j++) {1583BasicObjectLock* src = monitors->at(j);1584if (src->obj() != NULL) {1585ObjectSynchronizer::exit(src->obj(), src->lock(), thread);1586}1587}1588array->element(i)->free_monitors(thread);1589#ifdef ASSERT1590array->element(i)->set_removed_monitors();1591#endif1592}1593}1594}1595#endif15961597static void collect_monitors(compiledVFrame* cvf, GrowableArray<Handle>* objects_to_revoke,1598bool only_eliminated) {1599GrowableArray<MonitorInfo*>* monitors = cvf->monitors();1600Thread* thread = Thread::current();1601for (int i = 0; i < monitors->length(); i++) {1602MonitorInfo* mon_info = monitors->at(i);1603if (mon_info->eliminated() == only_eliminated &&1604!mon_info->owner_is_scalar_replaced() &&1605mon_info->owner() != NULL) {1606objects_to_revoke->append(Handle(thread, mon_info->owner()));1607}1608}1609}16101611static void get_monitors_from_stack(GrowableArray<Handle>* objects_to_revoke, JavaThread* thread,1612frame fr, RegisterMap* map, bool only_eliminated) {1613// Unfortunately we don't have a RegisterMap available in most of1614// the places we want to call this routine so we need to walk the1615// stack again to update the register map.1616if (map == NULL || !map->update_map()) {1617StackFrameStream sfs(thread, true /* update */, true /* process_frames */);1618bool found = false;1619while (!found && !sfs.is_done()) {1620frame* cur = sfs.current();1621sfs.next();1622found = cur->id() == fr.id();1623}1624assert(found, "frame to be deoptimized not found on target thread's stack");1625map = sfs.register_map();1626}16271628vframe* vf = vframe::new_vframe(&fr, map, thread);1629compiledVFrame* cvf = compiledVFrame::cast(vf);1630// Revoke monitors' biases in all scopes1631while (!cvf->is_top()) {1632collect_monitors(cvf, objects_to_revoke, only_eliminated);1633cvf = compiledVFrame::cast(cvf->sender());1634}1635collect_monitors(cvf, objects_to_revoke, only_eliminated);1636}16371638void Deoptimization::revoke_from_deopt_handler(JavaThread* thread, frame fr, RegisterMap* map) {1639if (!UseBiasedLocking) {1640return;1641}1642assert(thread == Thread::current(), "should be");1643ResourceMark rm(thread);1644HandleMark hm(thread);1645GrowableArray<Handle>* objects_to_revoke = new GrowableArray<Handle>();1646get_monitors_from_stack(objects_to_revoke, thread, fr, map, false);16471648int len = objects_to_revoke->length();1649for (int i = 0; i < len; i++) {1650oop obj = (objects_to_revoke->at(i))();1651BiasedLocking::revoke_own_lock(thread, objects_to_revoke->at(i));1652assert(!obj->mark().has_bias_pattern(), "biases should be revoked by now");1653}1654}16551656// Revoke the bias of objects with eliminated locking to prepare subsequent relocking.1657void Deoptimization::revoke_for_object_deoptimization(JavaThread* deoptee_thread, frame fr,1658RegisterMap* map, JavaThread* thread) {1659if (!UseBiasedLocking) {1660return;1661}1662GrowableArray<Handle>* objects_to_revoke = new GrowableArray<Handle>();1663assert(KeepStackGCProcessedMark::stack_is_kept_gc_processed(deoptee_thread), "must be");1664// Collect monitors but only those with eliminated locking.1665get_monitors_from_stack(objects_to_revoke, deoptee_thread, fr, map, true);16661667int len = objects_to_revoke->length();1668for (int i = 0; i < len; i++) {1669oop obj = (objects_to_revoke->at(i))();1670markWord mark = obj->mark();1671if (!mark.has_bias_pattern() ||1672mark.is_biased_anonymously() || // eliminated locking does not bias an object if it wasn't before1673!obj->klass()->prototype_header().has_bias_pattern() || // bulk revoke ignores eliminated monitors1674(obj->klass()->prototype_header().bias_epoch() != mark.bias_epoch())) { // bulk rebias ignores eliminated monitors1675// We reach here regularly if there's just eliminated locking on obj.1676// We must not call BiasedLocking::revoke_own_lock() in this case, as we1677// would hit assertions because it is a prerequisite that there has to be1678// non-eliminated locking on obj by deoptee_thread.1679// Luckily we don't have to revoke here because obj has to be a1680// non-escaping obj and can be relocked without revoking the bias. See1681// Deoptimization::relock_objects().1682continue;1683}1684BiasedLocking::revoke(thread, objects_to_revoke->at(i));1685assert(!objects_to_revoke->at(i)->mark().has_bias_pattern(), "biases should be revoked by now");1686}1687}16881689void Deoptimization::deoptimize_single_frame(JavaThread* thread, frame fr, Deoptimization::DeoptReason reason) {1690assert(fr.can_be_deoptimized(), "checking frame type");16911692gather_statistics(reason, Action_none, Bytecodes::_illegal);16931694if (LogCompilation && xtty != NULL) {1695CompiledMethod* cm = fr.cb()->as_compiled_method_or_null();1696assert(cm != NULL, "only compiled methods can deopt");16971698ttyLocker ttyl;1699xtty->begin_head("deoptimized thread='" UINTX_FORMAT "' reason='%s' pc='" INTPTR_FORMAT "'",(uintx)thread->osthread()->thread_id(), trap_reason_name(reason), p2i(fr.pc()));1700cm->log_identity(xtty);1701xtty->end_head();1702for (ScopeDesc* sd = cm->scope_desc_at(fr.pc()); ; sd = sd->sender()) {1703xtty->begin_elem("jvms bci='%d'", sd->bci());1704xtty->method(sd->method());1705xtty->end_elem();1706if (sd->is_top()) break;1707}1708xtty->tail("deoptimized");1709}17101711// Patch the compiled method so that when execution returns to it we will1712// deopt the execution state and return to the interpreter.1713fr.deoptimize(thread);1714}17151716void Deoptimization::deoptimize(JavaThread* thread, frame fr, DeoptReason reason) {1717// Deoptimize only if the frame comes from compile code.1718// Do not deoptimize the frame which is already patched1719// during the execution of the loops below.1720if (!fr.is_compiled_frame() || fr.is_deoptimized_frame()) {1721return;1722}1723ResourceMark rm;1724DeoptimizationMarker dm;1725deoptimize_single_frame(thread, fr, reason);1726}17271728#if INCLUDE_JVMCI1729address Deoptimization::deoptimize_for_missing_exception_handler(CompiledMethod* cm) {1730// there is no exception handler for this pc => deoptimize1731cm->make_not_entrant();17321733// Use Deoptimization::deoptimize for all of its side-effects:1734// gathering traps statistics, logging...1735// it also patches the return pc but we do not care about that1736// since we return a continuation to the deopt_blob below.1737JavaThread* thread = JavaThread::current();1738RegisterMap reg_map(thread, false);1739frame runtime_frame = thread->last_frame();1740frame caller_frame = runtime_frame.sender(®_map);1741assert(caller_frame.cb()->as_compiled_method_or_null() == cm, "expect top frame compiled method");1742vframe* vf = vframe::new_vframe(&caller_frame, ®_map, thread);1743compiledVFrame* cvf = compiledVFrame::cast(vf);1744ScopeDesc* imm_scope = cvf->scope();1745MethodData* imm_mdo = get_method_data(thread, methodHandle(thread, imm_scope->method()), true);1746if (imm_mdo != NULL) {1747ProfileData* pdata = imm_mdo->allocate_bci_to_data(imm_scope->bci(), NULL);1748if (pdata != NULL && pdata->is_BitData()) {1749BitData* bit_data = (BitData*) pdata;1750bit_data->set_exception_seen();1751}1752}17531754Deoptimization::deoptimize(thread, caller_frame, Deoptimization::Reason_not_compiled_exception_handler);17551756MethodData* trap_mdo = get_method_data(thread, methodHandle(thread, cm->method()), true);1757if (trap_mdo != NULL) {1758trap_mdo->inc_trap_count(Deoptimization::Reason_not_compiled_exception_handler);1759}17601761return SharedRuntime::deopt_blob()->unpack_with_exception_in_tls();1762}1763#endif17641765void Deoptimization::deoptimize_frame_internal(JavaThread* thread, intptr_t* id, DeoptReason reason) {1766assert(thread == Thread::current() ||1767thread->is_handshake_safe_for(Thread::current()) ||1768SafepointSynchronize::is_at_safepoint(),1769"can only deoptimize other thread at a safepoint/handshake");1770// Compute frame and register map based on thread and sp.1771RegisterMap reg_map(thread, false);1772frame fr = thread->last_frame();1773while (fr.id() != id) {1774fr = fr.sender(®_map);1775}1776deoptimize(thread, fr, reason);1777}177817791780void Deoptimization::deoptimize_frame(JavaThread* thread, intptr_t* id, DeoptReason reason) {1781Thread* current = Thread::current();1782if (thread == current || thread->is_handshake_safe_for(current)) {1783Deoptimization::deoptimize_frame_internal(thread, id, reason);1784} else {1785VM_DeoptimizeFrame deopt(thread, id, reason);1786VMThread::execute(&deopt);1787}1788}17891790void Deoptimization::deoptimize_frame(JavaThread* thread, intptr_t* id) {1791deoptimize_frame(thread, id, Reason_constraint);1792}17931794// JVMTI PopFrame support1795JRT_LEAF(void, Deoptimization::popframe_preserve_args(JavaThread* thread, int bytes_to_save, void* start_address))1796{1797thread->popframe_preserve_args(in_ByteSize(bytes_to_save), start_address);1798}1799JRT_END18001801MethodData*1802Deoptimization::get_method_data(JavaThread* thread, const methodHandle& m,1803bool create_if_missing) {1804JavaThread* THREAD = thread; // For exception macros.1805MethodData* mdo = m()->method_data();1806if (mdo == NULL && create_if_missing && !HAS_PENDING_EXCEPTION) {1807// Build an MDO. Ignore errors like OutOfMemory;1808// that simply means we won't have an MDO to update.1809Method::build_interpreter_method_data(m, THREAD);1810if (HAS_PENDING_EXCEPTION) {1811// Only metaspace OOM is expected. No Java code executed.1812assert((PENDING_EXCEPTION->is_a(vmClasses::OutOfMemoryError_klass())), "we expect only an OOM error here");1813CLEAR_PENDING_EXCEPTION;1814}1815mdo = m()->method_data();1816}1817return mdo;1818}18191820#if COMPILER2_OR_JVMCI1821void Deoptimization::load_class_by_index(const constantPoolHandle& constant_pool, int index, TRAPS) {1822// In case of an unresolved klass entry, load the class.1823// This path is exercised from case _ldc in Parse::do_one_bytecode,1824// and probably nowhere else.1825// Even that case would benefit from simply re-interpreting the1826// bytecode, without paying special attention to the class index.1827// So this whole "class index" feature should probably be removed.18281829if (constant_pool->tag_at(index).is_unresolved_klass()) {1830Klass* tk = constant_pool->klass_at(index, THREAD);1831if (HAS_PENDING_EXCEPTION) {1832// Exception happened during classloading. We ignore the exception here, since it1833// is going to be rethrown since the current activation is going to be deoptimized and1834// the interpreter will re-execute the bytecode.1835// Do not clear probable Async Exceptions.1836CLEAR_PENDING_NONASYNC_EXCEPTION;1837// Class loading called java code which may have caused a stack1838// overflow. If the exception was thrown right before the return1839// to the runtime the stack is no longer guarded. Reguard the1840// stack otherwise if we return to the uncommon trap blob and the1841// stack bang causes a stack overflow we crash.1842JavaThread* jt = THREAD;1843bool guard_pages_enabled = jt->stack_overflow_state()->reguard_stack_if_needed();1844assert(guard_pages_enabled, "stack banging in uncommon trap blob may cause crash");1845}1846return;1847}18481849assert(!constant_pool->tag_at(index).is_symbol(),1850"no symbolic names here, please");1851}18521853#if INCLUDE_JFR18541855class DeoptReasonSerializer : public JfrSerializer {1856public:1857void serialize(JfrCheckpointWriter& writer) {1858writer.write_count((u4)(Deoptimization::Reason_LIMIT + 1)); // + Reason::many (-1)1859for (int i = -1; i < Deoptimization::Reason_LIMIT; ++i) {1860writer.write_key((u8)i);1861writer.write(Deoptimization::trap_reason_name(i));1862}1863}1864};18651866class DeoptActionSerializer : public JfrSerializer {1867public:1868void serialize(JfrCheckpointWriter& writer) {1869static const u4 nof_actions = Deoptimization::Action_LIMIT;1870writer.write_count(nof_actions);1871for (u4 i = 0; i < Deoptimization::Action_LIMIT; ++i) {1872writer.write_key(i);1873writer.write(Deoptimization::trap_action_name((int)i));1874}1875}1876};18771878static void register_serializers() {1879static int critical_section = 0;1880if (1 == critical_section || Atomic::cmpxchg(&critical_section, 0, 1) == 1) {1881return;1882}1883JfrSerializer::register_serializer(TYPE_DEOPTIMIZATIONREASON, true, new DeoptReasonSerializer());1884JfrSerializer::register_serializer(TYPE_DEOPTIMIZATIONACTION, true, new DeoptActionSerializer());1885}18861887static void post_deoptimization_event(CompiledMethod* nm,1888const Method* method,1889int trap_bci,1890int instruction,1891Deoptimization::DeoptReason reason,1892Deoptimization::DeoptAction action) {1893assert(nm != NULL, "invariant");1894assert(method != NULL, "invariant");1895if (EventDeoptimization::is_enabled()) {1896static bool serializers_registered = false;1897if (!serializers_registered) {1898register_serializers();1899serializers_registered = true;1900}1901EventDeoptimization event;1902event.set_compileId(nm->compile_id());1903event.set_compiler(nm->compiler_type());1904event.set_method(method);1905event.set_lineNumber(method->line_number_from_bci(trap_bci));1906event.set_bci(trap_bci);1907event.set_instruction(instruction);1908event.set_reason(reason);1909event.set_action(action);1910event.commit();1911}1912}19131914#endif // INCLUDE_JFR19151916JRT_ENTRY(void, Deoptimization::uncommon_trap_inner(JavaThread* current, jint trap_request)) {1917HandleMark hm(current);19181919// uncommon_trap() is called at the beginning of the uncommon trap1920// handler. Note this fact before we start generating temporary frames1921// that can confuse an asynchronous stack walker. This counter is1922// decremented at the end of unpack_frames().1923current->inc_in_deopt_handler();19241925// We need to update the map if we have biased locking.1926#if INCLUDE_JVMCI1927// JVMCI might need to get an exception from the stack, which in turn requires the register map to be valid1928RegisterMap reg_map(current, true);1929#else1930RegisterMap reg_map(current, UseBiasedLocking);1931#endif1932frame stub_frame = current->last_frame();1933frame fr = stub_frame.sender(®_map);1934// Make sure the calling nmethod is not getting deoptimized and removed1935// before we are done with it.1936nmethodLocker nl(fr.pc());19371938// Log a message1939Events::log_deopt_message(current, "Uncommon trap: trap_request=" PTR32_FORMAT " fr.pc=" INTPTR_FORMAT " relative=" INTPTR_FORMAT,1940trap_request, p2i(fr.pc()), fr.pc() - fr.cb()->code_begin());19411942{1943ResourceMark rm;19441945DeoptReason reason = trap_request_reason(trap_request);1946DeoptAction action = trap_request_action(trap_request);1947#if INCLUDE_JVMCI1948int debug_id = trap_request_debug_id(trap_request);1949#endif1950jint unloaded_class_index = trap_request_index(trap_request); // CP idx or -119511952vframe* vf = vframe::new_vframe(&fr, ®_map, current);1953compiledVFrame* cvf = compiledVFrame::cast(vf);19541955CompiledMethod* nm = cvf->code();19561957ScopeDesc* trap_scope = cvf->scope();19581959if (TraceDeoptimization) {1960ttyLocker ttyl;1961tty->print_cr(" bci=%d pc=" INTPTR_FORMAT ", relative_pc=" INTPTR_FORMAT ", method=%s" JVMCI_ONLY(", debug_id=%d"), trap_scope->bci(), p2i(fr.pc()), fr.pc() - nm->code_begin(), trap_scope->method()->name_and_sig_as_C_string()1962#if INCLUDE_JVMCI1963, debug_id1964#endif1965);1966}19671968methodHandle trap_method(current, trap_scope->method());1969int trap_bci = trap_scope->bci();1970#if INCLUDE_JVMCI1971jlong speculation = current->pending_failed_speculation();1972if (nm->is_compiled_by_jvmci()) {1973nm->as_nmethod()->update_speculation(current);1974} else {1975assert(speculation == 0, "There should not be a speculation for methods compiled by non-JVMCI compilers");1976}19771978if (trap_bci == SynchronizationEntryBCI) {1979trap_bci = 0;1980current->set_pending_monitorenter(true);1981}19821983if (reason == Deoptimization::Reason_transfer_to_interpreter) {1984current->set_pending_transfer_to_interpreter(true);1985}1986#endif19871988Bytecodes::Code trap_bc = trap_method->java_code_at(trap_bci);1989// Record this event in the histogram.1990gather_statistics(reason, action, trap_bc);19911992// Ensure that we can record deopt. history:1993// Need MDO to record RTM code generation state.1994bool create_if_missing = ProfileTraps || UseCodeAging RTM_OPT_ONLY( || UseRTMLocking );19951996methodHandle profiled_method;1997#if INCLUDE_JVMCI1998if (nm->is_compiled_by_jvmci()) {1999profiled_method = methodHandle(current, nm->method());2000} else {2001profiled_method = trap_method;2002}2003#else2004profiled_method = trap_method;2005#endif20062007MethodData* trap_mdo =2008get_method_data(current, profiled_method, create_if_missing);20092010JFR_ONLY(post_deoptimization_event(nm, trap_method(), trap_bci, trap_bc, reason, action);)20112012// Log a message2013Events::log_deopt_message(current, "Uncommon trap: reason=%s action=%s pc=" INTPTR_FORMAT " method=%s @ %d %s",2014trap_reason_name(reason), trap_action_name(action), p2i(fr.pc()),2015trap_method->name_and_sig_as_C_string(), trap_bci, nm->compiler_name());20162017// Print a bunch of diagnostics, if requested.2018if (TraceDeoptimization || LogCompilation) {2019ResourceMark rm;2020ttyLocker ttyl;2021char buf[100];2022if (xtty != NULL) {2023xtty->begin_head("uncommon_trap thread='" UINTX_FORMAT "' %s",2024os::current_thread_id(),2025format_trap_request(buf, sizeof(buf), trap_request));2026#if INCLUDE_JVMCI2027if (speculation != 0) {2028xtty->print(" speculation='" JLONG_FORMAT "'", speculation);2029}2030#endif2031nm->log_identity(xtty);2032}2033Symbol* class_name = NULL;2034bool unresolved = false;2035if (unloaded_class_index >= 0) {2036constantPoolHandle constants (current, trap_method->constants());2037if (constants->tag_at(unloaded_class_index).is_unresolved_klass()) {2038class_name = constants->klass_name_at(unloaded_class_index);2039unresolved = true;2040if (xtty != NULL)2041xtty->print(" unresolved='1'");2042} else if (constants->tag_at(unloaded_class_index).is_symbol()) {2043class_name = constants->symbol_at(unloaded_class_index);2044}2045if (xtty != NULL)2046xtty->name(class_name);2047}2048if (xtty != NULL && trap_mdo != NULL && (int)reason < (int)MethodData::_trap_hist_limit) {2049// Dump the relevant MDO state.2050// This is the deopt count for the current reason, any previous2051// reasons or recompiles seen at this point.2052int dcnt = trap_mdo->trap_count(reason);2053if (dcnt != 0)2054xtty->print(" count='%d'", dcnt);2055ProfileData* pdata = trap_mdo->bci_to_data(trap_bci);2056int dos = (pdata == NULL)? 0: pdata->trap_state();2057if (dos != 0) {2058xtty->print(" state='%s'", format_trap_state(buf, sizeof(buf), dos));2059if (trap_state_is_recompiled(dos)) {2060int recnt2 = trap_mdo->overflow_recompile_count();2061if (recnt2 != 0)2062xtty->print(" recompiles2='%d'", recnt2);2063}2064}2065}2066if (xtty != NULL) {2067xtty->stamp();2068xtty->end_head();2069}2070if (TraceDeoptimization) { // make noise on the tty2071tty->print("Uncommon trap occurred in");2072nm->method()->print_short_name(tty);2073tty->print(" compiler=%s compile_id=%d", nm->compiler_name(), nm->compile_id());2074#if INCLUDE_JVMCI2075if (nm->is_nmethod()) {2076const char* installed_code_name = nm->as_nmethod()->jvmci_name();2077if (installed_code_name != NULL) {2078tty->print(" (JVMCI: installed code name=%s) ", installed_code_name);2079}2080}2081#endif2082tty->print(" (@" INTPTR_FORMAT ") thread=" UINTX_FORMAT " reason=%s action=%s unloaded_class_index=%d" JVMCI_ONLY(" debug_id=%d"),2083p2i(fr.pc()),2084os::current_thread_id(),2085trap_reason_name(reason),2086trap_action_name(action),2087unloaded_class_index2088#if INCLUDE_JVMCI2089, debug_id2090#endif2091);2092if (class_name != NULL) {2093tty->print(unresolved ? " unresolved class: " : " symbol: ");2094class_name->print_symbol_on(tty);2095}2096tty->cr();2097}2098if (xtty != NULL) {2099// Log the precise location of the trap.2100for (ScopeDesc* sd = trap_scope; ; sd = sd->sender()) {2101xtty->begin_elem("jvms bci='%d'", sd->bci());2102xtty->method(sd->method());2103xtty->end_elem();2104if (sd->is_top()) break;2105}2106xtty->tail("uncommon_trap");2107}2108}2109// (End diagnostic printout.)21102111// Load class if necessary2112if (unloaded_class_index >= 0) {2113constantPoolHandle constants(current, trap_method->constants());2114load_class_by_index(constants, unloaded_class_index, THREAD);2115}21162117// Flush the nmethod if necessary and desirable.2118//2119// We need to avoid situations where we are re-flushing the nmethod2120// because of a hot deoptimization site. Repeated flushes at the same2121// point need to be detected by the compiler and avoided. If the compiler2122// cannot avoid them (or has a bug and "refuses" to avoid them), this2123// module must take measures to avoid an infinite cycle of recompilation2124// and deoptimization. There are several such measures:2125//2126// 1. If a recompilation is ordered a second time at some site X2127// and for the same reason R, the action is adjusted to 'reinterpret',2128// to give the interpreter time to exercise the method more thoroughly.2129// If this happens, the method's overflow_recompile_count is incremented.2130//2131// 2. If the compiler fails to reduce the deoptimization rate, then2132// the method's overflow_recompile_count will begin to exceed the set2133// limit PerBytecodeRecompilationCutoff. If this happens, the action2134// is adjusted to 'make_not_compilable', and the method is abandoned2135// to the interpreter. This is a performance hit for hot methods,2136// but is better than a disastrous infinite cycle of recompilations.2137// (Actually, only the method containing the site X is abandoned.)2138//2139// 3. In parallel with the previous measures, if the total number of2140// recompilations of a method exceeds the much larger set limit2141// PerMethodRecompilationCutoff, the method is abandoned.2142// This should only happen if the method is very large and has2143// many "lukewarm" deoptimizations. The code which enforces this2144// limit is elsewhere (class nmethod, class Method).2145//2146// Note that the per-BCI 'is_recompiled' bit gives the compiler one chance2147// to recompile at each bytecode independently of the per-BCI cutoff.2148//2149// The decision to update code is up to the compiler, and is encoded2150// in the Action_xxx code. If the compiler requests Action_none2151// no trap state is changed, no compiled code is changed, and the2152// computation suffers along in the interpreter.2153//2154// The other action codes specify various tactics for decompilation2155// and recompilation. Action_maybe_recompile is the loosest, and2156// allows the compiled code to stay around until enough traps are seen,2157// and until the compiler gets around to recompiling the trapping method.2158//2159// The other actions cause immediate removal of the present code.21602161// Traps caused by injected profile shouldn't pollute trap counts.2162bool injected_profile_trap = trap_method->has_injected_profile() &&2163(reason == Reason_intrinsic || reason == Reason_unreached);21642165bool update_trap_state = (reason != Reason_tenured) && !injected_profile_trap;2166bool make_not_entrant = false;2167bool make_not_compilable = false;2168bool reprofile = false;2169switch (action) {2170case Action_none:2171// Keep the old code.2172update_trap_state = false;2173break;2174case Action_maybe_recompile:2175// Do not need to invalidate the present code, but we can2176// initiate another2177// Start compiler without (necessarily) invalidating the nmethod.2178// The system will tolerate the old code, but new code should be2179// generated when possible.2180break;2181case Action_reinterpret:2182// Go back into the interpreter for a while, and then consider2183// recompiling form scratch.2184make_not_entrant = true;2185// Reset invocation counter for outer most method.2186// This will allow the interpreter to exercise the bytecodes2187// for a while before recompiling.2188// By contrast, Action_make_not_entrant is immediate.2189//2190// Note that the compiler will track null_check, null_assert,2191// range_check, and class_check events and log them as if they2192// had been traps taken from compiled code. This will update2193// the MDO trap history so that the next compilation will2194// properly detect hot trap sites.2195reprofile = true;2196break;2197case Action_make_not_entrant:2198// Request immediate recompilation, and get rid of the old code.2199// Make them not entrant, so next time they are called they get2200// recompiled. Unloaded classes are loaded now so recompile before next2201// time they are called. Same for uninitialized. The interpreter will2202// link the missing class, if any.2203make_not_entrant = true;2204break;2205case Action_make_not_compilable:2206// Give up on compiling this method at all.2207make_not_entrant = true;2208make_not_compilable = true;2209break;2210default:2211ShouldNotReachHere();2212}22132214// Setting +ProfileTraps fixes the following, on all platforms:2215// 4852688: ProfileInterpreter is off by default for ia64. The result is2216// infinite heroic-opt-uncommon-trap/deopt/recompile cycles, since the2217// recompile relies on a MethodData* to record heroic opt failures.22182219// Whether the interpreter is producing MDO data or not, we also need2220// to use the MDO to detect hot deoptimization points and control2221// aggressive optimization.2222bool inc_recompile_count = false;2223ProfileData* pdata = NULL;2224if (ProfileTraps && CompilerConfig::is_c2_or_jvmci_compiler_enabled() && update_trap_state && trap_mdo != NULL) {2225assert(trap_mdo == get_method_data(current, profiled_method, false), "sanity");2226uint this_trap_count = 0;2227bool maybe_prior_trap = false;2228bool maybe_prior_recompile = false;2229pdata = query_update_method_data(trap_mdo, trap_bci, reason, true,2230#if INCLUDE_JVMCI2231nm->is_compiled_by_jvmci() && nm->is_osr_method(),2232#endif2233nm->method(),2234//outputs:2235this_trap_count,2236maybe_prior_trap,2237maybe_prior_recompile);2238// Because the interpreter also counts null, div0, range, and class2239// checks, these traps from compiled code are double-counted.2240// This is harmless; it just means that the PerXTrapLimit values2241// are in effect a little smaller than they look.22422243DeoptReason per_bc_reason = reason_recorded_per_bytecode_if_any(reason);2244if (per_bc_reason != Reason_none) {2245// Now take action based on the partially known per-BCI history.2246if (maybe_prior_trap2247&& this_trap_count >= (uint)PerBytecodeTrapLimit) {2248// If there are too many traps at this BCI, force a recompile.2249// This will allow the compiler to see the limit overflow, and2250// take corrective action, if possible. The compiler generally2251// does not use the exact PerBytecodeTrapLimit value, but instead2252// changes its tactics if it sees any traps at all. This provides2253// a little hysteresis, delaying a recompile until a trap happens2254// several times.2255//2256// Actually, since there is only one bit of counter per BCI,2257// the possible per-BCI counts are {0,1,(per-method count)}.2258// This produces accurate results if in fact there is only2259// one hot trap site, but begins to get fuzzy if there are2260// many sites. For example, if there are ten sites each2261// trapping two or more times, they each get the blame for2262// all of their traps.2263make_not_entrant = true;2264}22652266// Detect repeated recompilation at the same BCI, and enforce a limit.2267if (make_not_entrant && maybe_prior_recompile) {2268// More than one recompile at this point.2269inc_recompile_count = maybe_prior_trap;2270}2271} else {2272// For reasons which are not recorded per-bytecode, we simply2273// force recompiles unconditionally.2274// (Note that PerMethodRecompilationCutoff is enforced elsewhere.)2275make_not_entrant = true;2276}22772278// Go back to the compiler if there are too many traps in this method.2279if (this_trap_count >= per_method_trap_limit(reason)) {2280// If there are too many traps in this method, force a recompile.2281// This will allow the compiler to see the limit overflow, and2282// take corrective action, if possible.2283// (This condition is an unlikely backstop only, because the2284// PerBytecodeTrapLimit is more likely to take effect first,2285// if it is applicable.)2286make_not_entrant = true;2287}22882289// Here's more hysteresis: If there has been a recompile at2290// this trap point already, run the method in the interpreter2291// for a while to exercise it more thoroughly.2292if (make_not_entrant && maybe_prior_recompile && maybe_prior_trap) {2293reprofile = true;2294}2295}22962297// Take requested actions on the method:22982299// Recompile2300if (make_not_entrant) {2301if (!nm->make_not_entrant()) {2302return; // the call did not change nmethod's state2303}23042305if (pdata != NULL) {2306// Record the recompilation event, if any.2307int tstate0 = pdata->trap_state();2308int tstate1 = trap_state_set_recompiled(tstate0, true);2309if (tstate1 != tstate0)2310pdata->set_trap_state(tstate1);2311}23122313#if INCLUDE_RTM_OPT2314// Restart collecting RTM locking abort statistic if the method2315// is recompiled for a reason other than RTM state change.2316// Assume that in new recompiled code the statistic could be different,2317// for example, due to different inlining.2318if ((reason != Reason_rtm_state_change) && (trap_mdo != NULL) &&2319UseRTMDeopt && (nm->as_nmethod()->rtm_state() != ProfileRTM)) {2320trap_mdo->atomic_set_rtm_state(ProfileRTM);2321}2322#endif2323// For code aging we count traps separately here, using make_not_entrant()2324// as a guard against simultaneous deopts in multiple threads.2325if (reason == Reason_tenured && trap_mdo != NULL) {2326trap_mdo->inc_tenure_traps();2327}2328}23292330if (inc_recompile_count) {2331trap_mdo->inc_overflow_recompile_count();2332if ((uint)trap_mdo->overflow_recompile_count() >2333(uint)PerBytecodeRecompilationCutoff) {2334// Give up on the method containing the bad BCI.2335if (trap_method() == nm->method()) {2336make_not_compilable = true;2337} else {2338trap_method->set_not_compilable("overflow_recompile_count > PerBytecodeRecompilationCutoff", CompLevel_full_optimization);2339// But give grace to the enclosing nm->method().2340}2341}2342}23432344// Reprofile2345if (reprofile) {2346CompilationPolicy::reprofile(trap_scope, nm->is_osr_method());2347}23482349// Give up compiling2350if (make_not_compilable && !nm->method()->is_not_compilable(CompLevel_full_optimization)) {2351assert(make_not_entrant, "consistent");2352nm->method()->set_not_compilable("give up compiling", CompLevel_full_optimization);2353}23542355} // Free marked resources23562357}2358JRT_END23592360ProfileData*2361Deoptimization::query_update_method_data(MethodData* trap_mdo,2362int trap_bci,2363Deoptimization::DeoptReason reason,2364bool update_total_trap_count,2365#if INCLUDE_JVMCI2366bool is_osr,2367#endif2368Method* compiled_method,2369//outputs:2370uint& ret_this_trap_count,2371bool& ret_maybe_prior_trap,2372bool& ret_maybe_prior_recompile) {2373bool maybe_prior_trap = false;2374bool maybe_prior_recompile = false;2375uint this_trap_count = 0;2376if (update_total_trap_count) {2377uint idx = reason;2378#if INCLUDE_JVMCI2379if (is_osr) {2380idx += Reason_LIMIT;2381}2382#endif2383uint prior_trap_count = trap_mdo->trap_count(idx);2384this_trap_count = trap_mdo->inc_trap_count(idx);23852386// If the runtime cannot find a place to store trap history,2387// it is estimated based on the general condition of the method.2388// If the method has ever been recompiled, or has ever incurred2389// a trap with the present reason , then this BCI is assumed2390// (pessimistically) to be the culprit.2391maybe_prior_trap = (prior_trap_count != 0);2392maybe_prior_recompile = (trap_mdo->decompile_count() != 0);2393}2394ProfileData* pdata = NULL;239523962397// For reasons which are recorded per bytecode, we check per-BCI data.2398DeoptReason per_bc_reason = reason_recorded_per_bytecode_if_any(reason);2399assert(per_bc_reason != Reason_none || update_total_trap_count, "must be");2400if (per_bc_reason != Reason_none) {2401// Find the profile data for this BCI. If there isn't one,2402// try to allocate one from the MDO's set of spares.2403// This will let us detect a repeated trap at this point.2404pdata = trap_mdo->allocate_bci_to_data(trap_bci, reason_is_speculate(reason) ? compiled_method : NULL);24052406if (pdata != NULL) {2407if (reason_is_speculate(reason) && !pdata->is_SpeculativeTrapData()) {2408if (LogCompilation && xtty != NULL) {2409ttyLocker ttyl;2410// no more room for speculative traps in this MDO2411xtty->elem("speculative_traps_oom");2412}2413}2414// Query the trap state of this profile datum.2415int tstate0 = pdata->trap_state();2416if (!trap_state_has_reason(tstate0, per_bc_reason))2417maybe_prior_trap = false;2418if (!trap_state_is_recompiled(tstate0))2419maybe_prior_recompile = false;24202421// Update the trap state of this profile datum.2422int tstate1 = tstate0;2423// Record the reason.2424tstate1 = trap_state_add_reason(tstate1, per_bc_reason);2425// Store the updated state on the MDO, for next time.2426if (tstate1 != tstate0)2427pdata->set_trap_state(tstate1);2428} else {2429if (LogCompilation && xtty != NULL) {2430ttyLocker ttyl;2431// Missing MDP? Leave a small complaint in the log.2432xtty->elem("missing_mdp bci='%d'", trap_bci);2433}2434}2435}24362437// Return results:2438ret_this_trap_count = this_trap_count;2439ret_maybe_prior_trap = maybe_prior_trap;2440ret_maybe_prior_recompile = maybe_prior_recompile;2441return pdata;2442}24432444void2445Deoptimization::update_method_data_from_interpreter(MethodData* trap_mdo, int trap_bci, int reason) {2446ResourceMark rm;2447// Ignored outputs:2448uint ignore_this_trap_count;2449bool ignore_maybe_prior_trap;2450bool ignore_maybe_prior_recompile;2451assert(!reason_is_speculate(reason), "reason speculate only used by compiler");2452// JVMCI uses the total counts to determine if deoptimizations are happening too frequently -> do not adjust total counts2453bool update_total_counts = true JVMCI_ONLY( && !UseJVMCICompiler);2454query_update_method_data(trap_mdo, trap_bci,2455(DeoptReason)reason,2456update_total_counts,2457#if INCLUDE_JVMCI2458false,2459#endif2460NULL,2461ignore_this_trap_count,2462ignore_maybe_prior_trap,2463ignore_maybe_prior_recompile);2464}24652466Deoptimization::UnrollBlock* Deoptimization::uncommon_trap(JavaThread* current, jint trap_request, jint exec_mode) {2467// Enable WXWrite: current function is called from methods compiled by C2 directly2468MACOS_AARCH64_ONLY(ThreadWXEnable wx(WXWrite, current));24692470if (TraceDeoptimization) {2471tty->print("Uncommon trap ");2472}2473// Still in Java no safepoints2474{2475// This enters VM and may safepoint2476uncommon_trap_inner(current, trap_request);2477}2478HandleMark hm(current);2479return fetch_unroll_info_helper(current, exec_mode);2480}24812482// Local derived constants.2483// Further breakdown of DataLayout::trap_state, as promised by DataLayout.2484const int DS_REASON_MASK = ((uint)DataLayout::trap_mask) >> 1;2485const int DS_RECOMPILE_BIT = DataLayout::trap_mask - DS_REASON_MASK;24862487//---------------------------trap_state_reason---------------------------------2488Deoptimization::DeoptReason2489Deoptimization::trap_state_reason(int trap_state) {2490// This assert provides the link between the width of DataLayout::trap_bits2491// and the encoding of "recorded" reasons. It ensures there are enough2492// bits to store all needed reasons in the per-BCI MDO profile.2493assert(DS_REASON_MASK >= Reason_RECORDED_LIMIT, "enough bits");2494int recompile_bit = (trap_state & DS_RECOMPILE_BIT);2495trap_state -= recompile_bit;2496if (trap_state == DS_REASON_MASK) {2497return Reason_many;2498} else {2499assert((int)Reason_none == 0, "state=0 => Reason_none");2500return (DeoptReason)trap_state;2501}2502}2503//-------------------------trap_state_has_reason-------------------------------2504int Deoptimization::trap_state_has_reason(int trap_state, int reason) {2505assert(reason_is_recorded_per_bytecode((DeoptReason)reason), "valid reason");2506assert(DS_REASON_MASK >= Reason_RECORDED_LIMIT, "enough bits");2507int recompile_bit = (trap_state & DS_RECOMPILE_BIT);2508trap_state -= recompile_bit;2509if (trap_state == DS_REASON_MASK) {2510return -1; // true, unspecifically (bottom of state lattice)2511} else if (trap_state == reason) {2512return 1; // true, definitely2513} else if (trap_state == 0) {2514return 0; // false, definitely (top of state lattice)2515} else {2516return 0; // false, definitely2517}2518}2519//-------------------------trap_state_add_reason-------------------------------2520int Deoptimization::trap_state_add_reason(int trap_state, int reason) {2521assert(reason_is_recorded_per_bytecode((DeoptReason)reason) || reason == Reason_many, "valid reason");2522int recompile_bit = (trap_state & DS_RECOMPILE_BIT);2523trap_state -= recompile_bit;2524if (trap_state == DS_REASON_MASK) {2525return trap_state + recompile_bit; // already at state lattice bottom2526} else if (trap_state == reason) {2527return trap_state + recompile_bit; // the condition is already true2528} else if (trap_state == 0) {2529return reason + recompile_bit; // no condition has yet been true2530} else {2531return DS_REASON_MASK + recompile_bit; // fall to state lattice bottom2532}2533}2534//-----------------------trap_state_is_recompiled------------------------------2535bool Deoptimization::trap_state_is_recompiled(int trap_state) {2536return (trap_state & DS_RECOMPILE_BIT) != 0;2537}2538//-----------------------trap_state_set_recompiled-----------------------------2539int Deoptimization::trap_state_set_recompiled(int trap_state, bool z) {2540if (z) return trap_state | DS_RECOMPILE_BIT;2541else return trap_state & ~DS_RECOMPILE_BIT;2542}2543//---------------------------format_trap_state---------------------------------2544// This is used for debugging and diagnostics, including LogFile output.2545const char* Deoptimization::format_trap_state(char* buf, size_t buflen,2546int trap_state) {2547assert(buflen > 0, "sanity");2548DeoptReason reason = trap_state_reason(trap_state);2549bool recomp_flag = trap_state_is_recompiled(trap_state);2550// Re-encode the state from its decoded components.2551int decoded_state = 0;2552if (reason_is_recorded_per_bytecode(reason) || reason == Reason_many)2553decoded_state = trap_state_add_reason(decoded_state, reason);2554if (recomp_flag)2555decoded_state = trap_state_set_recompiled(decoded_state, recomp_flag);2556// If the state re-encodes properly, format it symbolically.2557// Because this routine is used for debugging and diagnostics,2558// be robust even if the state is a strange value.2559size_t len;2560if (decoded_state != trap_state) {2561// Random buggy state that doesn't decode??2562len = jio_snprintf(buf, buflen, "#%d", trap_state);2563} else {2564len = jio_snprintf(buf, buflen, "%s%s",2565trap_reason_name(reason),2566recomp_flag ? " recompiled" : "");2567}2568return buf;2569}257025712572//--------------------------------statics--------------------------------------2573const char* Deoptimization::_trap_reason_name[] = {2574// Note: Keep this in sync. with enum DeoptReason.2575"none",2576"null_check",2577"null_assert" JVMCI_ONLY("_or_unreached0"),2578"range_check",2579"class_check",2580"array_check",2581"intrinsic" JVMCI_ONLY("_or_type_checked_inlining"),2582"bimorphic" JVMCI_ONLY("_or_optimized_type_check"),2583"profile_predicate",2584"unloaded",2585"uninitialized",2586"initialized",2587"unreached",2588"unhandled",2589"constraint",2590"div0_check",2591"age",2592"predicate",2593"loop_limit_check",2594"speculate_class_check",2595"speculate_null_check",2596"speculate_null_assert",2597"rtm_state_change",2598"unstable_if",2599"unstable_fused_if",2600#if INCLUDE_JVMCI2601"aliasing",2602"transfer_to_interpreter",2603"not_compiled_exception_handler",2604"unresolved",2605"jsr_mismatch",2606#endif2607"tenured"2608};2609const char* Deoptimization::_trap_action_name[] = {2610// Note: Keep this in sync. with enum DeoptAction.2611"none",2612"maybe_recompile",2613"reinterpret",2614"make_not_entrant",2615"make_not_compilable"2616};26172618const char* Deoptimization::trap_reason_name(int reason) {2619// Check that every reason has a name2620STATIC_ASSERT(sizeof(_trap_reason_name)/sizeof(const char*) == Reason_LIMIT);26212622if (reason == Reason_many) return "many";2623if ((uint)reason < Reason_LIMIT)2624return _trap_reason_name[reason];2625static char buf[20];2626sprintf(buf, "reason%d", reason);2627return buf;2628}2629const char* Deoptimization::trap_action_name(int action) {2630// Check that every action has a name2631STATIC_ASSERT(sizeof(_trap_action_name)/sizeof(const char*) == Action_LIMIT);26322633if ((uint)action < Action_LIMIT)2634return _trap_action_name[action];2635static char buf[20];2636sprintf(buf, "action%d", action);2637return buf;2638}26392640// This is used for debugging and diagnostics, including LogFile output.2641const char* Deoptimization::format_trap_request(char* buf, size_t buflen,2642int trap_request) {2643jint unloaded_class_index = trap_request_index(trap_request);2644const char* reason = trap_reason_name(trap_request_reason(trap_request));2645const char* action = trap_action_name(trap_request_action(trap_request));2646#if INCLUDE_JVMCI2647int debug_id = trap_request_debug_id(trap_request);2648#endif2649size_t len;2650if (unloaded_class_index < 0) {2651len = jio_snprintf(buf, buflen, "reason='%s' action='%s'" JVMCI_ONLY(" debug_id='%d'"),2652reason, action2653#if INCLUDE_JVMCI2654,debug_id2655#endif2656);2657} else {2658len = jio_snprintf(buf, buflen, "reason='%s' action='%s' index='%d'" JVMCI_ONLY(" debug_id='%d'"),2659reason, action, unloaded_class_index2660#if INCLUDE_JVMCI2661,debug_id2662#endif2663);2664}2665return buf;2666}26672668juint Deoptimization::_deoptimization_hist2669[Deoptimization::Reason_LIMIT]2670[1 + Deoptimization::Action_LIMIT]2671[Deoptimization::BC_CASE_LIMIT]2672= {0};26732674enum {2675LSB_BITS = 8,2676LSB_MASK = right_n_bits(LSB_BITS)2677};26782679void Deoptimization::gather_statistics(DeoptReason reason, DeoptAction action,2680Bytecodes::Code bc) {2681assert(reason >= 0 && reason < Reason_LIMIT, "oob");2682assert(action >= 0 && action < Action_LIMIT, "oob");2683_deoptimization_hist[Reason_none][0][0] += 1; // total2684_deoptimization_hist[reason][0][0] += 1; // per-reason total2685juint* cases = _deoptimization_hist[reason][1+action];2686juint* bc_counter_addr = NULL;2687juint bc_counter = 0;2688// Look for an unused counter, or an exact match to this BC.2689if (bc != Bytecodes::_illegal) {2690for (int bc_case = 0; bc_case < BC_CASE_LIMIT; bc_case++) {2691juint* counter_addr = &cases[bc_case];2692juint counter = *counter_addr;2693if ((counter == 0 && bc_counter_addr == NULL)2694|| (Bytecodes::Code)(counter & LSB_MASK) == bc) {2695// this counter is either free or is already devoted to this BC2696bc_counter_addr = counter_addr;2697bc_counter = counter | bc;2698}2699}2700}2701if (bc_counter_addr == NULL) {2702// Overflow, or no given bytecode.2703bc_counter_addr = &cases[BC_CASE_LIMIT-1];2704bc_counter = (*bc_counter_addr & ~LSB_MASK); // clear LSB2705}2706*bc_counter_addr = bc_counter + (1 << LSB_BITS);2707}27082709jint Deoptimization::total_deoptimization_count() {2710return _deoptimization_hist[Reason_none][0][0];2711}27122713void Deoptimization::print_statistics() {2714juint total = total_deoptimization_count();2715juint account = total;2716if (total != 0) {2717ttyLocker ttyl;2718if (xtty != NULL) xtty->head("statistics type='deoptimization'");2719tty->print_cr("Deoptimization traps recorded:");2720#define PRINT_STAT_LINE(name, r) \2721tty->print_cr(" %4d (%4.1f%%) %s", (int)(r), ((r) * 100.0) / total, name);2722PRINT_STAT_LINE("total", total);2723// For each non-zero entry in the histogram, print the reason,2724// the action, and (if specifically known) the type of bytecode.2725for (int reason = 0; reason < Reason_LIMIT; reason++) {2726for (int action = 0; action < Action_LIMIT; action++) {2727juint* cases = _deoptimization_hist[reason][1+action];2728for (int bc_case = 0; bc_case < BC_CASE_LIMIT; bc_case++) {2729juint counter = cases[bc_case];2730if (counter != 0) {2731char name[1*K];2732Bytecodes::Code bc = (Bytecodes::Code)(counter & LSB_MASK);2733if (bc_case == BC_CASE_LIMIT && (int)bc == 0)2734bc = Bytecodes::_illegal;2735sprintf(name, "%s/%s/%s",2736trap_reason_name(reason),2737trap_action_name(action),2738Bytecodes::is_defined(bc)? Bytecodes::name(bc): "other");2739juint r = counter >> LSB_BITS;2740tty->print_cr(" %40s: " UINT32_FORMAT " (%.1f%%)", name, r, (r * 100.0) / total);2741account -= r;2742}2743}2744}2745}2746if (account != 0) {2747PRINT_STAT_LINE("unaccounted", account);2748}2749#undef PRINT_STAT_LINE2750if (xtty != NULL) xtty->tail("statistics");2751}2752}27532754#else // COMPILER2_OR_JVMCI275527562757// Stubs for C1 only system.2758bool Deoptimization::trap_state_is_recompiled(int trap_state) {2759return false;2760}27612762const char* Deoptimization::trap_reason_name(int reason) {2763return "unknown";2764}27652766void Deoptimization::print_statistics() {2767// no output2768}27692770void2771Deoptimization::update_method_data_from_interpreter(MethodData* trap_mdo, int trap_bci, int reason) {2772// no udpate2773}27742775int Deoptimization::trap_state_has_reason(int trap_state, int reason) {2776return 0;2777}27782779void Deoptimization::gather_statistics(DeoptReason reason, DeoptAction action,2780Bytecodes::Code bc) {2781// no update2782}27832784const char* Deoptimization::format_trap_state(char* buf, size_t buflen,2785int trap_state) {2786jio_snprintf(buf, buflen, "#%d", trap_state);2787return buf;2788}27892790#endif // COMPILER2_OR_JVMCI279127922793