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