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