1 2 3 /* 4 * Copyright (c) 1997, 2020, Oracle and/or its affiliates. All rights reserved. 5 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 6 * 7 * This code is free software; you can redistribute it and/or modify it 8 * under the terms of the GNU General Public License version 2 only, as 9 * published by the Free Software Foundation. 10 * 11 * This code is distributed in the hope that it will be useful, but WITHOUT 12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 14 * version 2 for more details (a copy is included in the LICENSE file that 15 * accompanied this code). 16 * 17 * You should have received a copy of the GNU General Public License version 18 * 2 along with this work; if not, write to the Free Software Foundation, 19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 20 * 21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 22 * or visit www.oracle.com if you need additional information or have any 23 * questions. 24 * 25 */ 26 27 #include "precompiled.hpp" 28 #include "jvm.h" 29 #include "classfile/javaClasses.inline.hpp" 30 #include "classfile/symbolTable.hpp" 31 #include "classfile/systemDictionary.hpp" 32 #include "code/codeCache.hpp" 33 #include "code/debugInfoRec.hpp" 34 #include "code/nmethod.hpp" 35 #include "code/pcDesc.hpp" 36 #include "code/scopeDesc.hpp" 37 #include "compiler/compilationPolicy.hpp" 38 #include "interpreter/bytecode.hpp" 39 #include "interpreter/interpreter.hpp" 40 #include "interpreter/oopMapCache.hpp" 41 #include "memory/allocation.inline.hpp" 42 #include "memory/oopFactory.hpp" 43 #include "memory/resourceArea.hpp" 44 #include "memory/universe.hpp" 45 #include "oops/constantPool.hpp" 46 #include "oops/method.hpp" 47 #include "oops/objArrayKlass.hpp" 48 #include "oops/objArrayOop.inline.hpp" 49 #include "oops/oop.inline.hpp" 50 #include "oops/fieldStreams.inline.hpp" 51 #include "oops/typeArrayOop.inline.hpp" 52 #include "oops/verifyOopClosure.hpp" 53 #include "prims/jvmtiThreadState.hpp" 54 #include "runtime/atomic.hpp" 55 #include "runtime/biasedLocking.hpp" 56 #include "runtime/deoptimization.hpp" 57 #include "runtime/fieldDescriptor.hpp" 58 #include "runtime/fieldDescriptor.inline.hpp" 59 #include "runtime/frame.inline.hpp" 60 #include "runtime/handles.inline.hpp" 61 #include "runtime/interfaceSupport.inline.hpp" 62 #include "runtime/jniHandles.inline.hpp" 63 #include "runtime/objectMonitor.inline.hpp" 64 #include "runtime/safepointVerifiers.hpp" 65 #include "runtime/sharedRuntime.hpp" 66 #include "runtime/signature.hpp" 67 #include "runtime/stubRoutines.hpp" 68 #include "runtime/thread.hpp" 69 #include "runtime/threadSMR.hpp" 70 #include "runtime/vframe.hpp" 71 #include "runtime/vframeArray.hpp" 72 #include "runtime/vframe_hp.hpp" 73 #include "utilities/events.hpp" 74 #include "utilities/macros.hpp" 75 #include "utilities/preserveException.hpp" 76 #include "utilities/xmlstream.hpp" 77 #if INCLUDE_JFR 78 #include "jfr/jfrEvents.hpp" 79 #include "jfr/metadata/jfrSerializer.hpp" 80 #endif 81 82 bool DeoptimizationMarker::_is_active = false; 83 84 Deoptimization::UnrollBlock::UnrollBlock(int size_of_deoptimized_frame, 85 int caller_adjustment, 86 int caller_actual_parameters, 87 int number_of_frames, 88 intptr_t* frame_sizes, 89 address* frame_pcs, 90 BasicType return_type, 91 int exec_mode) { 92 _size_of_deoptimized_frame = size_of_deoptimized_frame; 93 _caller_adjustment = caller_adjustment; 94 _caller_actual_parameters = caller_actual_parameters; 95 _number_of_frames = number_of_frames; 96 _frame_sizes = frame_sizes; 97 _frame_pcs = frame_pcs; 98 _register_block = NEW_C_HEAP_ARRAY(intptr_t, RegisterMap::reg_count * 2, mtCompiler); 99 _return_type = return_type; 100 _initial_info = 0; 101 // PD (x86 only) 102 _counter_temp = 0; 103 _unpack_kind = exec_mode; 104 _sender_sp_temp = 0; 105 106 _total_frame_sizes = size_of_frames(); 107 assert(exec_mode >= 0 && exec_mode < Unpack_LIMIT, "Unexpected exec_mode"); 108 } 109 110 111 Deoptimization::UnrollBlock::~UnrollBlock() { 112 FREE_C_HEAP_ARRAY(intptr_t, _frame_sizes); 113 FREE_C_HEAP_ARRAY(intptr_t, _frame_pcs); 114 FREE_C_HEAP_ARRAY(intptr_t, _register_block); 115 } 116 117 118 intptr_t* Deoptimization::UnrollBlock::value_addr_at(int register_number) const { 119 assert(register_number < RegisterMap::reg_count, "checking register number"); 120 return &_register_block[register_number * 2]; 121 } 122 123 124 125 int Deoptimization::UnrollBlock::size_of_frames() const { 126 // Acount first for the adjustment of the initial frame 127 int result = _caller_adjustment; 128 for (int index = 0; index < number_of_frames(); index++) { 129 result += frame_sizes()[index]; 130 } 131 return result; 132 } 133 134 135 void Deoptimization::UnrollBlock::print() { 136 ttyLocker ttyl; 137 tty->print_cr("UnrollBlock"); 138 tty->print_cr(" size_of_deoptimized_frame = %d", _size_of_deoptimized_frame); 139 tty->print( " frame_sizes: "); 140 for (int index = 0; index < number_of_frames(); index++) { 141 tty->print(INTX_FORMAT " ", frame_sizes()[index]); 142 } 143 tty->cr(); 144 } 145 146 147 // In order to make fetch_unroll_info work properly with escape 148 // analysis, The method was changed from JRT_LEAF to JRT_BLOCK_ENTRY and 149 // ResetNoHandleMark and HandleMark were removed from it. The actual reallocation 150 // of previously eliminated objects occurs in realloc_objects, which is 151 // called from the method fetch_unroll_info_helper below. 152 JRT_BLOCK_ENTRY(Deoptimization::UnrollBlock*, Deoptimization::fetch_unroll_info(JavaThread* thread, int exec_mode)) 153 // It is actually ok to allocate handles in a leaf method. It causes no safepoints, 154 // but makes the entry a little slower. There is however a little dance we have to 155 // do in debug mode to get around the NoHandleMark code in the JRT_LEAF macro 156 157 // fetch_unroll_info() is called at the beginning of the deoptimization 158 // handler. Note this fact before we start generating temporary frames 159 // that can confuse an asynchronous stack walker. This counter is 160 // decremented at the end of unpack_frames(). 161 if (TraceDeoptimization) { 162 tty->print_cr("Deoptimizing thread " INTPTR_FORMAT, p2i(thread)); 163 } 164 thread->inc_in_deopt_handler(); 165 166 return fetch_unroll_info_helper(thread, exec_mode); 167 JRT_END 168 169 #if COMPILER2_OR_JVMCI 170 static bool eliminate_allocations(JavaThread* thread, int exec_mode, CompiledMethod* compiled_method, 171 frame& deoptee, RegisterMap& map, GrowableArray<compiledVFrame*>* chunk, 172 bool& deoptimized_objects) { 173 bool realloc_failures = false; 174 assert (chunk->at(0)->scope() != NULL,"expect only compiled java frames"); 175 176 JavaThread* deoptee_thread = chunk->at(0)->thread(); 177 assert(exec_mode == Deoptimization::Unpack_none || (deoptee_thread == thread), "a frame can only be deoptimized by the owner thread"); 178 179 GrowableArray<ScopeValue*>* objects = chunk->at(0)->scope()->objects(); 180 181 // The flag return_oop() indicates call sites which return oop 182 // in compiled code. Such sites include java method calls, 183 // runtime calls (for example, used to allocate new objects/arrays 184 // on slow code path) and any other calls generated in compiled code. 185 // It is not guaranteed that we can get such information here only 186 // by analyzing bytecode in deoptimized frames. This is why this flag 187 // is set during method compilation (see Compile::Process_OopMap_Node()). 188 // If the previous frame was popped or if we are dispatching an exception, 189 // we don't have an oop result. 190 bool save_oop_result = chunk->at(0)->scope()->return_oop() && !thread->popframe_forcing_deopt_reexecution() && (exec_mode == Deoptimization::Unpack_deopt); 191 Handle return_value; 192 if (save_oop_result) { 193 // Reallocation may trigger GC. If deoptimization happened on return from 194 // call which returns oop we need to save it since it is not in oopmap. 195 oop result = deoptee.saved_oop_result(&map); 196 assert(oopDesc::is_oop_or_null(result), "must be oop"); 197 return_value = Handle(thread, result); 198 assert(Universe::heap()->is_in_or_null(result), "must be heap pointer"); 199 if (TraceDeoptimization) { 200 ttyLocker ttyl; 201 tty->print_cr("SAVED OOP RESULT " INTPTR_FORMAT " in thread " INTPTR_FORMAT, p2i(result), p2i(thread)); 202 } 203 } 204 if (objects != NULL) { 205 if (exec_mode == Deoptimization::Unpack_none) { 206 assert(thread->thread_state() == _thread_in_vm, "assumption"); 207 Thread* THREAD = thread; 208 // Clear pending OOM if reallocation fails and return true indicating allocation failure 209 realloc_failures = Deoptimization::realloc_objects(thread, &deoptee, &map, objects, CHECK_AND_CLEAR_(true)); 210 deoptimized_objects = true; 211 } else { 212 JRT_BLOCK 213 realloc_failures = Deoptimization::realloc_objects(thread, &deoptee, &map, objects, THREAD); 214 JRT_END 215 } 216 bool skip_internal = (compiled_method != NULL) && !compiled_method->is_compiled_by_jvmci(); 217 Deoptimization::reassign_fields(&deoptee, &map, objects, realloc_failures, skip_internal); 218 #ifndef PRODUCT 219 if (TraceDeoptimization) { 220 ttyLocker ttyl; 221 tty->print_cr("REALLOC OBJECTS in thread " INTPTR_FORMAT, p2i(deoptee_thread)); 222 Deoptimization::print_objects(objects, realloc_failures); 223 } 224 #endif 225 } 226 if (save_oop_result) { 227 // Restore result. 228 deoptee.set_saved_oop_result(&map, return_value()); 229 } 230 return realloc_failures; 231 } 232 233 static void eliminate_locks(JavaThread* thread, GrowableArray<compiledVFrame*>* chunk, bool realloc_failures, 234 frame& deoptee, int exec_mode, bool& deoptimized_objects) { 235 JavaThread* deoptee_thread = chunk->at(0)->thread(); 236 assert(!EscapeBarrier::objs_are_deoptimized(deoptee_thread, deoptee.id()), "must relock just once"); 237 238 #ifndef PRODUCT 239 bool first = true; 240 #endif 241 for (int i = 0; i < chunk->length(); i++) { 242 compiledVFrame* cvf = chunk->at(i); 243 assert (cvf->scope() != NULL,"expect only compiled java frames"); 244 GrowableArray<MonitorInfo*>* monitors = cvf->monitors(); 245 if (monitors->is_nonempty()) { 246 bool relocked = Deoptimization::relock_objects(thread, monitors, deoptee_thread, deoptee, exec_mode, realloc_failures); 247 deoptimized_objects = deoptimized_objects || relocked; 248 #ifndef PRODUCT 249 if (PrintDeoptimizationDetails) { 250 ttyLocker ttyl; 251 for (int j = 0; j < monitors->length(); j++) { 252 MonitorInfo* mi = monitors->at(j); 253 if (mi->eliminated()) { 254 if (first) { 255 first = false; 256 tty->print_cr("RELOCK OBJECTS in thread " INTPTR_FORMAT, p2i(thread)); 257 } 258 if (exec_mode == Deoptimization::Unpack_none) { 259 ObjectMonitor* monitor = deoptee_thread->current_waiting_monitor(); 260 if (monitor != NULL && (oop)monitor->object() == mi->owner()) { 261 tty->print_cr(" object <" INTPTR_FORMAT "> DEFERRED relocking after wait", p2i(mi->owner())); 262 continue; 263 } 264 } 265 if (mi->owner_is_scalar_replaced()) { 266 Klass* k = java_lang_Class::as_Klass(mi->owner_klass()); 267 tty->print_cr(" failed reallocation for klass %s", k->external_name()); 268 } else { 269 tty->print_cr(" object <" INTPTR_FORMAT "> locked", p2i(mi->owner())); 270 } 271 } 272 } 273 } 274 #endif // !PRODUCT 275 } 276 } 277 } 278 279 // Deoptimize objects, that is reallocate and relock them, just before they escape through JVMTI. 280 // The given vframes cover one physical frame. 281 bool Deoptimization::deoptimize_objects_internal(JavaThread* thread, GrowableArray<compiledVFrame*>* chunk, bool& realloc_failures) { 282 frame deoptee = chunk->at(0)->fr(); 283 JavaThread* deoptee_thread = chunk->at(0)->thread(); 284 CompiledMethod* cm = deoptee.cb()->as_compiled_method_or_null(); 285 RegisterMap map(chunk->at(0)->register_map()); 286 bool deoptimized_objects = false; 287 288 bool const jvmci_enabled = JVMCI_ONLY(UseJVMCICompiler) NOT_JVMCI(false); 289 290 // Reallocate the non-escaping objects and restore their fields. 291 if (jvmci_enabled COMPILER2_PRESENT(|| (DoEscapeAnalysis && EliminateAllocations))) { 292 realloc_failures = eliminate_allocations(thread, Unpack_none, cm, deoptee, map, chunk, deoptimized_objects); 293 } 294 295 // Revoke biases of objects with eliminated locks in the given frame. 296 Deoptimization::revoke_for_object_deoptimization(deoptee_thread, deoptee, &map, thread); 297 298 // MonitorInfo structures used in eliminate_locks are not GC safe. 299 NoSafepointVerifier no_safepoint; 300 301 // Now relock objects if synchronization on them was eliminated. 302 if (jvmci_enabled COMPILER2_PRESENT(|| ((DoEscapeAnalysis || EliminateNestedLocks) && EliminateLocks))) { 303 eliminate_locks(thread, chunk, realloc_failures, deoptee, Unpack_none, deoptimized_objects); 304 } 305 return deoptimized_objects; 306 } 307 #endif // COMPILER2_OR_JVMCI 308 309 // This is factored, since it is both called from a JRT_LEAF (deoptimization) and a JRT_ENTRY (uncommon_trap) 310 Deoptimization::UnrollBlock* Deoptimization::fetch_unroll_info_helper(JavaThread* thread, int exec_mode) { 311 312 // Note: there is a safepoint safety issue here. No matter whether we enter 313 // via vanilla deopt or uncommon trap we MUST NOT stop at a safepoint once 314 // the vframeArray is created. 315 // 316 317 // Allocate our special deoptimization ResourceMark 318 DeoptResourceMark* dmark = new DeoptResourceMark(thread); 319 assert(thread->deopt_mark() == NULL, "Pending deopt!"); 320 thread->set_deopt_mark(dmark); 321 322 frame stub_frame = thread->last_frame(); // Makes stack walkable as side effect 323 RegisterMap map(thread, true); 324 RegisterMap dummy_map(thread, false); 325 // Now get the deoptee with a valid map 326 frame deoptee = stub_frame.sender(&map); 327 // Set the deoptee nmethod 328 assert(thread->deopt_compiled_method() == NULL, "Pending deopt!"); 329 CompiledMethod* cm = deoptee.cb()->as_compiled_method_or_null(); 330 thread->set_deopt_compiled_method(cm); 331 332 if (VerifyStack) { 333 thread->validate_frame_layout(); 334 } 335 336 // Create a growable array of VFrames where each VFrame represents an inlined 337 // Java frame. This storage is allocated with the usual system arena. 338 assert(deoptee.is_compiled_frame(), "Wrong frame type"); 339 GrowableArray<compiledVFrame*>* chunk = new GrowableArray<compiledVFrame*>(10); 340 vframe* vf = vframe::new_vframe(&deoptee, &map, thread); 341 while (!vf->is_top()) { 342 assert(vf->is_compiled_frame(), "Wrong frame type"); 343 chunk->push(compiledVFrame::cast(vf)); 344 vf = vf->sender(); 345 } 346 assert(vf->is_compiled_frame(), "Wrong frame type"); 347 chunk->push(compiledVFrame::cast(vf)); 348 349 bool realloc_failures = false; 350 351 #if COMPILER2_OR_JVMCI 352 #if INCLUDE_JVMCI 353 bool jvmci_enabled = true; 354 #else 355 bool jvmci_enabled = false; 356 #endif 357 358 // Reallocate the non-escaping objects and restore their fields. Then 359 // relock objects if synchronization on them was eliminated. 360 if (jvmci_enabled COMPILER2_PRESENT( || (DoEscapeAnalysis && EliminateAllocations) )) { 361 bool unused; 362 realloc_failures = eliminate_allocations(thread, exec_mode, cm, deoptee, map, chunk, unused); 363 } 364 #endif // COMPILER2_OR_JVMCI 365 366 // Revoke biases, done with in java state. 367 // No safepoints allowed after this 368 revoke_from_deopt_handler(thread, deoptee, &map); 369 370 // Ensure that no safepoint is taken after pointers have been stored 371 // in fields of rematerialized objects. If a safepoint occurs from here on 372 // out the java state residing in the vframeArray will be missed. 373 // Locks may be rebaised in a safepoint. 374 NoSafepointVerifier no_safepoint; 375 376 #if COMPILER2_OR_JVMCI 377 if ((jvmci_enabled COMPILER2_PRESENT( || ((DoEscapeAnalysis || EliminateNestedLocks) && EliminateLocks) )) 378 && !EscapeBarrier::objs_are_deoptimized(thread, deoptee.id())) { 379 bool unused; 380 eliminate_locks(thread, chunk, realloc_failures, deoptee, exec_mode, unused); 381 } 382 #endif // COMPILER2_OR_JVMCI 383 384 ScopeDesc* trap_scope = chunk->at(0)->scope(); 385 Handle exceptionObject; 386 if (trap_scope->rethrow_exception()) { 387 if (PrintDeoptimizationDetails) { 388 tty->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()); 389 } 390 GrowableArray<ScopeValue*>* expressions = trap_scope->expressions(); 391 guarantee(expressions != NULL && expressions->length() > 0, "must have exception to throw"); 392 ScopeValue* topOfStack = expressions->top(); 393 exceptionObject = StackValue::create_stack_value(&deoptee, &map, topOfStack)->get_obj(); 394 guarantee(exceptionObject() != NULL, "exception oop can not be null"); 395 } 396 397 vframeArray* array = create_vframeArray(thread, deoptee, &map, chunk, realloc_failures); 398 #if COMPILER2_OR_JVMCI 399 if (realloc_failures) { 400 pop_frames_failed_reallocs(thread, array); 401 } 402 #endif 403 404 assert(thread->vframe_array_head() == NULL, "Pending deopt!"); 405 thread->set_vframe_array_head(array); 406 407 // Now that the vframeArray has been created if we have any deferred local writes 408 // added by jvmti then we can free up that structure as the data is now in the 409 // vframeArray 410 411 if (JvmtiDeferredUpdates::deferred_locals(thread) != NULL) { 412 GrowableArray<jvmtiDeferredLocalVariableSet*>* list = JvmtiDeferredUpdates::deferred_locals(thread); 413 int i = 0; 414 do { 415 // Because of inlining we could have multiple vframes for a single frame 416 // and several of the vframes could have deferred writes. Find them all. 417 if (list->at(i)->id() == array->original().id()) { 418 jvmtiDeferredLocalVariableSet* dlv = list->at(i); 419 list->remove_at(i); 420 // individual jvmtiDeferredLocalVariableSet are CHeapObj's 421 delete dlv; 422 } else { 423 i++; 424 } 425 } while ( i < list->length() ); 426 if (list->length() == 0) { 427 JvmtiDeferredUpdates* updates = thread->deferred_updates(); 428 thread->set_deferred_updates(NULL); 429 // free deferred updates. 430 delete updates; 431 } 432 433 } 434 435 // Compute the caller frame based on the sender sp of stub_frame and stored frame sizes info. 436 CodeBlob* cb = stub_frame.cb(); 437 // Verify we have the right vframeArray 438 assert(cb->frame_size() >= 0, "Unexpected frame size"); 439 intptr_t* unpack_sp = stub_frame.sp() + cb->frame_size(); 440 441 // If the deopt call site is a MethodHandle invoke call site we have 442 // to adjust the unpack_sp. 443 nmethod* deoptee_nm = deoptee.cb()->as_nmethod_or_null(); 444 if (deoptee_nm != NULL && deoptee_nm->is_method_handle_return(deoptee.pc())) 445 unpack_sp = deoptee.unextended_sp(); 446 447 #ifdef ASSERT 448 assert(cb->is_deoptimization_stub() || 449 cb->is_uncommon_trap_stub() || 450 strcmp("Stub<DeoptimizationStub.deoptimizationHandler>", cb->name()) == 0 || 451 strcmp("Stub<UncommonTrapStub.uncommonTrapHandler>", cb->name()) == 0, 452 "unexpected code blob: %s", cb->name()); 453 #endif 454 455 // This is a guarantee instead of an assert because if vframe doesn't match 456 // we will unpack the wrong deoptimized frame and wind up in strange places 457 // where it will be very difficult to figure out what went wrong. Better 458 // to die an early death here than some very obscure death later when the 459 // trail is cold. 460 // Note: on ia64 this guarantee can be fooled by frames with no memory stack 461 // in that it will fail to detect a problem when there is one. This needs 462 // more work in tiger timeframe. 463 guarantee(array->unextended_sp() == unpack_sp, "vframe_array_head must contain the vframeArray to unpack"); 464 465 int number_of_frames = array->frames(); 466 467 // Compute the vframes' sizes. Note that frame_sizes[] entries are ordered from outermost to innermost 468 // virtual activation, which is the reverse of the elements in the vframes array. 469 intptr_t* frame_sizes = NEW_C_HEAP_ARRAY(intptr_t, number_of_frames, mtCompiler); 470 // +1 because we always have an interpreter return address for the final slot. 471 address* frame_pcs = NEW_C_HEAP_ARRAY(address, number_of_frames + 1, mtCompiler); 472 int popframe_extra_args = 0; 473 // Create an interpreter return address for the stub to use as its return 474 // address so the skeletal frames are perfectly walkable 475 frame_pcs[number_of_frames] = Interpreter::deopt_entry(vtos, 0); 476 477 // PopFrame requires that the preserved incoming arguments from the recently-popped topmost 478 // activation be put back on the expression stack of the caller for reexecution 479 if (JvmtiExport::can_pop_frame() && thread->popframe_forcing_deopt_reexecution()) { 480 popframe_extra_args = in_words(thread->popframe_preserved_args_size_in_words()); 481 } 482 483 // Find the current pc for sender of the deoptee. Since the sender may have been deoptimized 484 // itself since the deoptee vframeArray was created we must get a fresh value of the pc rather 485 // than simply use array->sender.pc(). This requires us to walk the current set of frames 486 // 487 frame deopt_sender = stub_frame.sender(&dummy_map); // First is the deoptee frame 488 deopt_sender = deopt_sender.sender(&dummy_map); // Now deoptee caller 489 490 // It's possible that the number of parameters at the call site is 491 // different than number of arguments in the callee when method 492 // handles are used. If the caller is interpreted get the real 493 // value so that the proper amount of space can be added to it's 494 // frame. 495 bool caller_was_method_handle = false; 496 if (deopt_sender.is_interpreted_frame()) { 497 methodHandle method(thread, deopt_sender.interpreter_frame_method()); 498 Bytecode_invoke cur = Bytecode_invoke_check(method, deopt_sender.interpreter_frame_bci()); 499 if (cur.is_invokedynamic() || cur.is_invokehandle()) { 500 // Method handle invokes may involve fairly arbitrary chains of 501 // calls so it's impossible to know how much actual space the 502 // caller has for locals. 503 caller_was_method_handle = true; 504 } 505 } 506 507 // 508 // frame_sizes/frame_pcs[0] oldest frame (int or c2i) 509 // frame_sizes/frame_pcs[1] next oldest frame (int) 510 // frame_sizes/frame_pcs[n] youngest frame (int) 511 // 512 // Now a pc in frame_pcs is actually the return address to the frame's caller (a frame 513 // owns the space for the return address to it's caller). Confusing ain't it. 514 // 515 // The vframe array can address vframes with indices running from 516 // 0.._frames-1. Index 0 is the youngest frame and _frame - 1 is the oldest (root) frame. 517 // When we create the skeletal frames we need the oldest frame to be in the zero slot 518 // in the frame_sizes/frame_pcs so the assembly code can do a trivial walk. 519 // so things look a little strange in this loop. 520 // 521 int callee_parameters = 0; 522 int callee_locals = 0; 523 for (int index = 0; index < array->frames(); index++ ) { 524 // frame[number_of_frames - 1 ] = on_stack_size(youngest) 525 // frame[number_of_frames - 2 ] = on_stack_size(sender(youngest)) 526 // frame[number_of_frames - 3 ] = on_stack_size(sender(sender(youngest))) 527 frame_sizes[number_of_frames - 1 - index] = BytesPerWord * array->element(index)->on_stack_size(callee_parameters, 528 callee_locals, 529 index == 0, 530 popframe_extra_args); 531 // This pc doesn't have to be perfect just good enough to identify the frame 532 // as interpreted so the skeleton frame will be walkable 533 // The correct pc will be set when the skeleton frame is completely filled out 534 // The final pc we store in the loop is wrong and will be overwritten below 535 frame_pcs[number_of_frames - 1 - index ] = Interpreter::deopt_entry(vtos, 0) - frame::pc_return_offset; 536 537 callee_parameters = array->element(index)->method()->size_of_parameters(); 538 callee_locals = array->element(index)->method()->max_locals(); 539 popframe_extra_args = 0; 540 } 541 542 // Compute whether the root vframe returns a float or double value. 543 BasicType return_type; 544 { 545 methodHandle method(thread, array->element(0)->method()); 546 Bytecode_invoke invoke = Bytecode_invoke_check(method, array->element(0)->bci()); 547 return_type = invoke.is_valid() ? invoke.result_type() : T_ILLEGAL; 548 } 549 550 // Compute information for handling adapters and adjusting the frame size of the caller. 551 int caller_adjustment = 0; 552 553 // Compute the amount the oldest interpreter frame will have to adjust 554 // its caller's stack by. If the caller is a compiled frame then 555 // we pretend that the callee has no parameters so that the 556 // extension counts for the full amount of locals and not just 557 // locals-parms. This is because without a c2i adapter the parm 558 // area as created by the compiled frame will not be usable by 559 // the interpreter. (Depending on the calling convention there 560 // may not even be enough space). 561 562 // QQQ I'd rather see this pushed down into last_frame_adjust 563 // and have it take the sender (aka caller). 564 565 if (deopt_sender.is_compiled_frame() || caller_was_method_handle) { 566 caller_adjustment = last_frame_adjust(0, callee_locals); 567 } else if (callee_locals > callee_parameters) { 568 // The caller frame may need extending to accommodate 569 // non-parameter locals of the first unpacked interpreted frame. 570 // Compute that adjustment. 571 caller_adjustment = last_frame_adjust(callee_parameters, callee_locals); 572 } 573 574 // If the sender is deoptimized the we must retrieve the address of the handler 575 // since the frame will "magically" show the original pc before the deopt 576 // and we'd undo the deopt. 577 578 frame_pcs[0] = deopt_sender.raw_pc(); 579 580 assert(CodeCache::find_blob_unsafe(frame_pcs[0]) != NULL, "bad pc"); 581 582 #if INCLUDE_JVMCI 583 if (exceptionObject() != NULL) { 584 thread->set_exception_oop(exceptionObject()); 585 exec_mode = Unpack_exception; 586 } 587 #endif 588 589 if (thread->frames_to_pop_failed_realloc() > 0 && exec_mode != Unpack_uncommon_trap) { 590 assert(thread->has_pending_exception(), "should have thrown OOME"); 591 thread->set_exception_oop(thread->pending_exception()); 592 thread->clear_pending_exception(); 593 exec_mode = Unpack_exception; 594 } 595 596 #if INCLUDE_JVMCI 597 if (thread->frames_to_pop_failed_realloc() > 0) { 598 thread->set_pending_monitorenter(false); 599 } 600 #endif 601 602 UnrollBlock* info = new UnrollBlock(array->frame_size() * BytesPerWord, 603 caller_adjustment * BytesPerWord, 604 caller_was_method_handle ? 0 : callee_parameters, 605 number_of_frames, 606 frame_sizes, 607 frame_pcs, 608 return_type, 609 exec_mode); 610 // On some platforms, we need a way to pass some platform dependent 611 // information to the unpacking code so the skeletal frames come out 612 // correct (initial fp value, unextended sp, ...) 613 info->set_initial_info((intptr_t) array->sender().initial_deoptimization_info()); 614 615 if (array->frames() > 1) { 616 if (VerifyStack && TraceDeoptimization) { 617 ttyLocker ttyl; 618 tty->print_cr("Deoptimizing method containing inlining"); 619 } 620 } 621 622 array->set_unroll_block(info); 623 return info; 624 } 625 626 // Called to cleanup deoptimization data structures in normal case 627 // after unpacking to stack and when stack overflow error occurs 628 void Deoptimization::cleanup_deopt_info(JavaThread *thread, 629 vframeArray *array) { 630 631 // Get array if coming from exception 632 if (array == NULL) { 633 array = thread->vframe_array_head(); 634 } 635 thread->set_vframe_array_head(NULL); 636 637 // Free the previous UnrollBlock 638 vframeArray* old_array = thread->vframe_array_last(); 639 thread->set_vframe_array_last(array); 640 641 if (old_array != NULL) { 642 UnrollBlock* old_info = old_array->unroll_block(); 643 old_array->set_unroll_block(NULL); 644 delete old_info; 645 delete old_array; 646 } 647 648 // Deallocate any resource creating in this routine and any ResourceObjs allocated 649 // inside the vframeArray (StackValueCollections) 650 651 delete thread->deopt_mark(); 652 thread->set_deopt_mark(NULL); 653 thread->set_deopt_compiled_method(NULL); 654 655 656 if (JvmtiExport::can_pop_frame()) { 657 // Regardless of whether we entered this routine with the pending 658 // popframe condition bit set, we should always clear it now 659 thread->clear_popframe_condition(); 660 } 661 662 // unpack_frames() is called at the end of the deoptimization handler 663 // and (in C2) at the end of the uncommon trap handler. Note this fact 664 // so that an asynchronous stack walker can work again. This counter is 665 // incremented at the beginning of fetch_unroll_info() and (in C2) at 666 // the beginning of uncommon_trap(). 667 thread->dec_in_deopt_handler(); 668 } 669 670 // Moved from cpu directories because none of the cpus has callee save values. 671 // If a cpu implements callee save values, move this to deoptimization_<cpu>.cpp. 672 void Deoptimization::unwind_callee_save_values(frame* f, vframeArray* vframe_array) { 673 674 // This code is sort of the equivalent of C2IAdapter::setup_stack_frame back in 675 // the days we had adapter frames. When we deoptimize a situation where a 676 // compiled caller calls a compiled caller will have registers it expects 677 // to survive the call to the callee. If we deoptimize the callee the only 678 // way we can restore these registers is to have the oldest interpreter 679 // frame that we create restore these values. That is what this routine 680 // will accomplish. 681 682 // At the moment we have modified c2 to not have any callee save registers 683 // so this problem does not exist and this routine is just a place holder. 684 685 assert(f->is_interpreted_frame(), "must be interpreted"); 686 } 687 688 // Return BasicType of value being returned 689 JRT_LEAF(BasicType, Deoptimization::unpack_frames(JavaThread* thread, int exec_mode)) 690 691 // We are already active in the special DeoptResourceMark any ResourceObj's we 692 // allocate will be freed at the end of the routine. 693 694 // It is actually ok to allocate handles in a leaf method. It causes no safepoints, 695 // but makes the entry a little slower. There is however a little dance we have to 696 // do in debug mode to get around the NoHandleMark code in the JRT_LEAF macro 697 ResetNoHandleMark rnhm; // No-op in release/product versions 698 HandleMark hm; 699 700 frame stub_frame = thread->last_frame(); 701 702 // Since the frame to unpack is the top frame of this thread, the vframe_array_head 703 // must point to the vframeArray for the unpack frame. 704 vframeArray* array = thread->vframe_array_head(); 705 706 #ifndef PRODUCT 707 if (TraceDeoptimization) { 708 ttyLocker ttyl; 709 tty->print_cr("DEOPT UNPACKING thread " INTPTR_FORMAT " vframeArray " INTPTR_FORMAT " mode %d", 710 p2i(thread), p2i(array), exec_mode); 711 } 712 #endif 713 Events::log_deopt_message(thread, "DEOPT UNPACKING pc=" INTPTR_FORMAT " sp=" INTPTR_FORMAT " mode %d", 714 p2i(stub_frame.pc()), p2i(stub_frame.sp()), exec_mode); 715 716 UnrollBlock* info = array->unroll_block(); 717 718 // We set the last_Java frame. But the stack isn't really parsable here. So we 719 // clear it to make sure JFR understands not to try and walk stacks from events 720 // in here. 721 intptr_t* sp = thread->frame_anchor()->last_Java_sp(); 722 thread->frame_anchor()->set_last_Java_sp(NULL); 723 724 // Unpack the interpreter frames and any adapter frame (c2 only) we might create. 725 array->unpack_to_stack(stub_frame, exec_mode, info->caller_actual_parameters()); 726 727 thread->frame_anchor()->set_last_Java_sp(sp); 728 729 BasicType bt = info->return_type(); 730 731 // If we have an exception pending, claim that the return type is an oop 732 // so the deopt_blob does not overwrite the exception_oop. 733 734 if (exec_mode == Unpack_exception) 735 bt = T_OBJECT; 736 737 // Cleanup thread deopt data 738 cleanup_deopt_info(thread, array); 739 740 #ifndef PRODUCT 741 if (VerifyStack) { 742 ResourceMark res_mark; 743 // Clear pending exception to not break verification code (restored afterwards) 744 PRESERVE_EXCEPTION_MARK; 745 746 thread->validate_frame_layout(); 747 748 // Verify that the just-unpacked frames match the interpreter's 749 // notions of expression stack and locals 750 vframeArray* cur_array = thread->vframe_array_last(); 751 RegisterMap rm(thread, false); 752 rm.set_include_argument_oops(false); 753 bool is_top_frame = true; 754 int callee_size_of_parameters = 0; 755 int callee_max_locals = 0; 756 for (int i = 0; i < cur_array->frames(); i++) { 757 vframeArrayElement* el = cur_array->element(i); 758 frame* iframe = el->iframe(); 759 guarantee(iframe->is_interpreted_frame(), "Wrong frame type"); 760 761 // Get the oop map for this bci 762 InterpreterOopMap mask; 763 int cur_invoke_parameter_size = 0; 764 bool try_next_mask = false; 765 int next_mask_expression_stack_size = -1; 766 int top_frame_expression_stack_adjustment = 0; 767 methodHandle mh(thread, iframe->interpreter_frame_method()); 768 OopMapCache::compute_one_oop_map(mh, iframe->interpreter_frame_bci(), &mask); 769 BytecodeStream str(mh, iframe->interpreter_frame_bci()); 770 int max_bci = mh->code_size(); 771 // Get to the next bytecode if possible 772 assert(str.bci() < max_bci, "bci in interpreter frame out of bounds"); 773 // Check to see if we can grab the number of outgoing arguments 774 // at an uncommon trap for an invoke (where the compiler 775 // generates debug info before the invoke has executed) 776 Bytecodes::Code cur_code = str.next(); 777 if (Bytecodes::is_invoke(cur_code)) { 778 Bytecode_invoke invoke(mh, iframe->interpreter_frame_bci()); 779 cur_invoke_parameter_size = invoke.size_of_parameters(); 780 if (i != 0 && !invoke.is_invokedynamic() && MethodHandles::has_member_arg(invoke.klass(), invoke.name())) { 781 callee_size_of_parameters++; 782 } 783 } 784 if (str.bci() < max_bci) { 785 Bytecodes::Code next_code = str.next(); 786 if (next_code >= 0) { 787 // The interpreter oop map generator reports results before 788 // the current bytecode has executed except in the case of 789 // calls. It seems to be hard to tell whether the compiler 790 // has emitted debug information matching the "state before" 791 // a given bytecode or the state after, so we try both 792 if (!Bytecodes::is_invoke(cur_code) && cur_code != Bytecodes::_athrow) { 793 // Get expression stack size for the next bytecode 794 InterpreterOopMap next_mask; 795 OopMapCache::compute_one_oop_map(mh, str.bci(), &next_mask); 796 next_mask_expression_stack_size = next_mask.expression_stack_size(); 797 if (Bytecodes::is_invoke(next_code)) { 798 Bytecode_invoke invoke(mh, str.bci()); 799 next_mask_expression_stack_size += invoke.size_of_parameters(); 800 } 801 // Need to subtract off the size of the result type of 802 // the bytecode because this is not described in the 803 // debug info but returned to the interpreter in the TOS 804 // caching register 805 BasicType bytecode_result_type = Bytecodes::result_type(cur_code); 806 if (bytecode_result_type != T_ILLEGAL) { 807 top_frame_expression_stack_adjustment = type2size[bytecode_result_type]; 808 } 809 assert(top_frame_expression_stack_adjustment >= 0, "stack adjustment must be positive"); 810 try_next_mask = true; 811 } 812 } 813 } 814 815 // Verify stack depth and oops in frame 816 // This assertion may be dependent on the platform we're running on and may need modification (tested on x86 and sparc) 817 if (!( 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 - 824 top_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 { 830 ttyLocker ttyl; 831 832 // Print out some information that will help us debug the problem 833 tty->print_cr("Wrong number of expression stack elements during deoptimization"); 834 tty->print_cr(" Error occurred while verifying frame %d (0..%d, 0 is topmost)", i, cur_array->frames() - 1); 835 tty->print_cr(" Fabricated interpreter frame had %d expression stack elements", 836 iframe->interpreter_frame_expression_stack_size()); 837 tty->print_cr(" Interpreter oop map had %d expression stack elements", mask.expression_stack_size()); 838 tty->print_cr(" try_next_mask = %d", try_next_mask); 839 tty->print_cr(" next_mask_expression_stack_size = %d", next_mask_expression_stack_size); 840 tty->print_cr(" callee_size_of_parameters = %d", callee_size_of_parameters); 841 tty->print_cr(" callee_max_locals = %d", callee_max_locals); 842 tty->print_cr(" top_frame_expression_stack_adjustment = %d", top_frame_expression_stack_adjustment); 843 tty->print_cr(" exec_mode = %d", exec_mode); 844 tty->print_cr(" cur_invoke_parameter_size = %d", cur_invoke_parameter_size); 845 tty->print_cr(" Thread = " INTPTR_FORMAT ", thread ID = %d", p2i(thread), thread->osthread()->thread_id()); 846 tty->print_cr(" Interpreted frames:"); 847 for (int k = 0; k < cur_array->frames(); k++) { 848 vframeArrayElement* el = cur_array->element(k); 849 tty->print_cr(" %s (bci %d)", el->method()->name_and_sig_as_C_string(), el->bci()); 850 } 851 cur_array->print_on_2(tty); 852 } // release tty lock before calling guarantee 853 guarantee(false, "wrong number of expression stack elements during deopt"); 854 } 855 VerifyOopClosure verify; 856 iframe->oops_interpreted_do(&verify, &rm, false); 857 callee_size_of_parameters = mh->size_of_parameters(); 858 callee_max_locals = mh->max_locals(); 859 is_top_frame = false; 860 } 861 } 862 #endif /* !PRODUCT */ 863 864 return bt; 865 JRT_END 866 867 class DeoptimizeMarkedClosure : public HandshakeClosure { 868 public: 869 DeoptimizeMarkedClosure() : HandshakeClosure("Deoptimize") {} 870 void do_thread(Thread* thread) { 871 JavaThread* jt = (JavaThread*)thread; 872 jt->deoptimize_marked_methods(); 873 } 874 }; 875 876 void Deoptimization::deoptimize_all_marked(nmethod* nmethod_only) { 877 ResourceMark rm; 878 DeoptimizationMarker dm; 879 880 // Make the dependent methods not entrant 881 if (nmethod_only != NULL) { 882 nmethod_only->mark_for_deoptimization(); 883 nmethod_only->make_not_entrant(); 884 } else { 885 MutexLocker mu(SafepointSynchronize::is_at_safepoint() ? NULL : CodeCache_lock, Mutex::_no_safepoint_check_flag); 886 CodeCache::make_marked_nmethods_not_entrant(); 887 } 888 889 DeoptimizeMarkedClosure deopt; 890 if (SafepointSynchronize::is_at_safepoint()) { 891 Threads::java_threads_do(&deopt); 892 } else { 893 Handshake::execute(&deopt); 894 } 895 } 896 897 Deoptimization::DeoptAction Deoptimization::_unloaded_action 898 = Deoptimization::Action_reinterpret; 899 900 901 902 #if INCLUDE_JVMCI || INCLUDE_AOT 903 template<typename CacheType> 904 class BoxCacheBase : public CHeapObj<mtCompiler> { 905 protected: 906 static InstanceKlass* find_cache_klass(Symbol* klass_name, TRAPS) { 907 ResourceMark rm; 908 char* klass_name_str = klass_name->as_C_string(); 909 Klass* k = SystemDictionary::find(klass_name, Handle(), Handle(), THREAD); 910 guarantee(k != NULL, "%s must be loaded", klass_name_str); 911 InstanceKlass* ik = InstanceKlass::cast(k); 912 guarantee(ik->is_initialized(), "%s must be initialized", klass_name_str); 913 CacheType::compute_offsets(ik); 914 return ik; 915 } 916 }; 917 918 template<typename PrimitiveType, typename CacheType, typename BoxType> class BoxCache : public BoxCacheBase<CacheType> { 919 PrimitiveType _low; 920 PrimitiveType _high; 921 jobject _cache; 922 protected: 923 static BoxCache<PrimitiveType, CacheType, BoxType> *_singleton; 924 BoxCache(Thread* thread) { 925 InstanceKlass* ik = BoxCacheBase<CacheType>::find_cache_klass(CacheType::symbol(), thread); 926 objArrayOop cache = CacheType::cache(ik); 927 assert(cache->length() > 0, "Empty cache"); 928 _low = BoxType::value(cache->obj_at(0)); 929 _high = _low + cache->length() - 1; 930 _cache = JNIHandles::make_global(Handle(thread, cache)); 931 } 932 ~BoxCache() { 933 JNIHandles::destroy_global(_cache); 934 } 935 public: 936 static BoxCache<PrimitiveType, CacheType, BoxType>* singleton(Thread* thread) { 937 if (_singleton == NULL) { 938 BoxCache<PrimitiveType, CacheType, BoxType>* s = new BoxCache<PrimitiveType, CacheType, BoxType>(thread); 939 if (!Atomic::replace_if_null(&_singleton, s)) { 940 delete s; 941 } 942 } 943 return _singleton; 944 } 945 oop lookup(PrimitiveType value) { 946 if (_low <= value && value <= _high) { 947 int offset = value - _low; 948 return objArrayOop(JNIHandles::resolve_non_null(_cache))->obj_at(offset); 949 } 950 return NULL; 951 } 952 oop lookup_raw(intptr_t raw_value) { 953 // Have to cast to avoid little/big-endian problems. 954 if (sizeof(PrimitiveType) > sizeof(jint)) { 955 jlong value = (jlong)raw_value; 956 return lookup(value); 957 } 958 PrimitiveType value = (PrimitiveType)*((jint*)&raw_value); 959 return lookup(value); 960 } 961 }; 962 963 typedef BoxCache<jint, java_lang_Integer_IntegerCache, java_lang_Integer> IntegerBoxCache; 964 typedef BoxCache<jlong, java_lang_Long_LongCache, java_lang_Long> LongBoxCache; 965 typedef BoxCache<jchar, java_lang_Character_CharacterCache, java_lang_Character> CharacterBoxCache; 966 typedef BoxCache<jshort, java_lang_Short_ShortCache, java_lang_Short> ShortBoxCache; 967 typedef BoxCache<jbyte, java_lang_Byte_ByteCache, java_lang_Byte> ByteBoxCache; 968 969 template<> BoxCache<jint, java_lang_Integer_IntegerCache, java_lang_Integer>* BoxCache<jint, java_lang_Integer_IntegerCache, java_lang_Integer>::_singleton = NULL; 970 template<> BoxCache<jlong, java_lang_Long_LongCache, java_lang_Long>* BoxCache<jlong, java_lang_Long_LongCache, java_lang_Long>::_singleton = NULL; 971 template<> BoxCache<jchar, java_lang_Character_CharacterCache, java_lang_Character>* BoxCache<jchar, java_lang_Character_CharacterCache, java_lang_Character>::_singleton = NULL; 972 template<> BoxCache<jshort, java_lang_Short_ShortCache, java_lang_Short>* BoxCache<jshort, java_lang_Short_ShortCache, java_lang_Short>::_singleton = NULL; 973 template<> BoxCache<jbyte, java_lang_Byte_ByteCache, java_lang_Byte>* BoxCache<jbyte, java_lang_Byte_ByteCache, java_lang_Byte>::_singleton = NULL; 974 975 class BooleanBoxCache : public BoxCacheBase<java_lang_Boolean> { 976 jobject _true_cache; 977 jobject _false_cache; 978 protected: 979 static BooleanBoxCache *_singleton; 980 BooleanBoxCache(Thread *thread) { 981 InstanceKlass* ik = find_cache_klass(java_lang_Boolean::symbol(), thread); 982 _true_cache = JNIHandles::make_global(Handle(thread, java_lang_Boolean::get_TRUE(ik))); 983 _false_cache = JNIHandles::make_global(Handle(thread, java_lang_Boolean::get_FALSE(ik))); 984 } 985 ~BooleanBoxCache() { 986 JNIHandles::destroy_global(_true_cache); 987 JNIHandles::destroy_global(_false_cache); 988 } 989 public: 990 static BooleanBoxCache* singleton(Thread* thread) { 991 if (_singleton == NULL) { 992 BooleanBoxCache* s = new BooleanBoxCache(thread); 993 if (!Atomic::replace_if_null(&_singleton, s)) { 994 delete s; 995 } 996 } 997 return _singleton; 998 } 999 oop lookup_raw(intptr_t raw_value) { 1000 // Have to cast to avoid little/big-endian problems. 1001 jboolean value = (jboolean)*((jint*)&raw_value); 1002 return lookup(value); 1003 } 1004 oop lookup(jboolean value) { 1005 if (value != 0) { 1006 return JNIHandles::resolve_non_null(_true_cache); 1007 } 1008 return JNIHandles::resolve_non_null(_false_cache); 1009 } 1010 }; 1011 1012 BooleanBoxCache* BooleanBoxCache::_singleton = NULL; 1013 1014 oop Deoptimization::get_cached_box(AutoBoxObjectValue* bv, frame* fr, RegisterMap* reg_map, TRAPS) { 1015 Klass* k = java_lang_Class::as_Klass(bv->klass()->as_ConstantOopReadValue()->value()()); 1016 BasicType box_type = SystemDictionary::box_klass_type(k); 1017 if (box_type != T_OBJECT) { 1018 StackValue* value = StackValue::create_stack_value(fr, reg_map, bv->field_at(box_type == T_LONG ? 1 : 0)); 1019 switch(box_type) { 1020 case T_INT: return IntegerBoxCache::singleton(THREAD)->lookup_raw(value->get_int()); 1021 case T_CHAR: return CharacterBoxCache::singleton(THREAD)->lookup_raw(value->get_int()); 1022 case T_SHORT: return ShortBoxCache::singleton(THREAD)->lookup_raw(value->get_int()); 1023 case T_BYTE: return ByteBoxCache::singleton(THREAD)->lookup_raw(value->get_int()); 1024 case T_BOOLEAN: return BooleanBoxCache::singleton(THREAD)->lookup_raw(value->get_int()); 1025 case T_LONG: return LongBoxCache::singleton(THREAD)->lookup_raw(value->get_int()); 1026 default:; 1027 } 1028 } 1029 return NULL; 1030 } 1031 #endif // INCLUDE_JVMCI || INCLUDE_AOT 1032 1033 #if COMPILER2_OR_JVMCI 1034 bool Deoptimization::realloc_objects(JavaThread* thread, frame* fr, RegisterMap* reg_map, GrowableArray<ScopeValue*>* objects, TRAPS) { 1035 Handle pending_exception(THREAD, thread->pending_exception()); 1036 const char* exception_file = thread->exception_file(); 1037 int exception_line = thread->exception_line(); 1038 thread->clear_pending_exception(); 1039 1040 bool failures = false; 1041 1042 for (int i = 0; i < objects->length(); i++) { 1043 assert(objects->at(i)->is_object(), "invalid debug information"); 1044 ObjectValue* sv = (ObjectValue*) objects->at(i); 1045 1046 Klass* k = java_lang_Class::as_Klass(sv->klass()->as_ConstantOopReadValue()->value()()); 1047 oop obj = NULL; 1048 1049 if (k->is_instance_klass()) { 1050 #if INCLUDE_JVMCI || INCLUDE_AOT 1051 CompiledMethod* cm = fr->cb()->as_compiled_method_or_null(); 1052 if (cm->is_compiled_by_jvmci() && sv->is_auto_box()) { 1053 AutoBoxObjectValue* abv = (AutoBoxObjectValue*) sv; 1054 obj = get_cached_box(abv, fr, reg_map, THREAD); 1055 if (obj != NULL) { 1056 // Set the flag to indicate the box came from a cache, so that we can skip the field reassignment for it. 1057 abv->set_cached(true); 1058 } 1059 } 1060 #endif // INCLUDE_JVMCI || INCLUDE_AOT 1061 InstanceKlass* ik = InstanceKlass::cast(k); 1062 if (obj == NULL) { 1063 obj = ik->allocate_instance(THREAD); 1064 } 1065 } else if (k->is_typeArray_klass()) { 1066 TypeArrayKlass* ak = TypeArrayKlass::cast(k); 1067 assert(sv->field_size() % type2size[ak->element_type()] == 0, "non-integral array length"); 1068 int len = sv->field_size() / type2size[ak->element_type()]; 1069 obj = ak->allocate(len, THREAD); 1070 } else if (k->is_objArray_klass()) { 1071 ObjArrayKlass* ak = ObjArrayKlass::cast(k); 1072 obj = ak->allocate(sv->field_size(), THREAD); 1073 } 1074 1075 if (obj == NULL) { 1076 failures = true; 1077 } 1078 1079 assert(sv->value().is_null(), "redundant reallocation"); 1080 assert(obj != NULL || HAS_PENDING_EXCEPTION, "allocation should succeed or we should get an exception"); 1081 CLEAR_PENDING_EXCEPTION; 1082 sv->set_value(obj); 1083 } 1084 1085 if (failures) { 1086 THROW_OOP_(Universe::out_of_memory_error_realloc_objects(), failures); 1087 } else if (pending_exception.not_null()) { 1088 thread->set_pending_exception(pending_exception(), exception_file, exception_line); 1089 } 1090 1091 return failures; 1092 } 1093 1094 #if INCLUDE_JVMCI 1095 /** 1096 * For primitive types whose kind gets "erased" at runtime (shorts become stack ints), 1097 * we need to somehow be able to recover the actual kind to be able to write the correct 1098 * amount of bytes. 1099 * For that purpose, this method assumes that, for an entry spanning n bytes at index i, 1100 * the entries at index n + 1 to n + i are 'markers'. 1101 * For example, if we were writing a short at index 4 of a byte array of size 8, the 1102 * expected form of the array would be: 1103 * 1104 * {b0, b1, b2, b3, INT, marker, b6, b7} 1105 * 1106 * Thus, in order to get back the size of the entry, we simply need to count the number 1107 * of marked entries 1108 * 1109 * @param virtualArray the virtualized byte array 1110 * @param i index of the virtual entry we are recovering 1111 * @return The number of bytes the entry spans 1112 */ 1113 static int count_number_of_bytes_for_entry(ObjectValue *virtualArray, int i) { 1114 int index = i; 1115 while (++index < virtualArray->field_size() && 1116 virtualArray->field_at(index)->is_marker()) {} 1117 return index - i; 1118 } 1119 1120 /** 1121 * If there was a guarantee for byte array to always start aligned to a long, we could 1122 * do a simple check on the parity of the index. Unfortunately, that is not always the 1123 * case. Thus, we check alignment of the actual address we are writing to. 1124 * In the unlikely case index 0 is 5-aligned for example, it would then be possible to 1125 * write a long to index 3. 1126 */ 1127 static jbyte* check_alignment_get_addr(typeArrayOop obj, int index, int expected_alignment) { 1128 jbyte* res = obj->byte_at_addr(index); 1129 assert((((intptr_t) res) % expected_alignment) == 0, "Non-aligned write"); 1130 return res; 1131 } 1132 1133 static void byte_array_put(typeArrayOop obj, intptr_t val, int index, int byte_count) { 1134 switch (byte_count) { 1135 case 1: 1136 obj->byte_at_put(index, (jbyte) *((jint *) &val)); 1137 break; 1138 case 2: 1139 *((jshort *) check_alignment_get_addr(obj, index, 2)) = (jshort) *((jint *) &val); 1140 break; 1141 case 4: 1142 *((jint *) check_alignment_get_addr(obj, index, 4)) = (jint) *((jint *) &val); 1143 break; 1144 case 8: 1145 *((jlong *) check_alignment_get_addr(obj, index, 8)) = (jlong) *((jlong *) &val); 1146 break; 1147 default: 1148 ShouldNotReachHere(); 1149 } 1150 } 1151 #endif // INCLUDE_JVMCI 1152 1153 1154 // restore elements of an eliminated type array 1155 void Deoptimization::reassign_type_array_elements(frame* fr, RegisterMap* reg_map, ObjectValue* sv, typeArrayOop obj, BasicType type) { 1156 int index = 0; 1157 intptr_t val; 1158 1159 for (int i = 0; i < sv->field_size(); i++) { 1160 StackValue* value = StackValue::create_stack_value(fr, reg_map, sv->field_at(i)); 1161 switch(type) { 1162 case T_LONG: case T_DOUBLE: { 1163 assert(value->type() == T_INT, "Agreement."); 1164 StackValue* low = 1165 StackValue::create_stack_value(fr, reg_map, sv->field_at(++i)); 1166 #ifdef _LP64 1167 jlong res = (jlong)low->get_int(); 1168 #else 1169 jlong res = jlong_from((jint)value->get_int(), (jint)low->get_int()); 1170 #endif 1171 obj->long_at_put(index, res); 1172 break; 1173 } 1174 1175 // Have to cast to INT (32 bits) pointer to avoid little/big-endian problem. 1176 case T_INT: case T_FLOAT: { // 4 bytes. 1177 assert(value->type() == T_INT, "Agreement."); 1178 bool big_value = false; 1179 if (i + 1 < sv->field_size() && type == T_INT) { 1180 if (sv->field_at(i)->is_location()) { 1181 Location::Type type = ((LocationValue*) sv->field_at(i))->location().type(); 1182 if (type == Location::dbl || type == Location::lng) { 1183 big_value = true; 1184 } 1185 } else if (sv->field_at(i)->is_constant_int()) { 1186 ScopeValue* next_scope_field = sv->field_at(i + 1); 1187 if (next_scope_field->is_constant_long() || next_scope_field->is_constant_double()) { 1188 big_value = true; 1189 } 1190 } 1191 } 1192 1193 if (big_value) { 1194 StackValue* low = StackValue::create_stack_value(fr, reg_map, sv->field_at(++i)); 1195 #ifdef _LP64 1196 jlong res = (jlong)low->get_int(); 1197 #else 1198 jlong res = jlong_from((jint)value->get_int(), (jint)low->get_int()); 1199 #endif 1200 obj->int_at_put(index, (jint)*((jint*)&res)); 1201 obj->int_at_put(++index, (jint)*(((jint*)&res) + 1)); 1202 } else { 1203 val = value->get_int(); 1204 obj->int_at_put(index, (jint)*((jint*)&val)); 1205 } 1206 break; 1207 } 1208 1209 case T_SHORT: 1210 assert(value->type() == T_INT, "Agreement."); 1211 val = value->get_int(); 1212 obj->short_at_put(index, (jshort)*((jint*)&val)); 1213 break; 1214 1215 case T_CHAR: 1216 assert(value->type() == T_INT, "Agreement."); 1217 val = value->get_int(); 1218 obj->char_at_put(index, (jchar)*((jint*)&val)); 1219 break; 1220 1221 case T_BYTE: { 1222 assert(value->type() == T_INT, "Agreement."); 1223 // The value we get is erased as a regular int. We will need to find its actual byte count 'by hand'. 1224 val = value->get_int(); 1225 #if INCLUDE_JVMCI 1226 int byte_count = count_number_of_bytes_for_entry(sv, i); 1227 byte_array_put(obj, val, index, byte_count); 1228 // According to byte_count contract, the values from i + 1 to i + byte_count are illegal values. Skip. 1229 i += byte_count - 1; // Balance the loop counter. 1230 index += byte_count; 1231 // index has been updated so continue at top of loop 1232 continue; 1233 #else 1234 obj->byte_at_put(index, (jbyte)*((jint*)&val)); 1235 break; 1236 #endif // INCLUDE_JVMCI 1237 } 1238 1239 case T_BOOLEAN: { 1240 assert(value->type() == T_INT, "Agreement."); 1241 val = value->get_int(); 1242 obj->bool_at_put(index, (jboolean)*((jint*)&val)); 1243 break; 1244 } 1245 1246 default: 1247 ShouldNotReachHere(); 1248 } 1249 index++; 1250 } 1251 } 1252 1253 // restore fields of an eliminated object array 1254 void Deoptimization::reassign_object_array_elements(frame* fr, RegisterMap* reg_map, ObjectValue* sv, objArrayOop obj) { 1255 for (int i = 0; i < sv->field_size(); i++) { 1256 StackValue* value = StackValue::create_stack_value(fr, reg_map, sv->field_at(i)); 1257 assert(value->type() == T_OBJECT, "object element expected"); 1258 obj->obj_at_put(i, value->get_obj()()); 1259 } 1260 } 1261 1262 class ReassignedField { 1263 public: 1264 int _offset; 1265 BasicType _type; 1266 public: 1267 ReassignedField() { 1268 _offset = 0; 1269 _type = T_ILLEGAL; 1270 } 1271 }; 1272 1273 int compare(ReassignedField* left, ReassignedField* right) { 1274 return left->_offset - right->_offset; 1275 } 1276 1277 // Restore fields of an eliminated instance object using the same field order 1278 // returned by HotSpotResolvedObjectTypeImpl.getInstanceFields(true) 1279 static int reassign_fields_by_klass(InstanceKlass* klass, frame* fr, RegisterMap* reg_map, ObjectValue* sv, int svIndex, oop obj, bool skip_internal) { 1280 GrowableArray<ReassignedField>* fields = new GrowableArray<ReassignedField>(); 1281 InstanceKlass* ik = klass; 1282 while (ik != NULL) { 1283 for (AllFieldStream fs(ik); !fs.done(); fs.next()) { 1284 if (!fs.access_flags().is_static() && (!skip_internal || !fs.access_flags().is_internal())) { 1285 ReassignedField field; 1286 field._offset = fs.offset(); 1287 field._type = Signature::basic_type(fs.signature()); 1288 fields->append(field); 1289 } 1290 } 1291 ik = ik->superklass(); 1292 } 1293 fields->sort(compare); 1294 for (int i = 0; i < fields->length(); i++) { 1295 intptr_t val; 1296 ScopeValue* scope_field = sv->field_at(svIndex); 1297 StackValue* value = StackValue::create_stack_value(fr, reg_map, scope_field); 1298 int offset = fields->at(i)._offset; 1299 BasicType type = fields->at(i)._type; 1300 switch (type) { 1301 case T_OBJECT: case T_ARRAY: 1302 assert(value->type() == T_OBJECT, "Agreement."); 1303 obj->obj_field_put(offset, value->get_obj()()); 1304 break; 1305 1306 // Have to cast to INT (32 bits) pointer to avoid little/big-endian problem. 1307 case T_INT: case T_FLOAT: { // 4 bytes. 1308 assert(value->type() == T_INT, "Agreement."); 1309 bool big_value = false; 1310 if (i+1 < fields->length() && fields->at(i+1)._type == T_INT) { 1311 if (scope_field->is_location()) { 1312 Location::Type type = ((LocationValue*) scope_field)->location().type(); 1313 if (type == Location::dbl || type == Location::lng) { 1314 big_value = true; 1315 } 1316 } 1317 if (scope_field->is_constant_int()) { 1318 ScopeValue* next_scope_field = sv->field_at(svIndex + 1); 1319 if (next_scope_field->is_constant_long() || next_scope_field->is_constant_double()) { 1320 big_value = true; 1321 } 1322 } 1323 } 1324 1325 if (big_value) { 1326 i++; 1327 assert(i < fields->length(), "second T_INT field needed"); 1328 assert(fields->at(i)._type == T_INT, "T_INT field needed"); 1329 } else { 1330 val = value->get_int(); 1331 obj->int_field_put(offset, (jint)*((jint*)&val)); 1332 break; 1333 } 1334 } 1335 /* no break */ 1336 1337 case T_LONG: case T_DOUBLE: { 1338 assert(value->type() == T_INT, "Agreement."); 1339 StackValue* low = StackValue::create_stack_value(fr, reg_map, sv->field_at(++svIndex)); 1340 #ifdef _LP64 1341 jlong res = (jlong)low->get_int(); 1342 #else 1343 jlong res = jlong_from((jint)value->get_int(), (jint)low->get_int()); 1344 #endif 1345 obj->long_field_put(offset, res); 1346 break; 1347 } 1348 1349 case T_SHORT: 1350 assert(value->type() == T_INT, "Agreement."); 1351 val = value->get_int(); 1352 obj->short_field_put(offset, (jshort)*((jint*)&val)); 1353 break; 1354 1355 case T_CHAR: 1356 assert(value->type() == T_INT, "Agreement."); 1357 val = value->get_int(); 1358 obj->char_field_put(offset, (jchar)*((jint*)&val)); 1359 break; 1360 1361 case T_BYTE: 1362 assert(value->type() == T_INT, "Agreement."); 1363 val = value->get_int(); 1364 obj->byte_field_put(offset, (jbyte)*((jint*)&val)); 1365 break; 1366 1367 case T_BOOLEAN: 1368 assert(value->type() == T_INT, "Agreement."); 1369 val = value->get_int(); 1370 obj->bool_field_put(offset, (jboolean)*((jint*)&val)); 1371 break; 1372 1373 default: 1374 ShouldNotReachHere(); 1375 } 1376 svIndex++; 1377 } 1378 return svIndex; 1379 } 1380 1381 // restore fields of all eliminated objects and arrays 1382 void Deoptimization::reassign_fields(frame* fr, RegisterMap* reg_map, GrowableArray<ScopeValue*>* objects, bool realloc_failures, bool skip_internal) { 1383 for (int i = 0; i < objects->length(); i++) { 1384 ObjectValue* sv = (ObjectValue*) objects->at(i); 1385 Klass* k = java_lang_Class::as_Klass(sv->klass()->as_ConstantOopReadValue()->value()()); 1386 Handle obj = sv->value(); 1387 assert(obj.not_null() || realloc_failures, "reallocation was missed"); 1388 if (PrintDeoptimizationDetails) { 1389 tty->print_cr("reassign fields for object of type %s!", k->name()->as_C_string()); 1390 } 1391 if (obj.is_null()) { 1392 continue; 1393 } 1394 #if INCLUDE_JVMCI || INCLUDE_AOT 1395 // Don't reassign fields of boxes that came from a cache. Caches may be in CDS. 1396 if (sv->is_auto_box() && ((AutoBoxObjectValue*) sv)->is_cached()) { 1397 continue; 1398 } 1399 #endif // INCLUDE_JVMCI || INCLUDE_AOT 1400 if (k->is_instance_klass()) { 1401 InstanceKlass* ik = InstanceKlass::cast(k); 1402 reassign_fields_by_klass(ik, fr, reg_map, sv, 0, obj(), skip_internal); 1403 } else if (k->is_typeArray_klass()) { 1404 TypeArrayKlass* ak = TypeArrayKlass::cast(k); 1405 reassign_type_array_elements(fr, reg_map, sv, (typeArrayOop) obj(), ak->element_type()); 1406 } else if (k->is_objArray_klass()) { 1407 reassign_object_array_elements(fr, reg_map, sv, (objArrayOop) obj()); 1408 } 1409 } 1410 } 1411 1412 1413 // relock objects for which synchronization was eliminated 1414 bool Deoptimization::relock_objects(JavaThread* thread, GrowableArray<MonitorInfo*>* monitors, 1415 JavaThread* deoptee_thread, frame& fr, int exec_mode, bool realloc_failures) { 1416 bool relocked_objects = false; 1417 for (int i = 0; i < monitors->length(); i++) { 1418 MonitorInfo* mon_info = monitors->at(i); 1419 if (mon_info->eliminated()) { 1420 assert(!mon_info->owner_is_scalar_replaced() || realloc_failures, "reallocation was missed"); 1421 relocked_objects = true; 1422 if (!mon_info->owner_is_scalar_replaced()) { 1423 Handle obj(thread, mon_info->owner()); 1424 markWord mark = obj->mark(); 1425 if (UseBiasedLocking && mark.has_bias_pattern()) { 1426 // New allocated objects may have the mark set to anonymously biased. 1427 // Also the deoptimized method may called methods with synchronization 1428 // where the thread-local object is bias locked to the current thread. 1429 assert(mark.is_biased_anonymously() || 1430 mark.biased_locker() == deoptee_thread, "should be locked to current thread"); 1431 // Reset mark word to unbiased prototype. 1432 markWord unbiased_prototype = markWord::prototype().set_age(mark.age()); 1433 obj->set_mark(unbiased_prototype); 1434 } else if (exec_mode == Unpack_none) { 1435 if (mark.has_locker() && fr.sp() > (intptr_t*)mark.locker()) { 1436 // With exec_mode == Unpack_none obj may be thread local and locked in 1437 // a callee frame. In this case the bias was revoked before in revoke_for_object_deoptimization(). 1438 // Make the lock in the callee a recursive lock and restore the displaced header. 1439 markWord dmw = mark.displaced_mark_helper(); 1440 mark.locker()->set_displaced_header(markWord::encode((BasicLock*) NULL)); 1441 obj->set_mark(dmw); 1442 } 1443 if (mark.has_monitor()) { 1444 // defer relocking if the deoptee thread is currently waiting for obj 1445 ObjectMonitor* waiting_monitor = deoptee_thread->current_waiting_monitor(); 1446 if (waiting_monitor != NULL && (oop)waiting_monitor->object() == obj()) { 1447 assert(fr.is_deoptimized_frame(), "frame must be scheduled for deoptimization"); 1448 mon_info->lock()->set_displaced_header(markWord::unused_mark()); 1449 JvmtiDeferredUpdates::inc_relock_count_after_wait(deoptee_thread); 1450 continue; 1451 } 1452 } 1453 } 1454 BasicLock* lock = mon_info->lock(); 1455 ObjectSynchronizer::enter(obj, lock, deoptee_thread); 1456 assert(mon_info->owner()->is_locked(), "object must be locked now"); 1457 } 1458 } 1459 } 1460 return relocked_objects; 1461 } 1462 1463 1464 #ifndef PRODUCT 1465 // print information about reallocated objects 1466 void Deoptimization::print_objects(GrowableArray<ScopeValue*>* objects, bool realloc_failures) { 1467 fieldDescriptor fd; 1468 1469 for (int i = 0; i < objects->length(); i++) { 1470 ObjectValue* sv = (ObjectValue*) objects->at(i); 1471 Klass* k = java_lang_Class::as_Klass(sv->klass()->as_ConstantOopReadValue()->value()()); 1472 Handle obj = sv->value(); 1473 1474 tty->print(" object <" INTPTR_FORMAT "> of type ", p2i(sv->value()())); 1475 k->print_value(); 1476 assert(obj.not_null() || realloc_failures, "reallocation was missed"); 1477 if (obj.is_null()) { 1478 tty->print(" allocation failed"); 1479 } else { 1480 tty->print(" allocated (%d bytes)", obj->size() * HeapWordSize); 1481 } 1482 tty->cr(); 1483 1484 if (Verbose && !obj.is_null()) { 1485 k->oop_print_on(obj(), tty); 1486 } 1487 } 1488 } 1489 #endif 1490 #endif // COMPILER2_OR_JVMCI 1491 1492 vframeArray* Deoptimization::create_vframeArray(JavaThread* thread, frame fr, RegisterMap *reg_map, GrowableArray<compiledVFrame*>* chunk, bool realloc_failures) { 1493 Events::log_deopt_message(thread, "DEOPT PACKING pc=" INTPTR_FORMAT " sp=" INTPTR_FORMAT, p2i(fr.pc()), p2i(fr.sp())); 1494 1495 #ifndef PRODUCT 1496 if (PrintDeoptimizationDetails) { 1497 ttyLocker ttyl; 1498 tty->print("DEOPT PACKING thread " INTPTR_FORMAT " ", p2i(thread)); 1499 fr.print_on(tty); 1500 tty->print_cr(" Virtual frames (innermost first):"); 1501 for (int index = 0; index < chunk->length(); index++) { 1502 compiledVFrame* vf = chunk->at(index); 1503 tty->print(" %2d - ", index); 1504 vf->print_value(); 1505 int bci = chunk->at(index)->raw_bci(); 1506 const char* code_name; 1507 if (bci == SynchronizationEntryBCI) { 1508 code_name = "sync entry"; 1509 } else { 1510 Bytecodes::Code code = vf->method()->code_at(bci); 1511 code_name = Bytecodes::name(code); 1512 } 1513 tty->print(" - %s", code_name); 1514 tty->print_cr(" @ bci %d ", bci); 1515 if (Verbose) { 1516 vf->print(); 1517 tty->cr(); 1518 } 1519 } 1520 } 1521 #endif 1522 1523 // Register map for next frame (used for stack crawl). We capture 1524 // the state of the deopt'ing frame's caller. Thus if we need to 1525 // stuff a C2I adapter we can properly fill in the callee-save 1526 // register locations. 1527 frame caller = fr.sender(reg_map); 1528 int frame_size = caller.sp() - fr.sp(); 1529 1530 frame sender = caller; 1531 1532 // Since the Java thread being deoptimized will eventually adjust it's own stack, 1533 // the vframeArray containing the unpacking information is allocated in the C heap. 1534 // For Compiler1, the caller of the deoptimized frame is saved for use by unpack_frames(). 1535 vframeArray* array = vframeArray::allocate(thread, frame_size, chunk, reg_map, sender, caller, fr, realloc_failures); 1536 1537 // Compare the vframeArray to the collected vframes 1538 assert(array->structural_compare(thread, chunk), "just checking"); 1539 1540 #ifndef PRODUCT 1541 if (PrintDeoptimizationDetails) { 1542 ttyLocker ttyl; 1543 tty->print_cr(" Created vframeArray " INTPTR_FORMAT, p2i(array)); 1544 } 1545 #endif // PRODUCT 1546 1547 return array; 1548 } 1549 1550 #if COMPILER2_OR_JVMCI 1551 void Deoptimization::pop_frames_failed_reallocs(JavaThread* thread, vframeArray* array) { 1552 // Reallocation of some scalar replaced objects failed. Record 1553 // that we need to pop all the interpreter frames for the 1554 // deoptimized compiled frame. 1555 assert(thread->frames_to_pop_failed_realloc() == 0, "missed frames to pop?"); 1556 thread->set_frames_to_pop_failed_realloc(array->frames()); 1557 // Unlock all monitors here otherwise the interpreter will see a 1558 // mix of locked and unlocked monitors (because of failed 1559 // reallocations of synchronized objects) and be confused. 1560 for (int i = 0; i < array->frames(); i++) { 1561 MonitorChunk* monitors = array->element(i)->monitors(); 1562 if (monitors != NULL) { 1563 for (int j = 0; j < monitors->number_of_monitors(); j++) { 1564 BasicObjectLock* src = monitors->at(j); 1565 if (src->obj() != NULL) { 1566 ObjectSynchronizer::exit(src->obj(), src->lock(), thread); 1567 } 1568 } 1569 array->element(i)->free_monitors(thread); 1570 #ifdef ASSERT 1571 array->element(i)->set_removed_monitors(); 1572 #endif 1573 } 1574 } 1575 } 1576 #endif 1577 1578 static void collect_monitors(compiledVFrame* cvf, GrowableArray<Handle>* objects_to_revoke, bool only_eliminated) { 1579 GrowableArray<MonitorInfo*>* monitors = cvf->monitors(); 1580 Thread* thread = Thread::current(); 1581 for (int i = 0; i < monitors->length(); i++) { 1582 MonitorInfo* mon_info = monitors->at(i); 1583 if ((mon_info->eliminated() == only_eliminated) && !mon_info->owner_is_scalar_replaced() && mon_info->owner() != NULL) { 1584 objects_to_revoke->append(Handle(thread, mon_info->owner())); 1585 } 1586 } 1587 } 1588 1589 static void get_monitors_from_stack(GrowableArray<Handle>* objects_to_revoke, JavaThread* thread, frame fr, RegisterMap* map, 1590 bool only_eliminated) { 1591 // Unfortunately we don't have a RegisterMap available in most of 1592 // the places we want to call this routine so we need to walk the 1593 // stack again to update the register map. 1594 if (map == NULL || !map->update_map()) { 1595 StackFrameStream sfs(thread, true); 1596 bool found = false; 1597 while (!found && !sfs.is_done()) { 1598 frame* cur = sfs.current(); 1599 sfs.next(); 1600 found = cur->id() == fr.id(); 1601 } 1602 assert(found, "frame to be deoptimized not found on target thread's stack"); 1603 map = sfs.register_map(); 1604 } 1605 1606 vframe* vf = vframe::new_vframe(&fr, map, thread); 1607 compiledVFrame* cvf = compiledVFrame::cast(vf); 1608 // Revoke monitors' biases in all scopes 1609 while (!cvf->is_top()) { 1610 collect_monitors(cvf, objects_to_revoke, only_eliminated); 1611 cvf = compiledVFrame::cast(cvf->sender()); 1612 } 1613 collect_monitors(cvf, objects_to_revoke, only_eliminated); 1614 } 1615 1616 void Deoptimization::revoke_from_deopt_handler(JavaThread* thread, frame fr, RegisterMap* map) { 1617 if (!UseBiasedLocking) { 1618 return; 1619 } 1620 GrowableArray<Handle>* objects_to_revoke = new GrowableArray<Handle>(); 1621 get_monitors_from_stack(objects_to_revoke, thread, fr, map, false); 1622 1623 int len = objects_to_revoke->length(); 1624 for (int i = 0; i < len; i++) { 1625 oop obj = (objects_to_revoke->at(i))(); 1626 BiasedLocking::revoke_own_lock(objects_to_revoke->at(i), thread); 1627 assert(!obj->mark().has_bias_pattern(), "biases should be revoked by now"); 1628 } 1629 } 1630 1631 // Revoke the bias of objects with eliminated locking to prepare subsequent relocking. 1632 void Deoptimization::revoke_for_object_deoptimization(JavaThread* deoptee_thread, frame fr, RegisterMap* map, JavaThread* thread) { 1633 if (!UseBiasedLocking) { 1634 return; 1635 } 1636 GrowableArray<Handle>* objects_to_revoke = new GrowableArray<Handle>(); 1637 // Collect monitors, but only those with eliminated locking. 1638 get_monitors_from_stack(objects_to_revoke, deoptee_thread, fr, map, true); 1639 1640 int len = objects_to_revoke->length(); 1641 for (int i = 0; i < len; i++) { 1642 oop obj = (objects_to_revoke->at(i))(); 1643 markWord mark = obj->mark(); 1644 if (!mark.has_bias_pattern() || 1645 mark.is_biased_anonymously() || // eliminated locking does not bias an object if it wasn't before 1646 !obj->klass()->prototype_header().has_bias_pattern() || // bulk revoke ignores eliminated monitors 1647 (obj->klass()->prototype_header().bias_epoch() != mark.bias_epoch())) { // bulk rebias ignores eliminated monitors 1648 // We reach here regularly if there's just eliminated locking on obj. 1649 // We must not call BiasedLocking::revoke_own_lock() in this case, as we would hit assertions, because it is a 1650 // prerequisite that there has to be non-eliminated locking on obj by deoptee_thread. 1651 // Luckily we don't have to revoke here, because obj has to be a non-escaping obj and can be relocked without 1652 // revoking the bias. See Deoptimization::relock_objects(). 1653 continue; 1654 } 1655 BiasedLocking::revoke(objects_to_revoke->at(i), thread); 1656 assert(!objects_to_revoke->at(i)->mark().has_bias_pattern(), "biases should be revoked by now"); 1657 } 1658 } 1659 1660 void Deoptimization::deoptimize_single_frame(JavaThread* thread, frame fr, Deoptimization::DeoptReason reason) { 1661 assert(fr.can_be_deoptimized(), "checking frame type"); 1662 1663 gather_statistics(reason, Action_none, Bytecodes::_illegal); 1664 1665 if (LogCompilation && xtty != NULL) { 1666 CompiledMethod* cm = fr.cb()->as_compiled_method_or_null(); 1667 assert(cm != NULL, "only compiled methods can deopt"); 1668 1669 ttyLocker ttyl; 1670 xtty->begin_head("deoptimized thread='" UINTX_FORMAT "' reason='%s' pc='" INTPTR_FORMAT "'",(uintx)thread->osthread()->thread_id(), trap_reason_name(reason), p2i(fr.pc())); 1671 cm->log_identity(xtty); 1672 xtty->end_head(); 1673 for (ScopeDesc* sd = cm->scope_desc_at(fr.pc()); ; sd = sd->sender()) { 1674 xtty->begin_elem("jvms bci='%d'", sd->bci()); 1675 xtty->method(sd->method()); 1676 xtty->end_elem(); 1677 if (sd->is_top()) break; 1678 } 1679 xtty->tail("deoptimized"); 1680 } 1681 1682 // Patch the compiled method so that when execution returns to it we will 1683 // deopt the execution state and return to the interpreter. 1684 fr.deoptimize(thread); 1685 } 1686 1687 void Deoptimization::deoptimize(JavaThread* thread, frame fr, DeoptReason reason) { 1688 // Deoptimize only if the frame comes from compile code. 1689 // Do not deoptimize the frame which is already patched 1690 // during the execution of the loops below. 1691 if (!fr.is_compiled_frame() || fr.is_deoptimized_frame()) { 1692 return; 1693 } 1694 ResourceMark rm; 1695 DeoptimizationMarker dm; 1696 deoptimize_single_frame(thread, fr, reason); 1697 } 1698 1699 #if INCLUDE_JVMCI 1700 address Deoptimization::deoptimize_for_missing_exception_handler(CompiledMethod* cm) { 1701 // there is no exception handler for this pc => deoptimize 1702 cm->make_not_entrant(); 1703 1704 // Use Deoptimization::deoptimize for all of its side-effects: 1705 // gathering traps statistics, logging... 1706 // it also patches the return pc but we do not care about that 1707 // since we return a continuation to the deopt_blob below. 1708 JavaThread* thread = JavaThread::current(); 1709 RegisterMap reg_map(thread, false); 1710 frame runtime_frame = thread->last_frame(); 1711 frame caller_frame = runtime_frame.sender(®_map); 1712 assert(caller_frame.cb()->as_compiled_method_or_null() == cm, "expect top frame compiled method"); 1713 Deoptimization::deoptimize(thread, caller_frame, Deoptimization::Reason_not_compiled_exception_handler); 1714 1715 MethodData* trap_mdo = get_method_data(thread, methodHandle(thread, cm->method()), true); 1716 if (trap_mdo != NULL) { 1717 trap_mdo->inc_trap_count(Deoptimization::Reason_not_compiled_exception_handler); 1718 } 1719 1720 return SharedRuntime::deopt_blob()->unpack_with_exception_in_tls(); 1721 } 1722 #endif 1723 1724 void Deoptimization::deoptimize_frame_internal(JavaThread* thread, intptr_t* id, DeoptReason reason) { 1725 assert(thread == Thread::current() || SafepointSynchronize::is_at_safepoint(), 1726 "can only deoptimize other thread at a safepoint"); 1727 // Compute frame and register map based on thread and sp. 1728 RegisterMap reg_map(thread, false); 1729 frame fr = thread->last_frame(); 1730 while (fr.id() != id) { 1731 fr = fr.sender(®_map); 1732 } 1733 deoptimize(thread, fr, reason); 1734 } 1735 1736 1737 void Deoptimization::deoptimize_frame(JavaThread* thread, intptr_t* id, DeoptReason reason) { 1738 if (thread == Thread::current()) { 1739 Deoptimization::deoptimize_frame_internal(thread, id, reason); 1740 } else { 1741 VM_DeoptimizeFrame deopt(thread, id, reason); 1742 VMThread::execute(&deopt); 1743 } 1744 } 1745 1746 void Deoptimization::deoptimize_frame(JavaThread* thread, intptr_t* id) { 1747 deoptimize_frame(thread, id, Reason_constraint); 1748 } 1749 1750 // JVMTI PopFrame support 1751 JRT_LEAF(void, Deoptimization::popframe_preserve_args(JavaThread* thread, int bytes_to_save, void* start_address)) 1752 { 1753 thread->popframe_preserve_args(in_ByteSize(bytes_to_save), start_address); 1754 } 1755 JRT_END 1756 1757 MethodData* 1758 Deoptimization::get_method_data(JavaThread* thread, const methodHandle& m, 1759 bool create_if_missing) { 1760 Thread* THREAD = thread; 1761 MethodData* mdo = m()->method_data(); 1762 if (mdo == NULL && create_if_missing && !HAS_PENDING_EXCEPTION) { 1763 // Build an MDO. Ignore errors like OutOfMemory; 1764 // that simply means we won't have an MDO to update. 1765 Method::build_interpreter_method_data(m, THREAD); 1766 if (HAS_PENDING_EXCEPTION) { 1767 assert((PENDING_EXCEPTION->is_a(SystemDictionary::OutOfMemoryError_klass())), "we expect only an OOM error here"); 1768 CLEAR_PENDING_EXCEPTION; 1769 } 1770 mdo = m()->method_data(); 1771 } 1772 return mdo; 1773 } 1774 1775 #if COMPILER2_OR_JVMCI 1776 void Deoptimization::load_class_by_index(const constantPoolHandle& constant_pool, int index, TRAPS) { 1777 // In case of an unresolved klass entry, load the class. 1778 // This path is exercised from case _ldc in Parse::do_one_bytecode, 1779 // and probably nowhere else. 1780 // Even that case would benefit from simply re-interpreting the 1781 // bytecode, without paying special attention to the class index. 1782 // So this whole "class index" feature should probably be removed. 1783 1784 if (constant_pool->tag_at(index).is_unresolved_klass()) { 1785 Klass* tk = constant_pool->klass_at_ignore_error(index, CHECK); 1786 return; 1787 } 1788 1789 assert(!constant_pool->tag_at(index).is_symbol(), 1790 "no symbolic names here, please"); 1791 } 1792 1793 1794 void Deoptimization::load_class_by_index(const constantPoolHandle& constant_pool, int index) { 1795 EXCEPTION_MARK; 1796 load_class_by_index(constant_pool, index, THREAD); 1797 if (HAS_PENDING_EXCEPTION) { 1798 // Exception happened during classloading. We ignore the exception here, since it 1799 // is going to be rethrown since the current activation is going to be deoptimized and 1800 // the interpreter will re-execute the bytecode. 1801 CLEAR_PENDING_EXCEPTION; 1802 // Class loading called java code which may have caused a stack 1803 // overflow. If the exception was thrown right before the return 1804 // to the runtime the stack is no longer guarded. Reguard the 1805 // stack otherwise if we return to the uncommon trap blob and the 1806 // stack bang causes a stack overflow we crash. 1807 assert(THREAD->is_Java_thread(), "only a java thread can be here"); 1808 JavaThread* thread = (JavaThread*)THREAD; 1809 bool guard_pages_enabled = thread->stack_guards_enabled(); 1810 if (!guard_pages_enabled) guard_pages_enabled = thread->reguard_stack(); 1811 assert(guard_pages_enabled, "stack banging in uncommon trap blob may cause crash"); 1812 } 1813 } 1814 1815 #if INCLUDE_JFR 1816 1817 class DeoptReasonSerializer : public JfrSerializer { 1818 public: 1819 void serialize(JfrCheckpointWriter& writer) { 1820 writer.write_count((u4)(Deoptimization::Reason_LIMIT + 1)); // + Reason::many (-1) 1821 for (int i = -1; i < Deoptimization::Reason_LIMIT; ++i) { 1822 writer.write_key((u8)i); 1823 writer.write(Deoptimization::trap_reason_name(i)); 1824 } 1825 } 1826 }; 1827 1828 class DeoptActionSerializer : public JfrSerializer { 1829 public: 1830 void serialize(JfrCheckpointWriter& writer) { 1831 static const u4 nof_actions = Deoptimization::Action_LIMIT; 1832 writer.write_count(nof_actions); 1833 for (u4 i = 0; i < Deoptimization::Action_LIMIT; ++i) { 1834 writer.write_key(i); 1835 writer.write(Deoptimization::trap_action_name((int)i)); 1836 } 1837 } 1838 }; 1839 1840 static void register_serializers() { 1841 static int critical_section = 0; 1842 if (1 == critical_section || Atomic::cmpxchg(&critical_section, 0, 1) == 1) { 1843 return; 1844 } 1845 JfrSerializer::register_serializer(TYPE_DEOPTIMIZATIONREASON, true, new DeoptReasonSerializer()); 1846 JfrSerializer::register_serializer(TYPE_DEOPTIMIZATIONACTION, true, new DeoptActionSerializer()); 1847 } 1848 1849 static void post_deoptimization_event(CompiledMethod* nm, 1850 const Method* method, 1851 int trap_bci, 1852 int instruction, 1853 Deoptimization::DeoptReason reason, 1854 Deoptimization::DeoptAction action) { 1855 assert(nm != NULL, "invariant"); 1856 assert(method != NULL, "invariant"); 1857 if (EventDeoptimization::is_enabled()) { 1858 static bool serializers_registered = false; 1859 if (!serializers_registered) { 1860 register_serializers(); 1861 serializers_registered = true; 1862 } 1863 EventDeoptimization event; 1864 event.set_compileId(nm->compile_id()); 1865 event.set_compiler(nm->compiler_type()); 1866 event.set_method(method); 1867 event.set_lineNumber(method->line_number_from_bci(trap_bci)); 1868 event.set_bci(trap_bci); 1869 event.set_instruction(instruction); 1870 event.set_reason(reason); 1871 event.set_action(action); 1872 event.commit(); 1873 } 1874 } 1875 1876 #endif // INCLUDE_JFR 1877 1878 JRT_ENTRY(void, Deoptimization::uncommon_trap_inner(JavaThread* thread, jint trap_request)) { 1879 HandleMark hm; 1880 1881 // uncommon_trap() is called at the beginning of the uncommon trap 1882 // handler. Note this fact before we start generating temporary frames 1883 // that can confuse an asynchronous stack walker. This counter is 1884 // decremented at the end of unpack_frames(). 1885 thread->inc_in_deopt_handler(); 1886 1887 // We need to update the map if we have biased locking. 1888 #if INCLUDE_JVMCI 1889 // JVMCI might need to get an exception from the stack, which in turn requires the register map to be valid 1890 RegisterMap reg_map(thread, true); 1891 #else 1892 RegisterMap reg_map(thread, UseBiasedLocking); 1893 #endif 1894 frame stub_frame = thread->last_frame(); 1895 frame fr = stub_frame.sender(®_map); 1896 // Make sure the calling nmethod is not getting deoptimized and removed 1897 // before we are done with it. 1898 nmethodLocker nl(fr.pc()); 1899 1900 // Log a message 1901 Events::log_deopt_message(thread, "Uncommon trap: trap_request=" PTR32_FORMAT " fr.pc=" INTPTR_FORMAT " relative=" INTPTR_FORMAT, 1902 trap_request, p2i(fr.pc()), fr.pc() - fr.cb()->code_begin()); 1903 1904 { 1905 ResourceMark rm; 1906 1907 DeoptReason reason = trap_request_reason(trap_request); 1908 DeoptAction action = trap_request_action(trap_request); 1909 #if INCLUDE_JVMCI 1910 int debug_id = trap_request_debug_id(trap_request); 1911 #endif 1912 jint unloaded_class_index = trap_request_index(trap_request); // CP idx or -1 1913 1914 vframe* vf = vframe::new_vframe(&fr, ®_map, thread); 1915 compiledVFrame* cvf = compiledVFrame::cast(vf); 1916 1917 CompiledMethod* nm = cvf->code(); 1918 1919 ScopeDesc* trap_scope = cvf->scope(); 1920 1921 if (TraceDeoptimization) { 1922 ttyLocker ttyl; 1923 tty->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() 1924 #if INCLUDE_JVMCI 1925 , debug_id 1926 #endif 1927 ); 1928 } 1929 1930 methodHandle trap_method(THREAD, trap_scope->method()); 1931 int trap_bci = trap_scope->bci(); 1932 #if INCLUDE_JVMCI 1933 jlong speculation = thread->pending_failed_speculation(); 1934 if (nm->is_compiled_by_jvmci() && nm->is_nmethod()) { // Exclude AOTed methods 1935 nm->as_nmethod()->update_speculation(thread); 1936 } else { 1937 assert(speculation == 0, "There should not be a speculation for methods compiled by non-JVMCI compilers"); 1938 } 1939 1940 if (trap_bci == SynchronizationEntryBCI) { 1941 trap_bci = 0; 1942 thread->set_pending_monitorenter(true); 1943 } 1944 1945 if (reason == Deoptimization::Reason_transfer_to_interpreter) { 1946 thread->set_pending_transfer_to_interpreter(true); 1947 } 1948 #endif 1949 1950 Bytecodes::Code trap_bc = trap_method->java_code_at(trap_bci); 1951 // Record this event in the histogram. 1952 gather_statistics(reason, action, trap_bc); 1953 1954 // Ensure that we can record deopt. history: 1955 // Need MDO to record RTM code generation state. 1956 bool create_if_missing = ProfileTraps || UseCodeAging RTM_OPT_ONLY( || UseRTMLocking ); 1957 1958 methodHandle profiled_method; 1959 #if INCLUDE_JVMCI 1960 if (nm->is_compiled_by_jvmci()) { 1961 profiled_method = methodHandle(THREAD, nm->method()); 1962 } else { 1963 profiled_method = trap_method; 1964 } 1965 #else 1966 profiled_method = trap_method; 1967 #endif 1968 1969 MethodData* trap_mdo = 1970 get_method_data(thread, profiled_method, create_if_missing); 1971 1972 JFR_ONLY(post_deoptimization_event(nm, trap_method(), trap_bci, trap_bc, reason, action);) 1973 1974 // Log a message 1975 Events::log_deopt_message(thread, "Uncommon trap: reason=%s action=%s pc=" INTPTR_FORMAT " method=%s @ %d %s", 1976 trap_reason_name(reason), trap_action_name(action), p2i(fr.pc()), 1977 trap_method->name_and_sig_as_C_string(), trap_bci, nm->compiler_name()); 1978 1979 // Print a bunch of diagnostics, if requested. 1980 if (TraceDeoptimization || LogCompilation) { 1981 ResourceMark rm; 1982 ttyLocker ttyl; 1983 char buf[100]; 1984 if (xtty != NULL) { 1985 xtty->begin_head("uncommon_trap thread='" UINTX_FORMAT "' %s", 1986 os::current_thread_id(), 1987 format_trap_request(buf, sizeof(buf), trap_request)); 1988 #if INCLUDE_JVMCI 1989 if (speculation != 0) { 1990 xtty->print(" speculation='" JLONG_FORMAT "'", speculation); 1991 } 1992 #endif 1993 nm->log_identity(xtty); 1994 } 1995 Symbol* class_name = NULL; 1996 bool unresolved = false; 1997 if (unloaded_class_index >= 0) { 1998 constantPoolHandle constants (THREAD, trap_method->constants()); 1999 if (constants->tag_at(unloaded_class_index).is_unresolved_klass()) { 2000 class_name = constants->klass_name_at(unloaded_class_index); 2001 unresolved = true; 2002 if (xtty != NULL) 2003 xtty->print(" unresolved='1'"); 2004 } else if (constants->tag_at(unloaded_class_index).is_symbol()) { 2005 class_name = constants->symbol_at(unloaded_class_index); 2006 } 2007 if (xtty != NULL) 2008 xtty->name(class_name); 2009 } 2010 if (xtty != NULL && trap_mdo != NULL && (int)reason < (int)MethodData::_trap_hist_limit) { 2011 // Dump the relevant MDO state. 2012 // This is the deopt count for the current reason, any previous 2013 // reasons or recompiles seen at this point. 2014 int dcnt = trap_mdo->trap_count(reason); 2015 if (dcnt != 0) 2016 xtty->print(" count='%d'", dcnt); 2017 ProfileData* pdata = trap_mdo->bci_to_data(trap_bci); 2018 int dos = (pdata == NULL)? 0: pdata->trap_state(); 2019 if (dos != 0) { 2020 xtty->print(" state='%s'", format_trap_state(buf, sizeof(buf), dos)); 2021 if (trap_state_is_recompiled(dos)) { 2022 int recnt2 = trap_mdo->overflow_recompile_count(); 2023 if (recnt2 != 0) 2024 xtty->print(" recompiles2='%d'", recnt2); 2025 } 2026 } 2027 } 2028 if (xtty != NULL) { 2029 xtty->stamp(); 2030 xtty->end_head(); 2031 } 2032 if (TraceDeoptimization) { // make noise on the tty 2033 tty->print("Uncommon trap occurred in"); 2034 nm->method()->print_short_name(tty); 2035 tty->print(" compiler=%s compile_id=%d", nm->compiler_name(), nm->compile_id()); 2036 #if INCLUDE_JVMCI 2037 if (nm->is_nmethod()) { 2038 const char* installed_code_name = nm->as_nmethod()->jvmci_name(); 2039 if (installed_code_name != NULL) { 2040 tty->print(" (JVMCI: installed code name=%s) ", installed_code_name); 2041 } 2042 } 2043 #endif 2044 tty->print(" (@" INTPTR_FORMAT ") thread=" UINTX_FORMAT " reason=%s action=%s unloaded_class_index=%d" JVMCI_ONLY(" debug_id=%d"), 2045 p2i(fr.pc()), 2046 os::current_thread_id(), 2047 trap_reason_name(reason), 2048 trap_action_name(action), 2049 unloaded_class_index 2050 #if INCLUDE_JVMCI 2051 , debug_id 2052 #endif 2053 ); 2054 if (class_name != NULL) { 2055 tty->print(unresolved ? " unresolved class: " : " symbol: "); 2056 class_name->print_symbol_on(tty); 2057 } 2058 tty->cr(); 2059 } 2060 if (xtty != NULL) { 2061 // Log the precise location of the trap. 2062 for (ScopeDesc* sd = trap_scope; ; sd = sd->sender()) { 2063 xtty->begin_elem("jvms bci='%d'", sd->bci()); 2064 xtty->method(sd->method()); 2065 xtty->end_elem(); 2066 if (sd->is_top()) break; 2067 } 2068 xtty->tail("uncommon_trap"); 2069 } 2070 } 2071 // (End diagnostic printout.) 2072 2073 // Load class if necessary 2074 if (unloaded_class_index >= 0) { 2075 constantPoolHandle constants(THREAD, trap_method->constants()); 2076 load_class_by_index(constants, unloaded_class_index); 2077 } 2078 2079 // Flush the nmethod if necessary and desirable. 2080 // 2081 // We need to avoid situations where we are re-flushing the nmethod 2082 // because of a hot deoptimization site. Repeated flushes at the same 2083 // point need to be detected by the compiler and avoided. If the compiler 2084 // cannot avoid them (or has a bug and "refuses" to avoid them), this 2085 // module must take measures to avoid an infinite cycle of recompilation 2086 // and deoptimization. There are several such measures: 2087 // 2088 // 1. If a recompilation is ordered a second time at some site X 2089 // and for the same reason R, the action is adjusted to 'reinterpret', 2090 // to give the interpreter time to exercise the method more thoroughly. 2091 // If this happens, the method's overflow_recompile_count is incremented. 2092 // 2093 // 2. If the compiler fails to reduce the deoptimization rate, then 2094 // the method's overflow_recompile_count will begin to exceed the set 2095 // limit PerBytecodeRecompilationCutoff. If this happens, the action 2096 // is adjusted to 'make_not_compilable', and the method is abandoned 2097 // to the interpreter. This is a performance hit for hot methods, 2098 // but is better than a disastrous infinite cycle of recompilations. 2099 // (Actually, only the method containing the site X is abandoned.) 2100 // 2101 // 3. In parallel with the previous measures, if the total number of 2102 // recompilations of a method exceeds the much larger set limit 2103 // PerMethodRecompilationCutoff, the method is abandoned. 2104 // This should only happen if the method is very large and has 2105 // many "lukewarm" deoptimizations. The code which enforces this 2106 // limit is elsewhere (class nmethod, class Method). 2107 // 2108 // Note that the per-BCI 'is_recompiled' bit gives the compiler one chance 2109 // to recompile at each bytecode independently of the per-BCI cutoff. 2110 // 2111 // The decision to update code is up to the compiler, and is encoded 2112 // in the Action_xxx code. If the compiler requests Action_none 2113 // no trap state is changed, no compiled code is changed, and the 2114 // computation suffers along in the interpreter. 2115 // 2116 // The other action codes specify various tactics for decompilation 2117 // and recompilation. Action_maybe_recompile is the loosest, and 2118 // allows the compiled code to stay around until enough traps are seen, 2119 // and until the compiler gets around to recompiling the trapping method. 2120 // 2121 // The other actions cause immediate removal of the present code. 2122 2123 // Traps caused by injected profile shouldn't pollute trap counts. 2124 bool injected_profile_trap = trap_method->has_injected_profile() && 2125 (reason == Reason_intrinsic || reason == Reason_unreached); 2126 2127 bool update_trap_state = (reason != Reason_tenured) && !injected_profile_trap; 2128 bool make_not_entrant = false; 2129 bool make_not_compilable = false; 2130 bool reprofile = false; 2131 switch (action) { 2132 case Action_none: 2133 // Keep the old code. 2134 update_trap_state = false; 2135 break; 2136 case Action_maybe_recompile: 2137 // Do not need to invalidate the present code, but we can 2138 // initiate another 2139 // Start compiler without (necessarily) invalidating the nmethod. 2140 // The system will tolerate the old code, but new code should be 2141 // generated when possible. 2142 break; 2143 case Action_reinterpret: 2144 // Go back into the interpreter for a while, and then consider 2145 // recompiling form scratch. 2146 make_not_entrant = true; 2147 // Reset invocation counter for outer most method. 2148 // This will allow the interpreter to exercise the bytecodes 2149 // for a while before recompiling. 2150 // By contrast, Action_make_not_entrant is immediate. 2151 // 2152 // Note that the compiler will track null_check, null_assert, 2153 // range_check, and class_check events and log them as if they 2154 // had been traps taken from compiled code. This will update 2155 // the MDO trap history so that the next compilation will 2156 // properly detect hot trap sites. 2157 reprofile = true; 2158 break; 2159 case Action_make_not_entrant: 2160 // Request immediate recompilation, and get rid of the old code. 2161 // Make them not entrant, so next time they are called they get 2162 // recompiled. Unloaded classes are loaded now so recompile before next 2163 // time they are called. Same for uninitialized. The interpreter will 2164 // link the missing class, if any. 2165 make_not_entrant = true; 2166 break; 2167 case Action_make_not_compilable: 2168 // Give up on compiling this method at all. 2169 make_not_entrant = true; 2170 make_not_compilable = true; 2171 break; 2172 default: 2173 ShouldNotReachHere(); 2174 } 2175 2176 // Setting +ProfileTraps fixes the following, on all platforms: 2177 // 4852688: ProfileInterpreter is off by default for ia64. The result is 2178 // infinite heroic-opt-uncommon-trap/deopt/recompile cycles, since the 2179 // recompile relies on a MethodData* to record heroic opt failures. 2180 2181 // Whether the interpreter is producing MDO data or not, we also need 2182 // to use the MDO to detect hot deoptimization points and control 2183 // aggressive optimization. 2184 bool inc_recompile_count = false; 2185 ProfileData* pdata = NULL; 2186 if (ProfileTraps && !is_client_compilation_mode_vm() && update_trap_state && trap_mdo != NULL) { 2187 assert(trap_mdo == get_method_data(thread, profiled_method, false), "sanity"); 2188 uint this_trap_count = 0; 2189 bool maybe_prior_trap = false; 2190 bool maybe_prior_recompile = false; 2191 pdata = query_update_method_data(trap_mdo, trap_bci, reason, true, 2192 #if INCLUDE_JVMCI 2193 nm->is_compiled_by_jvmci() && nm->is_osr_method(), 2194 #endif 2195 nm->method(), 2196 //outputs: 2197 this_trap_count, 2198 maybe_prior_trap, 2199 maybe_prior_recompile); 2200 // Because the interpreter also counts null, div0, range, and class 2201 // checks, these traps from compiled code are double-counted. 2202 // This is harmless; it just means that the PerXTrapLimit values 2203 // are in effect a little smaller than they look. 2204 2205 DeoptReason per_bc_reason = reason_recorded_per_bytecode_if_any(reason); 2206 if (per_bc_reason != Reason_none) { 2207 // Now take action based on the partially known per-BCI history. 2208 if (maybe_prior_trap 2209 && this_trap_count >= (uint)PerBytecodeTrapLimit) { 2210 // If there are too many traps at this BCI, force a recompile. 2211 // This will allow the compiler to see the limit overflow, and 2212 // take corrective action, if possible. The compiler generally 2213 // does not use the exact PerBytecodeTrapLimit value, but instead 2214 // changes its tactics if it sees any traps at all. This provides 2215 // a little hysteresis, delaying a recompile until a trap happens 2216 // several times. 2217 // 2218 // Actually, since there is only one bit of counter per BCI, 2219 // the possible per-BCI counts are {0,1,(per-method count)}. 2220 // This produces accurate results if in fact there is only 2221 // one hot trap site, but begins to get fuzzy if there are 2222 // many sites. For example, if there are ten sites each 2223 // trapping two or more times, they each get the blame for 2224 // all of their traps. 2225 make_not_entrant = true; 2226 } 2227 2228 // Detect repeated recompilation at the same BCI, and enforce a limit. 2229 if (make_not_entrant && maybe_prior_recompile) { 2230 // More than one recompile at this point. 2231 inc_recompile_count = maybe_prior_trap; 2232 } 2233 } else { 2234 // For reasons which are not recorded per-bytecode, we simply 2235 // force recompiles unconditionally. 2236 // (Note that PerMethodRecompilationCutoff is enforced elsewhere.) 2237 make_not_entrant = true; 2238 } 2239 2240 // Go back to the compiler if there are too many traps in this method. 2241 if (this_trap_count >= per_method_trap_limit(reason)) { 2242 // If there are too many traps in this method, force a recompile. 2243 // This will allow the compiler to see the limit overflow, and 2244 // take corrective action, if possible. 2245 // (This condition is an unlikely backstop only, because the 2246 // PerBytecodeTrapLimit is more likely to take effect first, 2247 // if it is applicable.) 2248 make_not_entrant = true; 2249 } 2250 2251 // Here's more hysteresis: If there has been a recompile at 2252 // this trap point already, run the method in the interpreter 2253 // for a while to exercise it more thoroughly. 2254 if (make_not_entrant && maybe_prior_recompile && maybe_prior_trap) { 2255 reprofile = true; 2256 } 2257 } 2258 2259 // Take requested actions on the method: 2260 2261 // Recompile 2262 if (make_not_entrant) { 2263 if (!nm->make_not_entrant()) { 2264 return; // the call did not change nmethod's state 2265 } 2266 2267 if (pdata != NULL) { 2268 // Record the recompilation event, if any. 2269 int tstate0 = pdata->trap_state(); 2270 int tstate1 = trap_state_set_recompiled(tstate0, true); 2271 if (tstate1 != tstate0) 2272 pdata->set_trap_state(tstate1); 2273 } 2274 2275 #if INCLUDE_RTM_OPT 2276 // Restart collecting RTM locking abort statistic if the method 2277 // is recompiled for a reason other than RTM state change. 2278 // Assume that in new recompiled code the statistic could be different, 2279 // for example, due to different inlining. 2280 if ((reason != Reason_rtm_state_change) && (trap_mdo != NULL) && 2281 UseRTMDeopt && (nm->as_nmethod()->rtm_state() != ProfileRTM)) { 2282 trap_mdo->atomic_set_rtm_state(ProfileRTM); 2283 } 2284 #endif 2285 // For code aging we count traps separately here, using make_not_entrant() 2286 // as a guard against simultaneous deopts in multiple threads. 2287 if (reason == Reason_tenured && trap_mdo != NULL) { 2288 trap_mdo->inc_tenure_traps(); 2289 } 2290 } 2291 2292 if (inc_recompile_count) { 2293 trap_mdo->inc_overflow_recompile_count(); 2294 if ((uint)trap_mdo->overflow_recompile_count() > 2295 (uint)PerBytecodeRecompilationCutoff) { 2296 // Give up on the method containing the bad BCI. 2297 if (trap_method() == nm->method()) { 2298 make_not_compilable = true; 2299 } else { 2300 trap_method->set_not_compilable("overflow_recompile_count > PerBytecodeRecompilationCutoff", CompLevel_full_optimization); 2301 // But give grace to the enclosing nm->method(). 2302 } 2303 } 2304 } 2305 2306 // Reprofile 2307 if (reprofile) { 2308 CompilationPolicy::policy()->reprofile(trap_scope, nm->is_osr_method()); 2309 } 2310 2311 // Give up compiling 2312 if (make_not_compilable && !nm->method()->is_not_compilable(CompLevel_full_optimization)) { 2313 assert(make_not_entrant, "consistent"); 2314 nm->method()->set_not_compilable("give up compiling", CompLevel_full_optimization); 2315 } 2316 2317 } // Free marked resources 2318 2319 } 2320 JRT_END 2321 2322 ProfileData* 2323 Deoptimization::query_update_method_data(MethodData* trap_mdo, 2324 int trap_bci, 2325 Deoptimization::DeoptReason reason, 2326 bool update_total_trap_count, 2327 #if INCLUDE_JVMCI 2328 bool is_osr, 2329 #endif 2330 Method* compiled_method, 2331 //outputs: 2332 uint& ret_this_trap_count, 2333 bool& ret_maybe_prior_trap, 2334 bool& ret_maybe_prior_recompile) { 2335 bool maybe_prior_trap = false; 2336 bool maybe_prior_recompile = false; 2337 uint this_trap_count = 0; 2338 if (update_total_trap_count) { 2339 uint idx = reason; 2340 #if INCLUDE_JVMCI 2341 if (is_osr) { 2342 idx += Reason_LIMIT; 2343 } 2344 #endif 2345 uint prior_trap_count = trap_mdo->trap_count(idx); 2346 this_trap_count = trap_mdo->inc_trap_count(idx); 2347 2348 // If the runtime cannot find a place to store trap history, 2349 // it is estimated based on the general condition of the method. 2350 // If the method has ever been recompiled, or has ever incurred 2351 // a trap with the present reason , then this BCI is assumed 2352 // (pessimistically) to be the culprit. 2353 maybe_prior_trap = (prior_trap_count != 0); 2354 maybe_prior_recompile = (trap_mdo->decompile_count() != 0); 2355 } 2356 ProfileData* pdata = NULL; 2357 2358 2359 // For reasons which are recorded per bytecode, we check per-BCI data. 2360 DeoptReason per_bc_reason = reason_recorded_per_bytecode_if_any(reason); 2361 assert(per_bc_reason != Reason_none || update_total_trap_count, "must be"); 2362 if (per_bc_reason != Reason_none) { 2363 // Find the profile data for this BCI. If there isn't one, 2364 // try to allocate one from the MDO's set of spares. 2365 // This will let us detect a repeated trap at this point. 2366 pdata = trap_mdo->allocate_bci_to_data(trap_bci, reason_is_speculate(reason) ? compiled_method : NULL); 2367 2368 if (pdata != NULL) { 2369 if (reason_is_speculate(reason) && !pdata->is_SpeculativeTrapData()) { 2370 if (LogCompilation && xtty != NULL) { 2371 ttyLocker ttyl; 2372 // no more room for speculative traps in this MDO 2373 xtty->elem("speculative_traps_oom"); 2374 } 2375 } 2376 // Query the trap state of this profile datum. 2377 int tstate0 = pdata->trap_state(); 2378 if (!trap_state_has_reason(tstate0, per_bc_reason)) 2379 maybe_prior_trap = false; 2380 if (!trap_state_is_recompiled(tstate0)) 2381 maybe_prior_recompile = false; 2382 2383 // Update the trap state of this profile datum. 2384 int tstate1 = tstate0; 2385 // Record the reason. 2386 tstate1 = trap_state_add_reason(tstate1, per_bc_reason); 2387 // Store the updated state on the MDO, for next time. 2388 if (tstate1 != tstate0) 2389 pdata->set_trap_state(tstate1); 2390 } else { 2391 if (LogCompilation && xtty != NULL) { 2392 ttyLocker ttyl; 2393 // Missing MDP? Leave a small complaint in the log. 2394 xtty->elem("missing_mdp bci='%d'", trap_bci); 2395 } 2396 } 2397 } 2398 2399 // Return results: 2400 ret_this_trap_count = this_trap_count; 2401 ret_maybe_prior_trap = maybe_prior_trap; 2402 ret_maybe_prior_recompile = maybe_prior_recompile; 2403 return pdata; 2404 } 2405 2406 void 2407 Deoptimization::update_method_data_from_interpreter(MethodData* trap_mdo, int trap_bci, int reason) { 2408 ResourceMark rm; 2409 // Ignored outputs: 2410 uint ignore_this_trap_count; 2411 bool ignore_maybe_prior_trap; 2412 bool ignore_maybe_prior_recompile; 2413 assert(!reason_is_speculate(reason), "reason speculate only used by compiler"); 2414 // JVMCI uses the total counts to determine if deoptimizations are happening too frequently -> do not adjust total counts 2415 bool update_total_counts = true JVMCI_ONLY( && !UseJVMCICompiler); 2416 query_update_method_data(trap_mdo, trap_bci, 2417 (DeoptReason)reason, 2418 update_total_counts, 2419 #if INCLUDE_JVMCI 2420 false, 2421 #endif 2422 NULL, 2423 ignore_this_trap_count, 2424 ignore_maybe_prior_trap, 2425 ignore_maybe_prior_recompile); 2426 } 2427 2428 Deoptimization::UnrollBlock* Deoptimization::uncommon_trap(JavaThread* thread, jint trap_request, jint exec_mode) { 2429 if (TraceDeoptimization) { 2430 tty->print("Uncommon trap "); 2431 } 2432 // Still in Java no safepoints 2433 { 2434 // This enters VM and may safepoint 2435 uncommon_trap_inner(thread, trap_request); 2436 } 2437 return fetch_unroll_info_helper(thread, exec_mode); 2438 } 2439 2440 // Local derived constants. 2441 // Further breakdown of DataLayout::trap_state, as promised by DataLayout. 2442 const int DS_REASON_MASK = ((uint)DataLayout::trap_mask) >> 1; 2443 const int DS_RECOMPILE_BIT = DataLayout::trap_mask - DS_REASON_MASK; 2444 2445 //---------------------------trap_state_reason--------------------------------- 2446 Deoptimization::DeoptReason 2447 Deoptimization::trap_state_reason(int trap_state) { 2448 // This assert provides the link between the width of DataLayout::trap_bits 2449 // and the encoding of "recorded" reasons. It ensures there are enough 2450 // bits to store all needed reasons in the per-BCI MDO profile. 2451 assert(DS_REASON_MASK >= Reason_RECORDED_LIMIT, "enough bits"); 2452 int recompile_bit = (trap_state & DS_RECOMPILE_BIT); 2453 trap_state -= recompile_bit; 2454 if (trap_state == DS_REASON_MASK) { 2455 return Reason_many; 2456 } else { 2457 assert((int)Reason_none == 0, "state=0 => Reason_none"); 2458 return (DeoptReason)trap_state; 2459 } 2460 } 2461 //-------------------------trap_state_has_reason------------------------------- 2462 int Deoptimization::trap_state_has_reason(int trap_state, int reason) { 2463 assert(reason_is_recorded_per_bytecode((DeoptReason)reason), "valid reason"); 2464 assert(DS_REASON_MASK >= Reason_RECORDED_LIMIT, "enough bits"); 2465 int recompile_bit = (trap_state & DS_RECOMPILE_BIT); 2466 trap_state -= recompile_bit; 2467 if (trap_state == DS_REASON_MASK) { 2468 return -1; // true, unspecifically (bottom of state lattice) 2469 } else if (trap_state == reason) { 2470 return 1; // true, definitely 2471 } else if (trap_state == 0) { 2472 return 0; // false, definitely (top of state lattice) 2473 } else { 2474 return 0; // false, definitely 2475 } 2476 } 2477 //-------------------------trap_state_add_reason------------------------------- 2478 int Deoptimization::trap_state_add_reason(int trap_state, int reason) { 2479 assert(reason_is_recorded_per_bytecode((DeoptReason)reason) || reason == Reason_many, "valid reason"); 2480 int recompile_bit = (trap_state & DS_RECOMPILE_BIT); 2481 trap_state -= recompile_bit; 2482 if (trap_state == DS_REASON_MASK) { 2483 return trap_state + recompile_bit; // already at state lattice bottom 2484 } else if (trap_state == reason) { 2485 return trap_state + recompile_bit; // the condition is already true 2486 } else if (trap_state == 0) { 2487 return reason + recompile_bit; // no condition has yet been true 2488 } else { 2489 return DS_REASON_MASK + recompile_bit; // fall to state lattice bottom 2490 } 2491 } 2492 //-----------------------trap_state_is_recompiled------------------------------ 2493 bool Deoptimization::trap_state_is_recompiled(int trap_state) { 2494 return (trap_state & DS_RECOMPILE_BIT) != 0; 2495 } 2496 //-----------------------trap_state_set_recompiled----------------------------- 2497 int Deoptimization::trap_state_set_recompiled(int trap_state, bool z) { 2498 if (z) return trap_state | DS_RECOMPILE_BIT; 2499 else return trap_state & ~DS_RECOMPILE_BIT; 2500 } 2501 //---------------------------format_trap_state--------------------------------- 2502 // This is used for debugging and diagnostics, including LogFile output. 2503 const char* Deoptimization::format_trap_state(char* buf, size_t buflen, 2504 int trap_state) { 2505 assert(buflen > 0, "sanity"); 2506 DeoptReason reason = trap_state_reason(trap_state); 2507 bool recomp_flag = trap_state_is_recompiled(trap_state); 2508 // Re-encode the state from its decoded components. 2509 int decoded_state = 0; 2510 if (reason_is_recorded_per_bytecode(reason) || reason == Reason_many) 2511 decoded_state = trap_state_add_reason(decoded_state, reason); 2512 if (recomp_flag) 2513 decoded_state = trap_state_set_recompiled(decoded_state, recomp_flag); 2514 // If the state re-encodes properly, format it symbolically. 2515 // Because this routine is used for debugging and diagnostics, 2516 // be robust even if the state is a strange value. 2517 size_t len; 2518 if (decoded_state != trap_state) { 2519 // Random buggy state that doesn't decode?? 2520 len = jio_snprintf(buf, buflen, "#%d", trap_state); 2521 } else { 2522 len = jio_snprintf(buf, buflen, "%s%s", 2523 trap_reason_name(reason), 2524 recomp_flag ? " recompiled" : ""); 2525 } 2526 return buf; 2527 } 2528 2529 2530 //--------------------------------statics-------------------------------------- 2531 const char* Deoptimization::_trap_reason_name[] = { 2532 // Note: Keep this in sync. with enum DeoptReason. 2533 "none", 2534 "null_check", 2535 "null_assert" JVMCI_ONLY("_or_unreached0"), 2536 "range_check", 2537 "class_check", 2538 "array_check", 2539 "intrinsic" JVMCI_ONLY("_or_type_checked_inlining"), 2540 "bimorphic" JVMCI_ONLY("_or_optimized_type_check"), 2541 "profile_predicate", 2542 "unloaded", 2543 "uninitialized", 2544 "initialized", 2545 "unreached", 2546 "unhandled", 2547 "constraint", 2548 "div0_check", 2549 "age", 2550 "predicate", 2551 "loop_limit_check", 2552 "speculate_class_check", 2553 "speculate_null_check", 2554 "speculate_null_assert", 2555 "rtm_state_change", 2556 "unstable_if", 2557 "unstable_fused_if", 2558 #if INCLUDE_JVMCI 2559 "aliasing", 2560 "transfer_to_interpreter", 2561 "not_compiled_exception_handler", 2562 "unresolved", 2563 "jsr_mismatch", 2564 #endif 2565 "tenured" 2566 }; 2567 const char* Deoptimization::_trap_action_name[] = { 2568 // Note: Keep this in sync. with enum DeoptAction. 2569 "none", 2570 "maybe_recompile", 2571 "reinterpret", 2572 "make_not_entrant", 2573 "make_not_compilable" 2574 }; 2575 2576 const char* Deoptimization::trap_reason_name(int reason) { 2577 // Check that every reason has a name 2578 STATIC_ASSERT(sizeof(_trap_reason_name)/sizeof(const char*) == Reason_LIMIT); 2579 2580 if (reason == Reason_many) return "many"; 2581 if ((uint)reason < Reason_LIMIT) 2582 return _trap_reason_name[reason]; 2583 static char buf[20]; 2584 sprintf(buf, "reason%d", reason); 2585 return buf; 2586 } 2587 const char* Deoptimization::trap_action_name(int action) { 2588 // Check that every action has a name 2589 STATIC_ASSERT(sizeof(_trap_action_name)/sizeof(const char*) == Action_LIMIT); 2590 2591 if ((uint)action < Action_LIMIT) 2592 return _trap_action_name[action]; 2593 static char buf[20]; 2594 sprintf(buf, "action%d", action); 2595 return buf; 2596 } 2597 2598 // This is used for debugging and diagnostics, including LogFile output. 2599 const char* Deoptimization::format_trap_request(char* buf, size_t buflen, 2600 int trap_request) { 2601 jint unloaded_class_index = trap_request_index(trap_request); 2602 const char* reason = trap_reason_name(trap_request_reason(trap_request)); 2603 const char* action = trap_action_name(trap_request_action(trap_request)); 2604 #if INCLUDE_JVMCI 2605 int debug_id = trap_request_debug_id(trap_request); 2606 #endif 2607 size_t len; 2608 if (unloaded_class_index < 0) { 2609 len = jio_snprintf(buf, buflen, "reason='%s' action='%s'" JVMCI_ONLY(" debug_id='%d'"), 2610 reason, action 2611 #if INCLUDE_JVMCI 2612 ,debug_id 2613 #endif 2614 ); 2615 } else { 2616 len = jio_snprintf(buf, buflen, "reason='%s' action='%s' index='%d'" JVMCI_ONLY(" debug_id='%d'"), 2617 reason, action, unloaded_class_index 2618 #if INCLUDE_JVMCI 2619 ,debug_id 2620 #endif 2621 ); 2622 } 2623 return buf; 2624 } 2625 2626 juint Deoptimization::_deoptimization_hist 2627 [Deoptimization::Reason_LIMIT] 2628 [1 + Deoptimization::Action_LIMIT] 2629 [Deoptimization::BC_CASE_LIMIT] 2630 = {0}; 2631 2632 enum { 2633 LSB_BITS = 8, 2634 LSB_MASK = right_n_bits(LSB_BITS) 2635 }; 2636 2637 void Deoptimization::gather_statistics(DeoptReason reason, DeoptAction action, 2638 Bytecodes::Code bc) { 2639 assert(reason >= 0 && reason < Reason_LIMIT, "oob"); 2640 assert(action >= 0 && action < Action_LIMIT, "oob"); 2641 _deoptimization_hist[Reason_none][0][0] += 1; // total 2642 _deoptimization_hist[reason][0][0] += 1; // per-reason total 2643 juint* cases = _deoptimization_hist[reason][1+action]; 2644 juint* bc_counter_addr = NULL; 2645 juint bc_counter = 0; 2646 // Look for an unused counter, or an exact match to this BC. 2647 if (bc != Bytecodes::_illegal) { 2648 for (int bc_case = 0; bc_case < BC_CASE_LIMIT; bc_case++) { 2649 juint* counter_addr = &cases[bc_case]; 2650 juint counter = *counter_addr; 2651 if ((counter == 0 && bc_counter_addr == NULL) 2652 || (Bytecodes::Code)(counter & LSB_MASK) == bc) { 2653 // this counter is either free or is already devoted to this BC 2654 bc_counter_addr = counter_addr; 2655 bc_counter = counter | bc; 2656 } 2657 } 2658 } 2659 if (bc_counter_addr == NULL) { 2660 // Overflow, or no given bytecode. 2661 bc_counter_addr = &cases[BC_CASE_LIMIT-1]; 2662 bc_counter = (*bc_counter_addr & ~LSB_MASK); // clear LSB 2663 } 2664 *bc_counter_addr = bc_counter + (1 << LSB_BITS); 2665 } 2666 2667 jint Deoptimization::total_deoptimization_count() { 2668 return _deoptimization_hist[Reason_none][0][0]; 2669 } 2670 2671 void Deoptimization::print_statistics() { 2672 juint total = total_deoptimization_count(); 2673 juint account = total; 2674 if (total != 0) { 2675 ttyLocker ttyl; 2676 if (xtty != NULL) xtty->head("statistics type='deoptimization'"); 2677 tty->print_cr("Deoptimization traps recorded:"); 2678 #define PRINT_STAT_LINE(name, r) \ 2679 tty->print_cr(" %4d (%4.1f%%) %s", (int)(r), ((r) * 100.0) / total, name); 2680 PRINT_STAT_LINE("total", total); 2681 // For each non-zero entry in the histogram, print the reason, 2682 // the action, and (if specifically known) the type of bytecode. 2683 for (int reason = 0; reason < Reason_LIMIT; reason++) { 2684 for (int action = 0; action < Action_LIMIT; action++) { 2685 juint* cases = _deoptimization_hist[reason][1+action]; 2686 for (int bc_case = 0; bc_case < BC_CASE_LIMIT; bc_case++) { 2687 juint counter = cases[bc_case]; 2688 if (counter != 0) { 2689 char name[1*K]; 2690 Bytecodes::Code bc = (Bytecodes::Code)(counter & LSB_MASK); 2691 if (bc_case == BC_CASE_LIMIT && (int)bc == 0) 2692 bc = Bytecodes::_illegal; 2693 sprintf(name, "%s/%s/%s", 2694 trap_reason_name(reason), 2695 trap_action_name(action), 2696 Bytecodes::is_defined(bc)? Bytecodes::name(bc): "other"); 2697 juint r = counter >> LSB_BITS; 2698 tty->print_cr(" %40s: " UINT32_FORMAT " (%.1f%%)", name, r, (r * 100.0) / total); 2699 account -= r; 2700 } 2701 } 2702 } 2703 } 2704 if (account != 0) { 2705 PRINT_STAT_LINE("unaccounted", account); 2706 } 2707 #undef PRINT_STAT_LINE 2708 if (xtty != NULL) xtty->tail("statistics"); 2709 } 2710 } 2711 2712 // Returns true iff objects were reallocated and relocked because of access through JVMTI 2713 bool EscapeBarrier::objs_are_deoptimized(JavaThread* thread, intptr_t* fr_id) { 2714 // first/oldest update holds the flag 2715 GrowableArray<jvmtiDeferredLocalVariableSet*>* list = JvmtiDeferredUpdates::deferred_locals(thread); 2716 bool result = false; 2717 if (list != NULL) { 2718 for (int i = 0; i < list->length(); i++) { 2719 if (list->at(i)->matches(fr_id)) { 2720 result = list->at(i)->objects_are_deoptimized(); 2721 break; 2722 } 2723 } 2724 } 2725 return result; 2726 } 2727 2728 // Object references of frames up to the given depth are about to be accessed. Frames with 2729 // optimizations based on escape state that is potentially changed by the accesses need to be 2730 // deoptimized and the referenced objects need to be reallocated and relocked. 2731 // Up to depth this is done for frames with not escaping objects in scope. For deeper frames it is 2732 // done only, if they pass not escaping objects as arguments, because they potentially escape from 2733 // callee frames within the given depth. 2734 // The search for deeper frames is ended if an entry frame is found, because arguments to 2735 // native methods are considered to escape globally. 2736 bool EscapeBarrier::deoptimize_objects(int depth) { 2737 if (barrier_active() && deoptee_thread()->has_last_Java_frame()) { 2738 ResourceMark rm(calling_thread()); 2739 HandleMark hm; 2740 RegisterMap reg_map(deoptee_thread()); 2741 vframe* vf = deoptee_thread()->last_java_vframe(®_map); 2742 int cur_depth = 0; 2743 while (vf != NULL && ((cur_depth <= depth) || !vf->is_entry_frame())) { 2744 if (vf->is_compiled_frame()) { 2745 compiledVFrame* cvf = compiledVFrame::cast(vf); 2746 // Deoptimize frame and local objects if any exist. 2747 // If cvf is deeper than depth, then we deoptimize iff local objects are passed as args. 2748 bool should_deopt = cur_depth <= depth ? cvf->not_global_escape_in_scope() : cvf->arg_escape(); 2749 if (should_deopt && !deoptimize_objects(cvf->fr().id())) { 2750 // reallocation of scalar replaced objects failed, because heap is exhausted 2751 return false; 2752 } 2753 2754 // move to top frame 2755 while(!vf->is_top()) { 2756 cur_depth++; 2757 vf = vf->sender(); 2758 } 2759 } 2760 2761 // move to next physical frame 2762 cur_depth++; 2763 vf = vf->sender(); 2764 } 2765 } 2766 return true; 2767 } 2768 2769 bool EscapeBarrier::deoptimize_objects_all_threads() { 2770 if (!barrier_active()) return true; 2771 ResourceMark rm(calling_thread()); 2772 for (JavaThreadIteratorWithHandle jtiwh; JavaThread *jt = jtiwh.next(); ) { 2773 if (jt->has_last_Java_frame()) { 2774 RegisterMap reg_map(jt); 2775 vframe* vf = jt->last_java_vframe(®_map); 2776 assert(jt->frame_anchor()->walkable(), 2777 "The stack of JavaThread " PTR_FORMAT " is not walkable. Thread state is %d", 2778 p2i(jt), jt->thread_state()); 2779 while (vf != NULL) { 2780 if (vf->is_compiled_frame()) { 2781 compiledVFrame* cvf = compiledVFrame::cast(vf); 2782 if ((cvf->not_global_escape_in_scope() || cvf->arg_escape()) && 2783 !deoptimize_objects_internal(jt, cvf->fr().id())) { 2784 return false; // reallocation failure 2785 } 2786 // move to top frame 2787 while(!vf->is_top()) { 2788 vf = vf->sender(); 2789 } 2790 } 2791 // move to next physical frame 2792 vf = vf->sender(); 2793 } 2794 } 2795 } 2796 return true; // success 2797 } 2798 2799 bool EscapeBarrier::_deoptimizing_objects_for_all_threads = false; 2800 bool EscapeBarrier::_self_deoptimization_in_progress = false; 2801 2802 class EscapeBarrierSuspendHandshake : public HandshakeClosure { 2803 JavaThread* _excluded_thread; 2804 public: 2805 EscapeBarrierSuspendHandshake(JavaThread* excluded_thread, const char* name) : HandshakeClosure(name), _excluded_thread(excluded_thread) { } 2806 void do_thread(Thread* th) { 2807 if (th->is_Java_thread() && !th->is_hidden_from_external_view() && (th != _excluded_thread)) { 2808 th->set_obj_deopt_flag(); 2809 } 2810 } 2811 }; 2812 2813 void EscapeBarrier::sync_and_suspend_one() { 2814 assert(_calling_thread != NULL, "calling thread must not be NULL"); 2815 assert(_deoptee_thread != NULL, "deoptee thread must not be NULL"); 2816 assert(barrier_active(), "should not call"); 2817 2818 // Sync with other threads that might be doing deoptimizations 2819 { 2820 // Need to switch to _thread_blocked for the wait() call 2821 ThreadBlockInVM tbivm(_calling_thread); 2822 MonitorLocker ml(_calling_thread, EscapeBarrier_lock, Mutex::_no_safepoint_check_flag); 2823 while (_self_deoptimization_in_progress || _deoptee_thread->is_obj_deopt_suspend()) { 2824 ml.wait(); 2825 } 2826 2827 if (self_deopt()) { 2828 _self_deoptimization_in_progress = true; 2829 return; 2830 } 2831 2832 // set suspend flag for target thread 2833 _deoptee_thread->set_obj_deopt_flag(); 2834 } 2835 2836 // suspend target thread 2837 EscapeBarrierSuspendHandshake sh(NULL, "EscapeBarrierSuspendOne"); 2838 Handshake::execute_direct(&sh, _deoptee_thread); 2839 assert(!_deoptee_thread->has_last_Java_frame() || _deoptee_thread->frame_anchor()->walkable(), 2840 "stack should be walkable now"); 2841 } 2842 2843 void EscapeBarrier::sync_and_suspend_all() { 2844 assert(barrier_active(), "should not call"); 2845 assert(_calling_thread != NULL, "calling thread must not be NULL"); 2846 assert(all_threads(), "sanity"); 2847 2848 // Sync with other threads that might be doing deoptimizations 2849 { 2850 // Need to switch to _thread_blocked for the wait() call 2851 ThreadBlockInVM tbivm(_calling_thread); 2852 MonitorLocker ml(_calling_thread, EscapeBarrier_lock, Mutex::_no_safepoint_check_flag); 2853 2854 bool deopt_in_progress; 2855 do { 2856 deopt_in_progress = _self_deoptimization_in_progress; 2857 for (JavaThreadIteratorWithHandle jtiwh; JavaThread *jt = jtiwh.next(); ) { 2858 deopt_in_progress = (deopt_in_progress || jt->is_obj_deopt_suspend()); 2859 if (deopt_in_progress) { 2860 break; 2861 } 2862 } 2863 if (deopt_in_progress) { 2864 ml.wait(); // then check again 2865 } 2866 } while(deopt_in_progress); 2867 2868 _self_deoptimization_in_progress = true; 2869 _deoptimizing_objects_for_all_threads = true; 2870 } 2871 2872 EscapeBarrierSuspendHandshake sh(_calling_thread, "EscapeBarrierSuspendAll"); 2873 Handshake::execute(&sh); 2874 #ifdef ASSERT 2875 for (JavaThreadIteratorWithHandle jtiwh; JavaThread *jt = jtiwh.next(); ) { 2876 if (jt->is_hidden_from_external_view()) continue; 2877 assert(!jt->has_last_Java_frame() || jt->frame_anchor()->walkable(), 2878 "The stack of JavaThread " PTR_FORMAT " is not walkable. Thread state is %d", 2879 p2i(jt), jt->thread_state()); 2880 } 2881 #endif // ASSERT 2882 } 2883 2884 void EscapeBarrier::resume_one() { 2885 assert(barrier_active(), "should not call"); 2886 assert(!all_threads(), "use resume_all()"); 2887 MonitorLocker ml(_calling_thread, EscapeBarrier_lock, Mutex::_no_safepoint_check_flag); 2888 if (self_deopt()) { 2889 assert(_self_deoptimization_in_progress, "incorrect synchronization"); 2890 _self_deoptimization_in_progress = false; 2891 } else { 2892 _deoptee_thread->clear_obj_deopt_flag(); 2893 } 2894 ml.notify_all(); 2895 } 2896 2897 void EscapeBarrier::resume_all() { 2898 assert(barrier_active(), "should not call"); 2899 assert(all_threads(), "use resume_one()"); 2900 MonitorLocker ml(_calling_thread, EscapeBarrier_lock, Mutex::_no_safepoint_check_flag); 2901 assert(_self_deoptimization_in_progress, "incorrect synchronization"); 2902 _deoptimizing_objects_for_all_threads = false; 2903 _self_deoptimization_in_progress = false; 2904 for (JavaThreadIteratorWithHandle jtiwh; JavaThread *jt = jtiwh.next(); ) { 2905 jt->clear_obj_deopt_flag(); 2906 } 2907 ml.notify_all(); 2908 } 2909 2910 void EscapeBarrier::thread_added(JavaThread* jt) { 2911 if (!jt->is_hidden_from_external_view()) { 2912 MutexLocker ml(EscapeBarrier_lock, Mutex::_no_safepoint_check_flag); 2913 if (_deoptimizing_objects_for_all_threads) { 2914 jt->set_obj_deopt_flag(); 2915 } 2916 } 2917 } 2918 2919 void EscapeBarrier::thread_removed(JavaThread* jt) { 2920 MonitorLocker ml(EscapeBarrier_lock, Mutex::_no_safepoint_check_flag); 2921 if (jt->is_obj_deopt_suspend()) { 2922 // jt terminated before it self suspended. 2923 // Other threads might be waiting to perform deoptimizations for it. 2924 jt->clear_obj_deopt_flag(); 2925 ml.notify_all(); 2926 } 2927 } 2928 2929 // Remember that objects were reallocated and relocked for the compiled frame with the given id 2930 static void set_objs_are_deoptimized(JavaThread* thread, intptr_t* fr_id) { 2931 // set in first/oldest update 2932 GrowableArray<jvmtiDeferredLocalVariableSet*>* list = JvmtiDeferredUpdates::deferred_locals(thread); 2933 DEBUG_ONLY(bool found = false); 2934 if (list != NULL) { 2935 for (int i = 0; i < list->length(); i++) { 2936 if (list->at(i)->matches(fr_id)) { 2937 DEBUG_ONLY(found = true); 2938 list->at(i)->set_objs_are_deoptimized(); 2939 break; 2940 } 2941 } 2942 } 2943 assert(found, "variable set should exist at least for one vframe"); 2944 } 2945 2946 // Deoptimize the given frame and deoptimize objects with optimizations based on escape analysis, 2947 // i.e. reallocate scalar replaced objects on the heap and relock objects if locking has been 2948 // eliminated. 2949 // Deoptimized objects are kept as JVMTI deferred updates until the compiled frame is replaced with interpreter frames. 2950 // Returns false iff at least one reallocation failed. 2951 bool EscapeBarrier::deoptimize_objects_internal(JavaThread* deoptee, intptr_t* fr_id) { 2952 if (!barrier_active()) return true; 2953 2954 JavaThread* ct = calling_thread(); 2955 bool realloc_failures = false; 2956 2957 if (!objs_are_deoptimized(deoptee, fr_id)) { 2958 // Make sure the frame identified by fr_id is deoptimized and fetch its last vframe 2959 compiledVFrame* last_cvf; 2960 bool fr_is_deoptimized; 2961 do { 2962 StackFrameStream fst(deoptee); 2963 while (fst.current()->id() != fr_id && !fst.is_done()) { 2964 fst.next(); 2965 } 2966 assert(fst.current()->id() == fr_id, "frame not found"); 2967 assert(fst.current()->is_compiled_frame(), "only compiled frames can contain stack allocated objects"); 2968 fr_is_deoptimized = fst.current()->is_deoptimized_frame(); 2969 if (!fr_is_deoptimized) { 2970 // Execution must not continue in the compiled method, so we deoptimize the frame. 2971 Deoptimization::deoptimize_frame(deoptee, fr_id); 2972 } else { 2973 last_cvf = compiledVFrame::cast(vframe::new_vframe(fst.current(), fst.register_map(), deoptee)); 2974 } 2975 } while(!fr_is_deoptimized); 2976 2977 // collect inlined frames 2978 compiledVFrame* cvf = last_cvf; 2979 GrowableArray<compiledVFrame*>* vfs = new GrowableArray<compiledVFrame*>(10); 2980 while (!cvf->is_top()) { 2981 vfs->push(cvf); 2982 cvf = compiledVFrame::cast(cvf->sender()); 2983 } 2984 vfs->push(cvf); 2985 2986 // reallocate and relock optimized objects 2987 bool deoptimized_objects = Deoptimization::deoptimize_objects_internal(ct, vfs, realloc_failures); 2988 if (!realloc_failures && deoptimized_objects) { 2989 // now do the updates 2990 for (int frame_index = 0; frame_index < vfs->length(); frame_index++) { 2991 cvf = vfs->at(frame_index); 2992 2993 // locals 2994 GrowableArray<ScopeValue*>* scopeLocals = cvf->scope()->locals(); 2995 StackValueCollection* locals = cvf->locals(); 2996 if (locals != NULL) { 2997 for (int i2 = 0; i2 < locals->size(); i2++) { 2998 StackValue* var = locals->at(i2); 2999 if (var->type() == T_OBJECT && scopeLocals->at(i2)->is_object()) { 3000 jvalue val; 3001 val.l = cast_from_oop<jobject>(locals->at(i2)->get_obj()()); 3002 cvf->update_local(T_OBJECT, i2, val); 3003 } 3004 } 3005 } 3006 3007 // expressions 3008 GrowableArray<ScopeValue*>* scopeExpressions = cvf->scope()->expressions(); 3009 StackValueCollection* expressions = cvf->expressions(); 3010 if (expressions != NULL) { 3011 for (int i2 = 0; i2 < expressions->size(); i2++) { 3012 StackValue* var = expressions->at(i2); 3013 if (var->type() == T_OBJECT && scopeExpressions->at(i2)->is_object()) { 3014 jvalue val; 3015 val.l = cast_from_oop<jobject>(expressions->at(i2)->get_obj()()); 3016 cvf->update_stack(T_OBJECT, i2, val); 3017 } 3018 } 3019 } 3020 3021 // monitors 3022 GrowableArray<MonitorInfo*>* monitors = cvf->monitors(); 3023 if (monitors != NULL) { 3024 for (int i2 = 0; i2 < monitors->length(); i2++) { 3025 if (monitors->at(i2)->eliminated()) { 3026 assert(!monitors->at(i2)->owner_is_scalar_replaced(), "reallocation failure, should not update"); 3027 cvf->update_monitor(i2, monitors->at(i2)); 3028 } 3029 } 3030 } 3031 } 3032 set_objs_are_deoptimized(deoptee, fr_id); 3033 } 3034 } 3035 return !realloc_failures; 3036 } 3037 3038 #else // COMPILER2_OR_JVMCI 3039 3040 3041 // Stubs for C1 only system. 3042 bool Deoptimization::trap_state_is_recompiled(int trap_state) { 3043 return false; 3044 } 3045 3046 const char* Deoptimization::trap_reason_name(int reason) { 3047 return "unknown"; 3048 } 3049 3050 void Deoptimization::print_statistics() { 3051 // no output 3052 } 3053 3054 void 3055 Deoptimization::update_method_data_from_interpreter(MethodData* trap_mdo, int trap_bci, int reason) { 3056 // no udpate 3057 } 3058 3059 int Deoptimization::trap_state_has_reason(int trap_state, int reason) { 3060 return 0; 3061 } 3062 3063 void Deoptimization::gather_statistics(DeoptReason reason, DeoptAction action, 3064 Bytecodes::Code bc) { 3065 // no update 3066 } 3067 3068 const char* Deoptimization::format_trap_state(char* buf, size_t buflen, 3069 int trap_state) { 3070 jio_snprintf(buf, buflen, "#%d", trap_state); 3071 return buf; 3072 } 3073 3074 #endif // COMPILER2_OR_JVMCI