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