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