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