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