1 /* 2 * Copyright (c) 1997, 2014, 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 "prims/jvmtiThreadState.hpp" 41 #include "runtime/biasedLocking.hpp" 42 #include "runtime/compilationPolicy.hpp" 43 #include "runtime/deoptimization.hpp" 44 #include "runtime/interfaceSupport.hpp" 45 #include "runtime/sharedRuntime.hpp" 46 #include "runtime/signature.hpp" 47 #include "runtime/stubRoutines.hpp" 48 #include "runtime/thread.hpp" 49 #include "runtime/vframe.hpp" 50 #include "runtime/vframeArray.hpp" 51 #include "runtime/vframe_hp.hpp" 52 #include "utilities/events.hpp" 53 #include "utilities/xmlstream.hpp" 54 55 PRAGMA_FORMAT_MUTE_WARNINGS_FOR_GCC 56 57 bool DeoptimizationMarker::_is_active = false; 58 59 Deoptimization::UnrollBlock::UnrollBlock(int size_of_deoptimized_frame, 60 int caller_adjustment, 61 int caller_actual_parameters, 62 int number_of_frames, 63 intptr_t* frame_sizes, 64 address* frame_pcs, 65 BasicType return_type) { 66 _size_of_deoptimized_frame = size_of_deoptimized_frame; 67 _caller_adjustment = caller_adjustment; 68 _caller_actual_parameters = caller_actual_parameters; 69 _number_of_frames = number_of_frames; 70 _frame_sizes = frame_sizes; 71 _frame_pcs = frame_pcs; 72 _register_block = NEW_C_HEAP_ARRAY(intptr_t, RegisterMap::reg_count * 2, mtCompiler); 73 _return_type = return_type; 74 _initial_info = 0; 75 // PD (x86 only) 76 _counter_temp = 0; 77 _unpack_kind = 0; 78 _sender_sp_temp = 0; 79 80 _total_frame_sizes = size_of_frames(); 81 } 82 83 84 Deoptimization::UnrollBlock::~UnrollBlock() { 85 FREE_C_HEAP_ARRAY(intptr_t, _frame_sizes); 86 FREE_C_HEAP_ARRAY(intptr_t, _frame_pcs); 87 FREE_C_HEAP_ARRAY(intptr_t, _register_block); 88 } 89 90 91 intptr_t* Deoptimization::UnrollBlock::value_addr_at(int register_number) const { 92 assert(register_number < RegisterMap::reg_count, "checking register number"); 93 return &_register_block[register_number * 2]; 94 } 95 96 97 98 int Deoptimization::UnrollBlock::size_of_frames() const { 99 // Acount first for the adjustment of the initial frame 100 int result = _caller_adjustment; 101 for (int index = 0; index < number_of_frames(); index++) { 102 result += frame_sizes()[index]; 103 } 104 return result; 105 } 106 107 108 void Deoptimization::UnrollBlock::print() { 109 ttyLocker ttyl; 110 tty->print_cr("UnrollBlock"); 111 tty->print_cr(" size_of_deoptimized_frame = %d", _size_of_deoptimized_frame); 112 tty->print( " frame_sizes: "); 113 for (int index = 0; index < number_of_frames(); index++) { 114 tty->print("%d ", frame_sizes()[index]); 115 } 116 tty->cr(); 117 } 118 119 120 // In order to make fetch_unroll_info work properly with escape 121 // analysis, The method was changed from JRT_LEAF to JRT_BLOCK_ENTRY and 122 // ResetNoHandleMark and HandleMark were removed from it. The actual reallocation 123 // of previously eliminated objects occurs in realloc_objects, which is 124 // called from the method fetch_unroll_info_helper below. 125 JRT_BLOCK_ENTRY(Deoptimization::UnrollBlock*, Deoptimization::fetch_unroll_info(JavaThread* thread)) 126 // It is actually ok to allocate handles in a leaf method. It causes no safepoints, 127 // but makes the entry a little slower. There is however a little dance we have to 128 // do in debug mode to get around the NoHandleMark code in the JRT_LEAF macro 129 130 // fetch_unroll_info() is called at the beginning of the deoptimization 131 // handler. Note this fact before we start generating temporary frames 132 // that can confuse an asynchronous stack walker. This counter is 133 // decremented at the end of unpack_frames(). 134 thread->inc_in_deopt_handler(); 135 136 return fetch_unroll_info_helper(thread); 137 JRT_END 138 139 140 // This is factored, since it is both called from a JRT_LEAF (deoptimization) and a JRT_ENTRY (uncommon_trap) 141 Deoptimization::UnrollBlock* Deoptimization::fetch_unroll_info_helper(JavaThread* thread) { 142 143 // Note: there is a safepoint safety issue here. No matter whether we enter 144 // via vanilla deopt or uncommon trap we MUST NOT stop at a safepoint once 145 // the vframeArray is created. 146 // 147 148 // Allocate our special deoptimization ResourceMark 149 DeoptResourceMark* dmark = new DeoptResourceMark(thread); 150 assert(thread->deopt_mark() == NULL, "Pending deopt!"); 151 thread->set_deopt_mark(dmark); 152 153 frame stub_frame = thread->last_frame(); // Makes stack walkable as side effect 154 RegisterMap map(thread, true); 155 RegisterMap dummy_map(thread, false); 156 // Now get the deoptee with a valid map 157 frame deoptee = stub_frame.sender(&map); 158 // Set the deoptee nmethod 159 assert(thread->deopt_nmethod() == NULL, "Pending deopt!"); 160 thread->set_deopt_nmethod(deoptee.cb()->as_nmethod_or_null()); 161 162 if (VerifyStack) { 163 thread->validate_frame_layout(); 164 } 165 166 // Create a growable array of VFrames where each VFrame represents an inlined 167 // Java frame. This storage is allocated with the usual system arena. 168 assert(deoptee.is_compiled_frame(), "Wrong frame type"); 169 GrowableArray<compiledVFrame*>* chunk = new GrowableArray<compiledVFrame*>(10); 170 vframe* vf = vframe::new_vframe(&deoptee, &map, thread); 171 while (!vf->is_top()) { 172 assert(vf->is_compiled_frame(), "Wrong frame type"); 173 chunk->push(compiledVFrame::cast(vf)); 174 vf = vf->sender(); 175 } 176 assert(vf->is_compiled_frame(), "Wrong frame type"); 177 chunk->push(compiledVFrame::cast(vf)); 178 179 bool realloc_failures = false; 180 181 #ifdef COMPILER2 182 // Reallocate the non-escaping objects and restore their fields. Then 183 // relock objects if synchronization on them was eliminated. 184 if (DoEscapeAnalysis || EliminateNestedLocks) { 185 if (EliminateAllocations) { 186 assert (chunk->at(0)->scope() != NULL,"expect only compiled java frames"); 187 GrowableArray<ScopeValue*>* objects = chunk->at(0)->scope()->objects(); 188 189 // The flag return_oop() indicates call sites which return oop 190 // in compiled code. Such sites include java method calls, 191 // runtime calls (for example, used to allocate new objects/arrays 192 // on slow code path) and any other calls generated in compiled code. 193 // It is not guaranteed that we can get such information here only 194 // by analyzing bytecode in deoptimized frames. This is why this flag 195 // is set during method compilation (see Compile::Process_OopMap_Node()). 196 // If the previous frame was popped, we don't have a result. 197 bool save_oop_result = chunk->at(0)->scope()->return_oop() && !thread->popframe_forcing_deopt_reexecution(); 198 Handle return_value; 199 if (save_oop_result) { 200 // Reallocation may trigger GC. If deoptimization happened on return from 201 // call which returns oop we need to save it since it is not in oopmap. 202 oop result = deoptee.saved_oop_result(&map); 203 assert(result == NULL || result->is_oop(), "must be oop"); 204 return_value = Handle(thread, result); 205 assert(Universe::heap()->is_in_or_null(result), "must be heap pointer"); 206 if (TraceDeoptimization) { 207 ttyLocker ttyl; 208 tty->print_cr("SAVED OOP RESULT " INTPTR_FORMAT " in thread " INTPTR_FORMAT, (void *)result, thread); 209 } 210 } 211 if (objects != NULL) { 212 JRT_BLOCK 213 realloc_failures = realloc_objects(thread, &deoptee, objects, THREAD); 214 JRT_END 215 reassign_fields(&deoptee, &map, objects, realloc_failures); 216 #ifndef PRODUCT 217 if (TraceDeoptimization) { 218 ttyLocker ttyl; 219 tty->print_cr("REALLOC OBJECTS in thread " INTPTR_FORMAT, thread); 220 print_objects(objects, realloc_failures); 221 } 222 #endif 223 } 224 if (save_oop_result) { 225 // Restore result. 226 deoptee.set_saved_oop_result(&map, return_value()); 227 } 228 } 229 if (EliminateLocks) { 230 #ifndef PRODUCT 231 bool first = true; 232 #endif 233 for (int i = 0; i < chunk->length(); i++) { 234 compiledVFrame* cvf = chunk->at(i); 235 assert (cvf->scope() != NULL,"expect only compiled java frames"); 236 GrowableArray<MonitorInfo*>* monitors = cvf->monitors(); 237 if (monitors->is_nonempty()) { 238 relock_objects(monitors, thread, realloc_failures); 239 #ifndef PRODUCT 240 if (TraceDeoptimization) { 241 ttyLocker ttyl; 242 for (int j = 0; j < monitors->length(); j++) { 243 MonitorInfo* mi = monitors->at(j); 244 if (mi->eliminated()) { 245 if (first) { 246 first = false; 247 tty->print_cr("RELOCK OBJECTS in thread " INTPTR_FORMAT, thread); 248 } 249 if (mi->owner_is_scalar_replaced()) { 250 Klass* k = java_lang_Class::as_Klass(mi->owner_klass()); 251 tty->print_cr(" failed reallocation for klass %s", k->external_name()); 252 } else { 253 tty->print_cr(" object <" INTPTR_FORMAT "> locked", (void *)mi->owner()); 254 } 255 } 256 } 257 } 258 #endif 259 } 260 } 261 } 262 } 263 #endif // COMPILER2 264 // Ensure that no safepoint is taken after pointers have been stored 265 // in fields of rematerialized objects. If a safepoint occurs from here on 266 // out the java state residing in the vframeArray will be missed. 267 No_Safepoint_Verifier no_safepoint; 268 269 vframeArray* array = create_vframeArray(thread, deoptee, &map, chunk, realloc_failures); 270 #ifdef COMPILER2 271 if (realloc_failures) { 272 pop_frames_failed_reallocs(thread, array); 273 } 274 #endif 275 276 assert(thread->vframe_array_head() == NULL, "Pending deopt!"); 277 thread->set_vframe_array_head(array); 278 279 // Now that the vframeArray has been created if we have any deferred local writes 280 // added by jvmti then we can free up that structure as the data is now in the 281 // vframeArray 282 283 if (thread->deferred_locals() != NULL) { 284 GrowableArray<jvmtiDeferredLocalVariableSet*>* list = thread->deferred_locals(); 285 int i = 0; 286 do { 287 // Because of inlining we could have multiple vframes for a single frame 288 // and several of the vframes could have deferred writes. Find them all. 289 if (list->at(i)->id() == array->original().id()) { 290 jvmtiDeferredLocalVariableSet* dlv = list->at(i); 291 list->remove_at(i); 292 // individual jvmtiDeferredLocalVariableSet are CHeapObj's 293 delete dlv; 294 } else { 295 i++; 296 } 297 } while ( i < list->length() ); 298 if (list->length() == 0) { 299 thread->set_deferred_locals(NULL); 300 // free the list and elements back to C heap. 301 delete list; 302 } 303 304 } 305 306 #ifndef SHARK 307 // Compute the caller frame based on the sender sp of stub_frame and stored frame sizes info. 308 CodeBlob* cb = stub_frame.cb(); 309 // Verify we have the right vframeArray 310 assert(cb->frame_size() >= 0, "Unexpected frame size"); 311 intptr_t* unpack_sp = stub_frame.sp() + cb->frame_size(); 312 313 // If the deopt call site is a MethodHandle invoke call site we have 314 // to adjust the unpack_sp. 315 nmethod* deoptee_nm = deoptee.cb()->as_nmethod_or_null(); 316 if (deoptee_nm != NULL && deoptee_nm->is_method_handle_return(deoptee.pc())) 317 unpack_sp = deoptee.unextended_sp(); 318 319 #ifdef ASSERT 320 assert(cb->is_deoptimization_stub() || cb->is_uncommon_trap_stub(), "just checking"); 321 #endif 322 #else 323 intptr_t* unpack_sp = stub_frame.sender(&dummy_map).unextended_sp(); 324 #endif // !SHARK 325 326 // This is a guarantee instead of an assert because if vframe doesn't match 327 // we will unpack the wrong deoptimized frame and wind up in strange places 328 // where it will be very difficult to figure out what went wrong. Better 329 // to die an early death here than some very obscure death later when the 330 // trail is cold. 331 // Note: on ia64 this guarantee can be fooled by frames with no memory stack 332 // in that it will fail to detect a problem when there is one. This needs 333 // more work in tiger timeframe. 334 guarantee(array->unextended_sp() == unpack_sp, "vframe_array_head must contain the vframeArray to unpack"); 335 336 int number_of_frames = array->frames(); 337 338 // Compute the vframes' sizes. Note that frame_sizes[] entries are ordered from outermost to innermost 339 // virtual activation, which is the reverse of the elements in the vframes array. 340 intptr_t* frame_sizes = NEW_C_HEAP_ARRAY(intptr_t, number_of_frames, mtCompiler); 341 // +1 because we always have an interpreter return address for the final slot. 342 address* frame_pcs = NEW_C_HEAP_ARRAY(address, number_of_frames + 1, mtCompiler); 343 int popframe_extra_args = 0; 344 // Create an interpreter return address for the stub to use as its return 345 // address so the skeletal frames are perfectly walkable 346 frame_pcs[number_of_frames] = Interpreter::deopt_entry(vtos, 0); 347 348 // PopFrame requires that the preserved incoming arguments from the recently-popped topmost 349 // activation be put back on the expression stack of the caller for reexecution 350 if (JvmtiExport::can_pop_frame() && thread->popframe_forcing_deopt_reexecution()) { 351 popframe_extra_args = in_words(thread->popframe_preserved_args_size_in_words()); 352 } 353 354 // Find the current pc for sender of the deoptee. Since the sender may have been deoptimized 355 // itself since the deoptee vframeArray was created we must get a fresh value of the pc rather 356 // than simply use array->sender.pc(). This requires us to walk the current set of frames 357 // 358 frame deopt_sender = stub_frame.sender(&dummy_map); // First is the deoptee frame 359 deopt_sender = deopt_sender.sender(&dummy_map); // Now deoptee caller 360 361 // It's possible that the number of parameters at the call site is 362 // different than number of arguments in the callee when method 363 // handles are used. If the caller is interpreted get the real 364 // value so that the proper amount of space can be added to it's 365 // frame. 366 bool caller_was_method_handle = false; 367 if (deopt_sender.is_interpreted_frame()) { 368 methodHandle method = deopt_sender.interpreter_frame_method(); 369 Bytecode_invoke cur = Bytecode_invoke_check(method, deopt_sender.interpreter_frame_bci()); 370 if (cur.is_invokedynamic() || cur.is_invokehandle()) { 371 // Method handle invokes may involve fairly arbitrary chains of 372 // calls so it's impossible to know how much actual space the 373 // caller has for locals. 374 caller_was_method_handle = true; 375 } 376 } 377 378 // 379 // frame_sizes/frame_pcs[0] oldest frame (int or c2i) 380 // frame_sizes/frame_pcs[1] next oldest frame (int) 381 // frame_sizes/frame_pcs[n] youngest frame (int) 382 // 383 // Now a pc in frame_pcs is actually the return address to the frame's caller (a frame 384 // owns the space for the return address to it's caller). Confusing ain't it. 385 // 386 // The vframe array can address vframes with indices running from 387 // 0.._frames-1. Index 0 is the youngest frame and _frame - 1 is the oldest (root) frame. 388 // When we create the skeletal frames we need the oldest frame to be in the zero slot 389 // in the frame_sizes/frame_pcs so the assembly code can do a trivial walk. 390 // so things look a little strange in this loop. 391 // 392 int callee_parameters = 0; 393 int callee_locals = 0; 394 for (int index = 0; index < array->frames(); index++ ) { 395 // frame[number_of_frames - 1 ] = on_stack_size(youngest) 396 // frame[number_of_frames - 2 ] = on_stack_size(sender(youngest)) 397 // frame[number_of_frames - 3 ] = on_stack_size(sender(sender(youngest))) 398 frame_sizes[number_of_frames - 1 - index] = BytesPerWord * array->element(index)->on_stack_size(callee_parameters, 399 callee_locals, 400 index == 0, 401 popframe_extra_args); 402 // This pc doesn't have to be perfect just good enough to identify the frame 403 // as interpreted so the skeleton frame will be walkable 404 // The correct pc will be set when the skeleton frame is completely filled out 405 // The final pc we store in the loop is wrong and will be overwritten below 406 frame_pcs[number_of_frames - 1 - index ] = Interpreter::deopt_entry(vtos, 0) - frame::pc_return_offset; 407 408 callee_parameters = array->element(index)->method()->size_of_parameters(); 409 callee_locals = array->element(index)->method()->max_locals(); 410 popframe_extra_args = 0; 411 } 412 413 // Compute whether the root vframe returns a float or double value. 414 BasicType return_type; 415 { 416 HandleMark hm; 417 methodHandle method(thread, array->element(0)->method()); 418 Bytecode_invoke invoke = Bytecode_invoke_check(method, array->element(0)->bci()); 419 return_type = invoke.is_valid() ? invoke.result_type() : T_ILLEGAL; 420 } 421 422 // Compute information for handling adapters and adjusting the frame size of the caller. 423 int caller_adjustment = 0; 424 425 // Compute the amount the oldest interpreter frame will have to adjust 426 // its caller's stack by. If the caller is a compiled frame then 427 // we pretend that the callee has no parameters so that the 428 // extension counts for the full amount of locals and not just 429 // locals-parms. This is because without a c2i adapter the parm 430 // area as created by the compiled frame will not be usable by 431 // the interpreter. (Depending on the calling convention there 432 // may not even be enough space). 433 434 // QQQ I'd rather see this pushed down into last_frame_adjust 435 // and have it take the sender (aka caller). 436 437 if (deopt_sender.is_compiled_frame() || caller_was_method_handle) { 438 caller_adjustment = last_frame_adjust(0, callee_locals); 439 } else if (callee_locals > callee_parameters) { 440 // The caller frame may need extending to accommodate 441 // non-parameter locals of the first unpacked interpreted frame. 442 // Compute that adjustment. 443 caller_adjustment = last_frame_adjust(callee_parameters, callee_locals); 444 } 445 446 // If the sender is deoptimized the we must retrieve the address of the handler 447 // since the frame will "magically" show the original pc before the deopt 448 // and we'd undo the deopt. 449 450 frame_pcs[0] = deopt_sender.raw_pc(); 451 452 #ifndef SHARK 453 assert(CodeCache::find_blob_unsafe(frame_pcs[0]) != NULL, "bad pc"); 454 #endif // SHARK 455 456 UnrollBlock* info = new UnrollBlock(array->frame_size() * BytesPerWord, 457 caller_adjustment * BytesPerWord, 458 caller_was_method_handle ? 0 : callee_parameters, 459 number_of_frames, 460 frame_sizes, 461 frame_pcs, 462 return_type); 463 // On some platforms, we need a way to pass some platform dependent 464 // information to the unpacking code so the skeletal frames come out 465 // correct (initial fp value, unextended sp, ...) 466 info->set_initial_info((intptr_t) array->sender().initial_deoptimization_info()); 467 468 if (array->frames() > 1) { 469 if (VerifyStack && TraceDeoptimization) { 470 ttyLocker ttyl; 471 tty->print_cr("Deoptimizing method containing inlining"); 472 } 473 } 474 475 array->set_unroll_block(info); 476 return info; 477 } 478 479 // Called to cleanup deoptimization data structures in normal case 480 // after unpacking to stack and when stack overflow error occurs 481 void Deoptimization::cleanup_deopt_info(JavaThread *thread, 482 vframeArray *array) { 483 484 // Get array if coming from exception 485 if (array == NULL) { 486 array = thread->vframe_array_head(); 487 } 488 thread->set_vframe_array_head(NULL); 489 490 // Free the previous UnrollBlock 491 vframeArray* old_array = thread->vframe_array_last(); 492 thread->set_vframe_array_last(array); 493 494 if (old_array != NULL) { 495 UnrollBlock* old_info = old_array->unroll_block(); 496 old_array->set_unroll_block(NULL); 497 delete old_info; 498 delete old_array; 499 } 500 501 // Deallocate any resource creating in this routine and any ResourceObjs allocated 502 // inside the vframeArray (StackValueCollections) 503 504 delete thread->deopt_mark(); 505 thread->set_deopt_mark(NULL); 506 thread->set_deopt_nmethod(NULL); 507 508 509 if (JvmtiExport::can_pop_frame()) { 510 #ifndef CC_INTERP 511 // Regardless of whether we entered this routine with the pending 512 // popframe condition bit set, we should always clear it now 513 thread->clear_popframe_condition(); 514 #else 515 // C++ interpreter will clear has_pending_popframe when it enters 516 // with method_resume. For deopt_resume2 we clear it now. 517 if (thread->popframe_forcing_deopt_reexecution()) 518 thread->clear_popframe_condition(); 519 #endif /* CC_INTERP */ 520 } 521 522 // unpack_frames() is called at the end of the deoptimization handler 523 // and (in C2) at the end of the uncommon trap handler. Note this fact 524 // so that an asynchronous stack walker can work again. This counter is 525 // incremented at the beginning of fetch_unroll_info() and (in C2) at 526 // the beginning of uncommon_trap(). 527 thread->dec_in_deopt_handler(); 528 } 529 530 531 // Return BasicType of value being returned 532 JRT_LEAF(BasicType, Deoptimization::unpack_frames(JavaThread* thread, int exec_mode)) 533 534 // We are already active int he special DeoptResourceMark any ResourceObj's we 535 // allocate will be freed at the end of the routine. 536 537 // It is actually ok to allocate handles in a leaf method. It causes no safepoints, 538 // but makes the entry a little slower. There is however a little dance we have to 539 // do in debug mode to get around the NoHandleMark code in the JRT_LEAF macro 540 ResetNoHandleMark rnhm; // No-op in release/product versions 541 HandleMark hm; 542 543 frame stub_frame = thread->last_frame(); 544 545 // Since the frame to unpack is the top frame of this thread, the vframe_array_head 546 // must point to the vframeArray for the unpack frame. 547 vframeArray* array = thread->vframe_array_head(); 548 549 #ifndef PRODUCT 550 if (TraceDeoptimization) { 551 ttyLocker ttyl; 552 tty->print_cr("DEOPT UNPACKING thread " INTPTR_FORMAT " vframeArray " INTPTR_FORMAT " mode %d", thread, array, exec_mode); 553 } 554 #endif 555 Events::log(thread, "DEOPT UNPACKING pc=" INTPTR_FORMAT " sp=" INTPTR_FORMAT " mode %d", 556 stub_frame.pc(), 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 = " UINTX_FORMAT, 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 ", (void *)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, fr.pc(), fr.sp()); 988 989 #ifndef PRODUCT 990 if (TraceDeoptimization) { 991 ttyLocker ttyl; 992 tty->print("DEOPT PACKING thread " INTPTR_FORMAT " ", 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, 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, 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), 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 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 bool update_trap_state = (reason != Reason_tenured); 1463 bool make_not_entrant = false; 1464 bool make_not_compilable = false; 1465 bool reprofile = false; 1466 switch (action) { 1467 case Action_none: 1468 // Keep the old code. 1469 update_trap_state = false; 1470 break; 1471 case Action_maybe_recompile: 1472 // Do not need to invalidate the present code, but we can 1473 // initiate another 1474 // Start compiler without (necessarily) invalidating the nmethod. 1475 // The system will tolerate the old code, but new code should be 1476 // generated when possible. 1477 break; 1478 case Action_reinterpret: 1479 // Go back into the interpreter for a while, and then consider 1480 // recompiling form scratch. 1481 make_not_entrant = true; 1482 // Reset invocation counter for outer most method. 1483 // This will allow the interpreter to exercise the bytecodes 1484 // for a while before recompiling. 1485 // By contrast, Action_make_not_entrant is immediate. 1486 // 1487 // Note that the compiler will track null_check, null_assert, 1488 // range_check, and class_check events and log them as if they 1489 // had been traps taken from compiled code. This will update 1490 // the MDO trap history so that the next compilation will 1491 // properly detect hot trap sites. 1492 reprofile = true; 1493 break; 1494 case Action_make_not_entrant: 1495 // Request immediate recompilation, and get rid of the old code. 1496 // Make them not entrant, so next time they are called they get 1497 // recompiled. Unloaded classes are loaded now so recompile before next 1498 // time they are called. Same for uninitialized. The interpreter will 1499 // link the missing class, if any. 1500 make_not_entrant = true; 1501 break; 1502 case Action_make_not_compilable: 1503 // Give up on compiling this method at all. 1504 make_not_entrant = true; 1505 make_not_compilable = true; 1506 break; 1507 default: 1508 ShouldNotReachHere(); 1509 } 1510 1511 // Setting +ProfileTraps fixes the following, on all platforms: 1512 // 4852688: ProfileInterpreter is off by default for ia64. The result is 1513 // infinite heroic-opt-uncommon-trap/deopt/recompile cycles, since the 1514 // recompile relies on a MethodData* to record heroic opt failures. 1515 1516 // Whether the interpreter is producing MDO data or not, we also need 1517 // to use the MDO to detect hot deoptimization points and control 1518 // aggressive optimization. 1519 bool inc_recompile_count = false; 1520 ProfileData* pdata = NULL; 1521 if (ProfileTraps && update_trap_state && trap_mdo != NULL) { 1522 assert(trap_mdo == get_method_data(thread, trap_method, false), "sanity"); 1523 uint this_trap_count = 0; 1524 bool maybe_prior_trap = false; 1525 bool maybe_prior_recompile = false; 1526 pdata = query_update_method_data(trap_mdo, trap_bci, reason, 1527 nm->method(), 1528 //outputs: 1529 this_trap_count, 1530 maybe_prior_trap, 1531 maybe_prior_recompile); 1532 // Because the interpreter also counts null, div0, range, and class 1533 // checks, these traps from compiled code are double-counted. 1534 // This is harmless; it just means that the PerXTrapLimit values 1535 // are in effect a little smaller than they look. 1536 1537 DeoptReason per_bc_reason = reason_recorded_per_bytecode_if_any(reason); 1538 if (per_bc_reason != Reason_none) { 1539 // Now take action based on the partially known per-BCI history. 1540 if (maybe_prior_trap 1541 && this_trap_count >= (uint)PerBytecodeTrapLimit) { 1542 // If there are too many traps at this BCI, force a recompile. 1543 // This will allow the compiler to see the limit overflow, and 1544 // take corrective action, if possible. The compiler generally 1545 // does not use the exact PerBytecodeTrapLimit value, but instead 1546 // changes its tactics if it sees any traps at all. This provides 1547 // a little hysteresis, delaying a recompile until a trap happens 1548 // several times. 1549 // 1550 // Actually, since there is only one bit of counter per BCI, 1551 // the possible per-BCI counts are {0,1,(per-method count)}. 1552 // This produces accurate results if in fact there is only 1553 // one hot trap site, but begins to get fuzzy if there are 1554 // many sites. For example, if there are ten sites each 1555 // trapping two or more times, they each get the blame for 1556 // all of their traps. 1557 make_not_entrant = true; 1558 } 1559 1560 // Detect repeated recompilation at the same BCI, and enforce a limit. 1561 if (make_not_entrant && maybe_prior_recompile) { 1562 // More than one recompile at this point. 1563 inc_recompile_count = maybe_prior_trap; 1564 } 1565 } else { 1566 // For reasons which are not recorded per-bytecode, we simply 1567 // force recompiles unconditionally. 1568 // (Note that PerMethodRecompilationCutoff is enforced elsewhere.) 1569 make_not_entrant = true; 1570 } 1571 1572 // Go back to the compiler if there are too many traps in this method. 1573 if (this_trap_count >= per_method_trap_limit(reason)) { 1574 // If there are too many traps in this method, force a recompile. 1575 // This will allow the compiler to see the limit overflow, and 1576 // take corrective action, if possible. 1577 // (This condition is an unlikely backstop only, because the 1578 // PerBytecodeTrapLimit is more likely to take effect first, 1579 // if it is applicable.) 1580 make_not_entrant = true; 1581 } 1582 1583 // Here's more hysteresis: If there has been a recompile at 1584 // this trap point already, run the method in the interpreter 1585 // for a while to exercise it more thoroughly. 1586 if (make_not_entrant && maybe_prior_recompile && maybe_prior_trap) { 1587 reprofile = true; 1588 } 1589 } 1590 1591 // Take requested actions on the method: 1592 1593 // Recompile 1594 if (make_not_entrant) { 1595 if (!nm->make_not_entrant()) { 1596 return; // the call did not change nmethod's state 1597 } 1598 1599 if (pdata != NULL) { 1600 // Record the recompilation event, if any. 1601 int tstate0 = pdata->trap_state(); 1602 int tstate1 = trap_state_set_recompiled(tstate0, true); 1603 if (tstate1 != tstate0) 1604 pdata->set_trap_state(tstate1); 1605 } 1606 1607 #if INCLUDE_RTM_OPT 1608 // Restart collecting RTM locking abort statistic if the method 1609 // is recompiled for a reason other than RTM state change. 1610 // Assume that in new recompiled code the statistic could be different, 1611 // for example, due to different inlining. 1612 if ((reason != Reason_rtm_state_change) && (trap_mdo != NULL) && 1613 UseRTMDeopt && (nm->rtm_state() != ProfileRTM)) { 1614 trap_mdo->atomic_set_rtm_state(ProfileRTM); 1615 } 1616 #endif 1617 // For code aging we count traps separately here, using make_not_entrant() 1618 // as a guard against simultaneous deopts in multiple threads. 1619 if (reason == Reason_tenured && trap_mdo != NULL) { 1620 trap_mdo->inc_tenure_traps(); 1621 } 1622 } 1623 1624 if (inc_recompile_count) { 1625 trap_mdo->inc_overflow_recompile_count(); 1626 if ((uint)trap_mdo->overflow_recompile_count() > 1627 (uint)PerBytecodeRecompilationCutoff) { 1628 // Give up on the method containing the bad BCI. 1629 if (trap_method() == nm->method()) { 1630 make_not_compilable = true; 1631 } else { 1632 trap_method->set_not_compilable(CompLevel_full_optimization, true, "overflow_recompile_count > PerBytecodeRecompilationCutoff"); 1633 // But give grace to the enclosing nm->method(). 1634 } 1635 } 1636 } 1637 1638 // Reprofile 1639 if (reprofile) { 1640 CompilationPolicy::policy()->reprofile(trap_scope, nm->is_osr_method()); 1641 } 1642 1643 // Give up compiling 1644 if (make_not_compilable && !nm->method()->is_not_compilable(CompLevel_full_optimization)) { 1645 assert(make_not_entrant, "consistent"); 1646 nm->method()->set_not_compilable(CompLevel_full_optimization); 1647 } 1648 1649 } // Free marked resources 1650 1651 } 1652 JRT_END 1653 1654 ProfileData* 1655 Deoptimization::query_update_method_data(MethodData* trap_mdo, 1656 int trap_bci, 1657 Deoptimization::DeoptReason reason, 1658 Method* compiled_method, 1659 //outputs: 1660 uint& ret_this_trap_count, 1661 bool& ret_maybe_prior_trap, 1662 bool& ret_maybe_prior_recompile) { 1663 uint prior_trap_count = trap_mdo->trap_count(reason); 1664 uint this_trap_count = trap_mdo->inc_trap_count(reason); 1665 1666 // If the runtime cannot find a place to store trap history, 1667 // it is estimated based on the general condition of the method. 1668 // If the method has ever been recompiled, or has ever incurred 1669 // a trap with the present reason , then this BCI is assumed 1670 // (pessimistically) to be the culprit. 1671 bool maybe_prior_trap = (prior_trap_count != 0); 1672 bool maybe_prior_recompile = (trap_mdo->decompile_count() != 0); 1673 ProfileData* pdata = NULL; 1674 1675 1676 // For reasons which are recorded per bytecode, we check per-BCI data. 1677 DeoptReason per_bc_reason = reason_recorded_per_bytecode_if_any(reason); 1678 if (per_bc_reason != Reason_none) { 1679 // Find the profile data for this BCI. If there isn't one, 1680 // try to allocate one from the MDO's set of spares. 1681 // This will let us detect a repeated trap at this point. 1682 pdata = trap_mdo->allocate_bci_to_data(trap_bci, reason_is_speculate(reason) ? compiled_method : NULL); 1683 1684 if (pdata != NULL) { 1685 if (reason_is_speculate(reason) && !pdata->is_SpeculativeTrapData()) { 1686 if (LogCompilation && xtty != NULL) { 1687 ttyLocker ttyl; 1688 // no more room for speculative traps in this MDO 1689 xtty->elem("speculative_traps_oom"); 1690 } 1691 } 1692 // Query the trap state of this profile datum. 1693 int tstate0 = pdata->trap_state(); 1694 if (!trap_state_has_reason(tstate0, per_bc_reason)) 1695 maybe_prior_trap = false; 1696 if (!trap_state_is_recompiled(tstate0)) 1697 maybe_prior_recompile = false; 1698 1699 // Update the trap state of this profile datum. 1700 int tstate1 = tstate0; 1701 // Record the reason. 1702 tstate1 = trap_state_add_reason(tstate1, per_bc_reason); 1703 // Store the updated state on the MDO, for next time. 1704 if (tstate1 != tstate0) 1705 pdata->set_trap_state(tstate1); 1706 } else { 1707 if (LogCompilation && xtty != NULL) { 1708 ttyLocker ttyl; 1709 // Missing MDP? Leave a small complaint in the log. 1710 xtty->elem("missing_mdp bci='%d'", trap_bci); 1711 } 1712 } 1713 } 1714 1715 // Return results: 1716 ret_this_trap_count = this_trap_count; 1717 ret_maybe_prior_trap = maybe_prior_trap; 1718 ret_maybe_prior_recompile = maybe_prior_recompile; 1719 return pdata; 1720 } 1721 1722 void 1723 Deoptimization::update_method_data_from_interpreter(MethodData* trap_mdo, int trap_bci, int reason) { 1724 ResourceMark rm; 1725 // Ignored outputs: 1726 uint ignore_this_trap_count; 1727 bool ignore_maybe_prior_trap; 1728 bool ignore_maybe_prior_recompile; 1729 assert(!reason_is_speculate(reason), "reason speculate only used by compiler"); 1730 query_update_method_data(trap_mdo, trap_bci, 1731 (DeoptReason)reason, 1732 NULL, 1733 ignore_this_trap_count, 1734 ignore_maybe_prior_trap, 1735 ignore_maybe_prior_recompile); 1736 } 1737 1738 Deoptimization::UnrollBlock* Deoptimization::uncommon_trap(JavaThread* thread, jint trap_request) { 1739 1740 // Still in Java no safepoints 1741 { 1742 // This enters VM and may safepoint 1743 uncommon_trap_inner(thread, trap_request); 1744 } 1745 return fetch_unroll_info_helper(thread); 1746 } 1747 1748 // Local derived constants. 1749 // Further breakdown of DataLayout::trap_state, as promised by DataLayout. 1750 const int DS_REASON_MASK = DataLayout::trap_mask >> 1; 1751 const int DS_RECOMPILE_BIT = DataLayout::trap_mask - DS_REASON_MASK; 1752 1753 //---------------------------trap_state_reason--------------------------------- 1754 Deoptimization::DeoptReason 1755 Deoptimization::trap_state_reason(int trap_state) { 1756 // This assert provides the link between the width of DataLayout::trap_bits 1757 // and the encoding of "recorded" reasons. It ensures there are enough 1758 // bits to store all needed reasons in the per-BCI MDO profile. 1759 assert(DS_REASON_MASK >= Reason_RECORDED_LIMIT, "enough bits"); 1760 int recompile_bit = (trap_state & DS_RECOMPILE_BIT); 1761 trap_state -= recompile_bit; 1762 if (trap_state == DS_REASON_MASK) { 1763 return Reason_many; 1764 } else { 1765 assert((int)Reason_none == 0, "state=0 => Reason_none"); 1766 return (DeoptReason)trap_state; 1767 } 1768 } 1769 //-------------------------trap_state_has_reason------------------------------- 1770 int Deoptimization::trap_state_has_reason(int trap_state, int reason) { 1771 assert(reason_is_recorded_per_bytecode((DeoptReason)reason), "valid reason"); 1772 assert(DS_REASON_MASK >= Reason_RECORDED_LIMIT, "enough bits"); 1773 int recompile_bit = (trap_state & DS_RECOMPILE_BIT); 1774 trap_state -= recompile_bit; 1775 if (trap_state == DS_REASON_MASK) { 1776 return -1; // true, unspecifically (bottom of state lattice) 1777 } else if (trap_state == reason) { 1778 return 1; // true, definitely 1779 } else if (trap_state == 0) { 1780 return 0; // false, definitely (top of state lattice) 1781 } else { 1782 return 0; // false, definitely 1783 } 1784 } 1785 //-------------------------trap_state_add_reason------------------------------- 1786 int Deoptimization::trap_state_add_reason(int trap_state, int reason) { 1787 assert(reason_is_recorded_per_bytecode((DeoptReason)reason) || reason == Reason_many, "valid reason"); 1788 int recompile_bit = (trap_state & DS_RECOMPILE_BIT); 1789 trap_state -= recompile_bit; 1790 if (trap_state == DS_REASON_MASK) { 1791 return trap_state + recompile_bit; // already at state lattice bottom 1792 } else if (trap_state == reason) { 1793 return trap_state + recompile_bit; // the condition is already true 1794 } else if (trap_state == 0) { 1795 return reason + recompile_bit; // no condition has yet been true 1796 } else { 1797 return DS_REASON_MASK + recompile_bit; // fall to state lattice bottom 1798 } 1799 } 1800 //-----------------------trap_state_is_recompiled------------------------------ 1801 bool Deoptimization::trap_state_is_recompiled(int trap_state) { 1802 return (trap_state & DS_RECOMPILE_BIT) != 0; 1803 } 1804 //-----------------------trap_state_set_recompiled----------------------------- 1805 int Deoptimization::trap_state_set_recompiled(int trap_state, bool z) { 1806 if (z) return trap_state | DS_RECOMPILE_BIT; 1807 else return trap_state & ~DS_RECOMPILE_BIT; 1808 } 1809 //---------------------------format_trap_state--------------------------------- 1810 // This is used for debugging and diagnostics, including LogFile output. 1811 const char* Deoptimization::format_trap_state(char* buf, size_t buflen, 1812 int trap_state) { 1813 DeoptReason reason = trap_state_reason(trap_state); 1814 bool recomp_flag = trap_state_is_recompiled(trap_state); 1815 // Re-encode the state from its decoded components. 1816 int decoded_state = 0; 1817 if (reason_is_recorded_per_bytecode(reason) || reason == Reason_many) 1818 decoded_state = trap_state_add_reason(decoded_state, reason); 1819 if (recomp_flag) 1820 decoded_state = trap_state_set_recompiled(decoded_state, recomp_flag); 1821 // If the state re-encodes properly, format it symbolically. 1822 // Because this routine is used for debugging and diagnostics, 1823 // be robust even if the state is a strange value. 1824 size_t len; 1825 if (decoded_state != trap_state) { 1826 // Random buggy state that doesn't decode?? 1827 len = jio_snprintf(buf, buflen, "#%d", trap_state); 1828 } else { 1829 len = jio_snprintf(buf, buflen, "%s%s", 1830 trap_reason_name(reason), 1831 recomp_flag ? " recompiled" : ""); 1832 } 1833 if (len >= buflen) 1834 buf[buflen-1] = '\0'; 1835 return buf; 1836 } 1837 1838 1839 //--------------------------------statics-------------------------------------- 1840 const char* Deoptimization::_trap_reason_name[] = { 1841 // Note: Keep this in sync. with enum DeoptReason. 1842 "none", 1843 "null_check", 1844 "null_assert", 1845 "range_check", 1846 "class_check", 1847 "array_check", 1848 "intrinsic", 1849 "bimorphic", 1850 "unloaded", 1851 "uninitialized", 1852 "unreached", 1853 "unhandled", 1854 "constraint", 1855 "div0_check", 1856 "age", 1857 "predicate", 1858 "loop_limit_check", 1859 "speculate_class_check", 1860 "speculate_null_check", 1861 "rtm_state_change", 1862 "unstable_if", 1863 "tenured" 1864 }; 1865 const char* Deoptimization::_trap_action_name[] = { 1866 // Note: Keep this in sync. with enum DeoptAction. 1867 "none", 1868 "maybe_recompile", 1869 "reinterpret", 1870 "make_not_entrant", 1871 "make_not_compilable" 1872 }; 1873 1874 const char* Deoptimization::trap_reason_name(int reason) { 1875 // Check that every reason has a name 1876 STATIC_ASSERT(sizeof(_trap_reason_name)/sizeof(const char*) == Reason_LIMIT); 1877 1878 if (reason == Reason_many) return "many"; 1879 if ((uint)reason < Reason_LIMIT) 1880 return _trap_reason_name[reason]; 1881 static char buf[20]; 1882 sprintf(buf, "reason%d", reason); 1883 return buf; 1884 } 1885 const char* Deoptimization::trap_action_name(int action) { 1886 // Check that every action has a name 1887 STATIC_ASSERT(sizeof(_trap_action_name)/sizeof(const char*) == Action_LIMIT); 1888 1889 if ((uint)action < Action_LIMIT) 1890 return _trap_action_name[action]; 1891 static char buf[20]; 1892 sprintf(buf, "action%d", action); 1893 return buf; 1894 } 1895 1896 // This is used for debugging and diagnostics, including LogFile output. 1897 const char* Deoptimization::format_trap_request(char* buf, size_t buflen, 1898 int trap_request) { 1899 jint unloaded_class_index = trap_request_index(trap_request); 1900 const char* reason = trap_reason_name(trap_request_reason(trap_request)); 1901 const char* action = trap_action_name(trap_request_action(trap_request)); 1902 size_t len; 1903 if (unloaded_class_index < 0) { 1904 len = jio_snprintf(buf, buflen, "reason='%s' action='%s'", 1905 reason, action); 1906 } else { 1907 len = jio_snprintf(buf, buflen, "reason='%s' action='%s' index='%d'", 1908 reason, action, unloaded_class_index); 1909 } 1910 if (len >= buflen) 1911 buf[buflen-1] = '\0'; 1912 return buf; 1913 } 1914 1915 juint Deoptimization::_deoptimization_hist 1916 [Deoptimization::Reason_LIMIT] 1917 [1 + Deoptimization::Action_LIMIT] 1918 [Deoptimization::BC_CASE_LIMIT] 1919 = {0}; 1920 1921 enum { 1922 LSB_BITS = 8, 1923 LSB_MASK = right_n_bits(LSB_BITS) 1924 }; 1925 1926 void Deoptimization::gather_statistics(DeoptReason reason, DeoptAction action, 1927 Bytecodes::Code bc) { 1928 assert(reason >= 0 && reason < Reason_LIMIT, "oob"); 1929 assert(action >= 0 && action < Action_LIMIT, "oob"); 1930 _deoptimization_hist[Reason_none][0][0] += 1; // total 1931 _deoptimization_hist[reason][0][0] += 1; // per-reason total 1932 juint* cases = _deoptimization_hist[reason][1+action]; 1933 juint* bc_counter_addr = NULL; 1934 juint bc_counter = 0; 1935 // Look for an unused counter, or an exact match to this BC. 1936 if (bc != Bytecodes::_illegal) { 1937 for (int bc_case = 0; bc_case < BC_CASE_LIMIT; bc_case++) { 1938 juint* counter_addr = &cases[bc_case]; 1939 juint counter = *counter_addr; 1940 if ((counter == 0 && bc_counter_addr == NULL) 1941 || (Bytecodes::Code)(counter & LSB_MASK) == bc) { 1942 // this counter is either free or is already devoted to this BC 1943 bc_counter_addr = counter_addr; 1944 bc_counter = counter | bc; 1945 } 1946 } 1947 } 1948 if (bc_counter_addr == NULL) { 1949 // Overflow, or no given bytecode. 1950 bc_counter_addr = &cases[BC_CASE_LIMIT-1]; 1951 bc_counter = (*bc_counter_addr & ~LSB_MASK); // clear LSB 1952 } 1953 *bc_counter_addr = bc_counter + (1 << LSB_BITS); 1954 } 1955 1956 jint Deoptimization::total_deoptimization_count() { 1957 return _deoptimization_hist[Reason_none][0][0]; 1958 } 1959 1960 jint Deoptimization::deoptimization_count(DeoptReason reason) { 1961 assert(reason >= 0 && reason < Reason_LIMIT, "oob"); 1962 return _deoptimization_hist[reason][0][0]; 1963 } 1964 1965 void Deoptimization::print_statistics() { 1966 juint total = total_deoptimization_count(); 1967 juint account = total; 1968 if (total != 0) { 1969 ttyLocker ttyl; 1970 if (xtty != NULL) xtty->head("statistics type='deoptimization'"); 1971 tty->print_cr("Deoptimization traps recorded:"); 1972 #define PRINT_STAT_LINE(name, r) \ 1973 tty->print_cr(" %4d (%4.1f%%) %s", (int)(r), ((r) * 100.0) / total, name); 1974 PRINT_STAT_LINE("total", total); 1975 // For each non-zero entry in the histogram, print the reason, 1976 // the action, and (if specifically known) the type of bytecode. 1977 for (int reason = 0; reason < Reason_LIMIT; reason++) { 1978 for (int action = 0; action < Action_LIMIT; action++) { 1979 juint* cases = _deoptimization_hist[reason][1+action]; 1980 for (int bc_case = 0; bc_case < BC_CASE_LIMIT; bc_case++) { 1981 juint counter = cases[bc_case]; 1982 if (counter != 0) { 1983 char name[1*K]; 1984 Bytecodes::Code bc = (Bytecodes::Code)(counter & LSB_MASK); 1985 if (bc_case == BC_CASE_LIMIT && (int)bc == 0) 1986 bc = Bytecodes::_illegal; 1987 sprintf(name, "%s/%s/%s", 1988 trap_reason_name(reason), 1989 trap_action_name(action), 1990 Bytecodes::is_defined(bc)? Bytecodes::name(bc): "other"); 1991 juint r = counter >> LSB_BITS; 1992 tty->print_cr(" %40s: " UINT32_FORMAT " (%.1f%%)", name, r, (r * 100.0) / total); 1993 account -= r; 1994 } 1995 } 1996 } 1997 } 1998 if (account != 0) { 1999 PRINT_STAT_LINE("unaccounted", account); 2000 } 2001 #undef PRINT_STAT_LINE 2002 if (xtty != NULL) xtty->tail("statistics"); 2003 } 2004 } 2005 #else // COMPILER2 || SHARK 2006 2007 2008 // Stubs for C1 only system. 2009 bool Deoptimization::trap_state_is_recompiled(int trap_state) { 2010 return false; 2011 } 2012 2013 const char* Deoptimization::trap_reason_name(int reason) { 2014 return "unknown"; 2015 } 2016 2017 void Deoptimization::print_statistics() { 2018 // no output 2019 } 2020 2021 void 2022 Deoptimization::update_method_data_from_interpreter(MethodData* trap_mdo, int trap_bci, int reason) { 2023 // no udpate 2024 } 2025 2026 int Deoptimization::trap_state_has_reason(int trap_state, int reason) { 2027 return 0; 2028 } 2029 2030 void Deoptimization::gather_statistics(DeoptReason reason, DeoptAction action, 2031 Bytecodes::Code bc) { 2032 // no update 2033 } 2034 2035 const char* Deoptimization::format_trap_state(char* buf, size_t buflen, 2036 int trap_state) { 2037 jio_snprintf(buf, buflen, "#%d", trap_state); 2038 return buf; 2039 } 2040 2041 #endif // COMPILER2 || SHARK