1 /*
2 * Copyright (c) 1997, 2024, 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/javaClasses.inline.hpp"
27 #include "classfile/symbolTable.hpp"
28 #include "classfile/systemDictionary.hpp"
29 #include "classfile/vmClasses.hpp"
30 #include "code/codeCache.hpp"
31 #include "code/debugInfoRec.hpp"
32 #include "code/nmethod.hpp"
33 #include "code/pcDesc.hpp"
34 #include "code/scopeDesc.hpp"
35 #include "compiler/compilationPolicy.hpp"
36 #include "compiler/compilerDefinitions.inline.hpp"
37 #include "gc/shared/collectedHeap.hpp"
38 #include "interpreter/bytecode.hpp"
39 #include "interpreter/interpreter.hpp"
40 #include "interpreter/oopMapCache.hpp"
41 #include "jvm.h"
42 #include "logging/log.hpp"
43 #include "logging/logLevel.hpp"
44 #include "logging/logMessage.hpp"
45 #include "logging/logStream.hpp"
46 #include "memory/allocation.inline.hpp"
47 #include "memory/oopFactory.hpp"
48 #include "memory/resourceArea.hpp"
49 #include "memory/universe.hpp"
50 #include "oops/constantPool.hpp"
51 #include "oops/fieldStreams.inline.hpp"
52 #include "oops/method.hpp"
53 #include "oops/objArrayKlass.hpp"
54 #include "oops/objArrayOop.inline.hpp"
55 #include "oops/oop.inline.hpp"
56 #include "oops/typeArrayOop.inline.hpp"
57 #include "oops/verifyOopClosure.hpp"
58 #include "prims/jvmtiDeferredUpdates.hpp"
59 #include "prims/jvmtiExport.hpp"
60 #include "prims/jvmtiThreadState.hpp"
61 #include "prims/methodHandles.hpp"
62 #include "prims/vectorSupport.hpp"
63 #include "runtime/atomic.hpp"
64 #include "runtime/continuation.hpp"
65 #include "runtime/continuationEntry.inline.hpp"
66 #include "runtime/deoptimization.hpp"
67 #include "runtime/escapeBarrier.hpp"
68 #include "runtime/fieldDescriptor.hpp"
69 #include "runtime/fieldDescriptor.inline.hpp"
70 #include "runtime/frame.inline.hpp"
71 #include "runtime/handles.inline.hpp"
72 #include "runtime/interfaceSupport.inline.hpp"
73 #include "runtime/javaThread.hpp"
74 #include "runtime/jniHandles.inline.hpp"
75 #include "runtime/keepStackGCProcessed.hpp"
76 #include "runtime/objectMonitor.inline.hpp"
77 #include "runtime/osThread.hpp"
78 #include "runtime/safepointVerifiers.hpp"
79 #include "runtime/sharedRuntime.hpp"
80 #include "runtime/signature.hpp"
81 #include "runtime/stackFrameStream.inline.hpp"
82 #include "runtime/stackValue.hpp"
83 #include "runtime/stackWatermarkSet.hpp"
84 #include "runtime/stubRoutines.hpp"
85 #include "runtime/synchronizer.hpp"
86 #include "runtime/threadSMR.hpp"
87 #include "runtime/threadWXSetters.inline.hpp"
88 #include "runtime/vframe.hpp"
89 #include "runtime/vframeArray.hpp"
90 #include "runtime/vframe_hp.hpp"
91 #include "runtime/vmOperations.hpp"
92 #include "utilities/events.hpp"
93 #include "utilities/growableArray.hpp"
94 #include "utilities/macros.hpp"
95 #include "utilities/preserveException.hpp"
96 #include "utilities/xmlstream.hpp"
97 #if INCLUDE_JFR
98 #include "jfr/jfrEvents.hpp"
99 #include "jfr/metadata/jfrSerializer.hpp"
100 #endif
101
102 uint64_t DeoptimizationScope::_committed_deopt_gen = 0;
103 uint64_t DeoptimizationScope::_active_deopt_gen = 1;
104 bool DeoptimizationScope::_committing_in_progress = false;
105
106 DeoptimizationScope::DeoptimizationScope() : _required_gen(0) {
107 DEBUG_ONLY(_deopted = false;)
108
109 MutexLocker ml(CompiledMethod_lock, Mutex::_no_safepoint_check_flag);
110 // If there is nothing to deopt _required_gen is the same as comitted.
111 _required_gen = DeoptimizationScope::_committed_deopt_gen;
112 }
113
114 DeoptimizationScope::~DeoptimizationScope() {
115 assert(_deopted, "Deopt not executed");
116 }
117
118 void DeoptimizationScope::mark(CompiledMethod* cm, bool inc_recompile_counts) {
119 MutexLocker ml(CompiledMethod_lock->owned_by_self() ? nullptr : CompiledMethod_lock,
120 Mutex::_no_safepoint_check_flag);
121
122 // If it's already marked but we still need it to be deopted.
123 if (cm->is_marked_for_deoptimization()) {
124 dependent(cm);
125 return;
126 }
127
128 CompiledMethod::DeoptimizationStatus status =
129 inc_recompile_counts ? CompiledMethod::deoptimize : CompiledMethod::deoptimize_noupdate;
130 Atomic::store(&cm->_deoptimization_status, status);
131
132 // Make sure active is not committed
133 assert(DeoptimizationScope::_committed_deopt_gen < DeoptimizationScope::_active_deopt_gen, "Must be");
134 assert(cm->_deoptimization_generation == 0, "Is already marked");
135
136 cm->_deoptimization_generation = DeoptimizationScope::_active_deopt_gen;
137 _required_gen = DeoptimizationScope::_active_deopt_gen;
138 }
139
140 void DeoptimizationScope::dependent(CompiledMethod* cm) {
141 MutexLocker ml(CompiledMethod_lock->owned_by_self() ? nullptr : CompiledMethod_lock,
142 Mutex::_no_safepoint_check_flag);
143 // A method marked by someone else may have a _required_gen lower than what we marked with.
144 // Therefore only store it if it's higher than _required_gen.
145 if (_required_gen < cm->_deoptimization_generation) {
146 _required_gen = cm->_deoptimization_generation;
147 }
148 }
149
150 void DeoptimizationScope::deoptimize_marked() {
151 assert(!_deopted, "Already deopted");
152
153 // We are not alive yet.
154 if (!Universe::is_fully_initialized()) {
155 DEBUG_ONLY(_deopted = true;)
156 return;
157 }
158
159 // Safepoints are a special case, handled here.
160 if (SafepointSynchronize::is_at_safepoint()) {
161 DeoptimizationScope::_committed_deopt_gen = DeoptimizationScope::_active_deopt_gen;
162 DeoptimizationScope::_active_deopt_gen++;
163 Deoptimization::deoptimize_all_marked();
164 DEBUG_ONLY(_deopted = true;)
165 return;
166 }
167
168 uint64_t comitting = 0;
169 bool wait = false;
170 while (true) {
171 {
172 MutexLocker ml(CompiledMethod_lock->owned_by_self() ? nullptr : CompiledMethod_lock,
173 Mutex::_no_safepoint_check_flag);
174 // First we check if we or someone else already deopted the gen we want.
175 if (DeoptimizationScope::_committed_deopt_gen >= _required_gen) {
176 DEBUG_ONLY(_deopted = true;)
177 return;
178 }
179 if (!_committing_in_progress) {
180 // The version we are about to commit.
181 comitting = DeoptimizationScope::_active_deopt_gen;
182 // Make sure new marks use a higher gen.
183 DeoptimizationScope::_active_deopt_gen++;
184 _committing_in_progress = true;
185 wait = false;
186 } else {
187 // Another thread is handshaking and committing a gen.
188 wait = true;
189 }
190 }
191 if (wait) {
192 // Wait and let the concurrent handshake be performed.
193 ThreadBlockInVM tbivm(JavaThread::current());
194 os::naked_yield();
195 } else {
196 // Performs the handshake.
197 Deoptimization::deoptimize_all_marked(); // May safepoint and an additional deopt may have occurred.
198 DEBUG_ONLY(_deopted = true;)
199 {
200 MutexLocker ml(CompiledMethod_lock->owned_by_self() ? nullptr : CompiledMethod_lock,
201 Mutex::_no_safepoint_check_flag);
202 // Make sure that committed doesn't go backwards.
203 // Should only happen if we did a deopt during a safepoint above.
204 if (DeoptimizationScope::_committed_deopt_gen < comitting) {
205 DeoptimizationScope::_committed_deopt_gen = comitting;
206 }
207 _committing_in_progress = false;
208
209 assert(DeoptimizationScope::_committed_deopt_gen >= _required_gen, "Must be");
210
211 return;
212 }
213 }
214 }
215 }
216
217 Deoptimization::UnrollBlock::UnrollBlock(int size_of_deoptimized_frame,
218 int caller_adjustment,
219 int caller_actual_parameters,
220 int number_of_frames,
221 intptr_t* frame_sizes,
222 address* frame_pcs,
223 BasicType return_type,
224 int exec_mode) {
225 _size_of_deoptimized_frame = size_of_deoptimized_frame;
226 _caller_adjustment = caller_adjustment;
227 _caller_actual_parameters = caller_actual_parameters;
228 _number_of_frames = number_of_frames;
229 _frame_sizes = frame_sizes;
230 _frame_pcs = frame_pcs;
231 _register_block = NEW_C_HEAP_ARRAY(intptr_t, RegisterMap::reg_count * 2, mtCompiler);
232 _return_type = return_type;
233 _initial_info = 0;
234 // PD (x86 only)
235 _counter_temp = 0;
236 _unpack_kind = exec_mode;
237 _sender_sp_temp = 0;
238
239 _total_frame_sizes = size_of_frames();
240 assert(exec_mode >= 0 && exec_mode < Unpack_LIMIT, "Unexpected exec_mode");
241 }
242
243 Deoptimization::UnrollBlock::~UnrollBlock() {
244 FREE_C_HEAP_ARRAY(intptr_t, _frame_sizes);
245 FREE_C_HEAP_ARRAY(intptr_t, _frame_pcs);
246 FREE_C_HEAP_ARRAY(intptr_t, _register_block);
247 }
248
249 int Deoptimization::UnrollBlock::size_of_frames() const {
250 // Account first for the adjustment of the initial frame
251 int result = _caller_adjustment;
252 for (int index = 0; index < number_of_frames(); index++) {
253 result += frame_sizes()[index];
254 }
255 return result;
256 }
257
258 void Deoptimization::UnrollBlock::print() {
259 ResourceMark rm;
260 stringStream st;
261 st.print_cr("UnrollBlock");
262 st.print_cr(" size_of_deoptimized_frame = %d", _size_of_deoptimized_frame);
263 st.print( " frame_sizes: ");
264 for (int index = 0; index < number_of_frames(); index++) {
265 st.print(INTX_FORMAT " ", frame_sizes()[index]);
266 }
267 st.cr();
268 tty->print_raw(st.freeze());
269 }
270
271 // In order to make fetch_unroll_info work properly with escape
272 // analysis, the method was changed from JRT_LEAF to JRT_BLOCK_ENTRY.
273 // The actual reallocation of previously eliminated objects occurs in realloc_objects,
274 // which is called from the method fetch_unroll_info_helper below.
275 JRT_BLOCK_ENTRY(Deoptimization::UnrollBlock*, Deoptimization::fetch_unroll_info(JavaThread* current, int exec_mode))
276 // fetch_unroll_info() is called at the beginning of the deoptimization
277 // handler. Note this fact before we start generating temporary frames
278 // that can confuse an asynchronous stack walker. This counter is
279 // decremented at the end of unpack_frames().
280 current->inc_in_deopt_handler();
281
282 if (exec_mode == Unpack_exception) {
283 // When we get here, a callee has thrown an exception into a deoptimized
284 // frame. That throw might have deferred stack watermark checking until
285 // after unwinding. So we deal with such deferred requests here.
286 StackWatermarkSet::after_unwind(current);
287 }
288
289 return fetch_unroll_info_helper(current, exec_mode);
290 JRT_END
291
292 #if COMPILER2_OR_JVMCI
293 // print information about reallocated objects
294 static void print_objects(JavaThread* deoptee_thread,
295 GrowableArray<ScopeValue*>* objects, bool realloc_failures) {
296 ResourceMark rm;
297 stringStream st; // change to logStream with logging
298 st.print_cr("REALLOC OBJECTS in thread " INTPTR_FORMAT, p2i(deoptee_thread));
299 fieldDescriptor fd;
300
301 for (int i = 0; i < objects->length(); i++) {
302 ObjectValue* sv = (ObjectValue*) objects->at(i);
303 Klass* k = java_lang_Class::as_Klass(sv->klass()->as_ConstantOopReadValue()->value()());
304 Handle obj = sv->value();
305
306 st.print(" object <" INTPTR_FORMAT "> of type ", p2i(sv->value()()));
307 k->print_value_on(&st);
308 assert(obj.not_null() || realloc_failures, "reallocation was missed");
309 if (obj.is_null()) {
310 st.print(" allocation failed");
311 } else {
312 st.print(" allocated (" SIZE_FORMAT " bytes)", obj->size() * HeapWordSize);
313 }
314 st.cr();
315
316 if (Verbose && !obj.is_null()) {
317 k->oop_print_on(obj(), &st);
318 }
319 }
320 tty->print_raw(st.freeze());
321 }
322
323 static bool rematerialize_objects(JavaThread* thread, int exec_mode, CompiledMethod* compiled_method,
324 frame& deoptee, RegisterMap& map, GrowableArray<compiledVFrame*>* chunk,
325 bool& deoptimized_objects) {
326 bool realloc_failures = false;
327 assert (chunk->at(0)->scope() != nullptr,"expect only compiled java frames");
328
329 JavaThread* deoptee_thread = chunk->at(0)->thread();
330 assert(exec_mode == Deoptimization::Unpack_none || (deoptee_thread == thread),
331 "a frame can only be deoptimized by the owner thread");
332
333 GrowableArray<ScopeValue*>* objects = chunk->at(0)->scope()->objects();
334
335 // The flag return_oop() indicates call sites which return oop
336 // in compiled code. Such sites include java method calls,
337 // runtime calls (for example, used to allocate new objects/arrays
338 // on slow code path) and any other calls generated in compiled code.
339 // It is not guaranteed that we can get such information here only
340 // by analyzing bytecode in deoptimized frames. This is why this flag
341 // is set during method compilation (see Compile::Process_OopMap_Node()).
342 // If the previous frame was popped or if we are dispatching an exception,
343 // we don't have an oop result.
344 bool save_oop_result = chunk->at(0)->scope()->return_oop() && !thread->popframe_forcing_deopt_reexecution() && (exec_mode == Deoptimization::Unpack_deopt);
345 Handle return_value;
346 if (save_oop_result) {
347 // Reallocation may trigger GC. If deoptimization happened on return from
348 // call which returns oop we need to save it since it is not in oopmap.
349 oop result = deoptee.saved_oop_result(&map);
350 assert(oopDesc::is_oop_or_null(result), "must be oop");
351 return_value = Handle(thread, result);
352 assert(Universe::heap()->is_in_or_null(result), "must be heap pointer");
353 if (TraceDeoptimization) {
354 tty->print_cr("SAVED OOP RESULT " INTPTR_FORMAT " in thread " INTPTR_FORMAT, p2i(result), p2i(thread));
355 tty->cr();
356 }
357 }
358 if (objects != nullptr) {
359 if (exec_mode == Deoptimization::Unpack_none) {
360 assert(thread->thread_state() == _thread_in_vm, "assumption");
361 JavaThread* THREAD = thread; // For exception macros.
362 // Clear pending OOM if reallocation fails and return true indicating allocation failure
363 realloc_failures = Deoptimization::realloc_objects(thread, &deoptee, &map, objects, CHECK_AND_CLEAR_(true));
364 deoptimized_objects = true;
365 } else {
366 JavaThread* current = thread; // For JRT_BLOCK
367 JRT_BLOCK
368 realloc_failures = Deoptimization::realloc_objects(thread, &deoptee, &map, objects, THREAD);
369 JRT_END
370 }
371 bool skip_internal = (compiled_method != nullptr) && !compiled_method->is_compiled_by_jvmci();
372 Deoptimization::reassign_fields(&deoptee, &map, objects, realloc_failures, skip_internal);
373 if (TraceDeoptimization) {
374 print_objects(deoptee_thread, objects, realloc_failures);
375 }
376 }
377 if (save_oop_result) {
378 // Restore result.
379 deoptee.set_saved_oop_result(&map, return_value());
380 }
381 return realloc_failures;
382 }
383
384 static void restore_eliminated_locks(JavaThread* thread, GrowableArray<compiledVFrame*>* chunk, bool realloc_failures,
385 frame& deoptee, int exec_mode, bool& deoptimized_objects) {
386 JavaThread* deoptee_thread = chunk->at(0)->thread();
387 assert(!EscapeBarrier::objs_are_deoptimized(deoptee_thread, deoptee.id()), "must relock just once");
388 assert(thread == Thread::current(), "should be");
389 HandleMark hm(thread);
390 #ifndef PRODUCT
391 bool first = true;
392 #endif // !PRODUCT
393 DEBUG_ONLY(GrowableArray<oop> lock_order{0};)
394 // Start locking from outermost/oldest frame
395 for (int i = (chunk->length() - 1); i >= 0; i--) {
396 compiledVFrame* cvf = chunk->at(i);
397 assert (cvf->scope() != nullptr,"expect only compiled java frames");
398 GrowableArray<MonitorInfo*>* monitors = cvf->monitors();
399 if (monitors->is_nonempty()) {
400 bool relocked = Deoptimization::relock_objects(thread, monitors, deoptee_thread, deoptee,
401 exec_mode, realloc_failures);
402 deoptimized_objects = deoptimized_objects || relocked;
403 #ifdef ASSERT
404 if (LockingMode == LM_LIGHTWEIGHT && !realloc_failures) {
405 for (MonitorInfo* mi : *monitors) {
406 lock_order.push(mi->owner());
407 }
408 }
409 #endif // ASSERT
410 #ifndef PRODUCT
411 if (PrintDeoptimizationDetails) {
412 ResourceMark rm;
413 stringStream st;
414 for (int j = 0; j < monitors->length(); j++) {
415 MonitorInfo* mi = monitors->at(j);
416 if (mi->eliminated()) {
417 if (first) {
418 first = false;
419 st.print_cr("RELOCK OBJECTS in thread " INTPTR_FORMAT, p2i(thread));
420 }
421 if (exec_mode == Deoptimization::Unpack_none) {
422 ObjectMonitor* monitor = deoptee_thread->current_waiting_monitor();
423 if (monitor != nullptr && monitor->object() == mi->owner()) {
424 st.print_cr(" object <" INTPTR_FORMAT "> DEFERRED relocking after wait", p2i(mi->owner()));
425 continue;
426 }
427 }
428 if (mi->owner_is_scalar_replaced()) {
429 Klass* k = java_lang_Class::as_Klass(mi->owner_klass());
430 st.print_cr(" failed reallocation for klass %s", k->external_name());
431 } else {
432 st.print_cr(" object <" INTPTR_FORMAT "> locked", p2i(mi->owner()));
433 }
434 }
435 }
436 tty->print_raw(st.freeze());
437 }
438 #endif // !PRODUCT
439 }
440 }
441 #ifdef ASSERT
442 if (LockingMode == LM_LIGHTWEIGHT && !realloc_failures) {
443 deoptee_thread->lock_stack().verify_consistent_lock_order(lock_order, exec_mode != Deoptimization::Unpack_none);
444 }
445 #endif // ASSERT
446 }
447
448 // Deoptimize objects, that is reallocate and relock them, just before they escape through JVMTI.
449 // The given vframes cover one physical frame.
450 bool Deoptimization::deoptimize_objects_internal(JavaThread* thread, GrowableArray<compiledVFrame*>* chunk,
451 bool& realloc_failures) {
452 frame deoptee = chunk->at(0)->fr();
453 JavaThread* deoptee_thread = chunk->at(0)->thread();
454 CompiledMethod* cm = deoptee.cb()->as_compiled_method_or_null();
455 RegisterMap map(chunk->at(0)->register_map());
456 bool deoptimized_objects = false;
457
458 bool const jvmci_enabled = JVMCI_ONLY(UseJVMCICompiler) NOT_JVMCI(false);
459
460 // Reallocate the non-escaping objects and restore their fields.
461 if (jvmci_enabled COMPILER2_PRESENT(|| (DoEscapeAnalysis && EliminateAllocations)
462 || EliminateAutoBox || EnableVectorAggressiveReboxing)) {
463 realloc_failures = rematerialize_objects(thread, Unpack_none, cm, deoptee, map, chunk, deoptimized_objects);
464 }
465
466 // MonitorInfo structures used in eliminate_locks are not GC safe.
467 NoSafepointVerifier no_safepoint;
468
469 // Now relock objects if synchronization on them was eliminated.
470 if (jvmci_enabled COMPILER2_PRESENT(|| ((DoEscapeAnalysis || EliminateNestedLocks) && EliminateLocks))) {
471 restore_eliminated_locks(thread, chunk, realloc_failures, deoptee, Unpack_none, deoptimized_objects);
472 }
473 return deoptimized_objects;
474 }
475 #endif // COMPILER2_OR_JVMCI
476
477 // This is factored, since it is both called from a JRT_LEAF (deoptimization) and a JRT_ENTRY (uncommon_trap)
478 Deoptimization::UnrollBlock* Deoptimization::fetch_unroll_info_helper(JavaThread* current, int exec_mode) {
479 // When we get here we are about to unwind the deoptee frame. In order to
480 // catch not yet safe to use frames, the following stack watermark barrier
481 // poll will make such frames safe to use.
482 StackWatermarkSet::before_unwind(current);
483
484 // Note: there is a safepoint safety issue here. No matter whether we enter
485 // via vanilla deopt or uncommon trap we MUST NOT stop at a safepoint once
486 // the vframeArray is created.
487 //
488
489 // Allocate our special deoptimization ResourceMark
490 DeoptResourceMark* dmark = new DeoptResourceMark(current);
491 assert(current->deopt_mark() == nullptr, "Pending deopt!");
492 current->set_deopt_mark(dmark);
493
494 frame stub_frame = current->last_frame(); // Makes stack walkable as side effect
495 RegisterMap map(current,
496 RegisterMap::UpdateMap::include,
497 RegisterMap::ProcessFrames::include,
498 RegisterMap::WalkContinuation::skip);
499 RegisterMap dummy_map(current,
500 RegisterMap::UpdateMap::skip,
501 RegisterMap::ProcessFrames::include,
502 RegisterMap::WalkContinuation::skip);
503 // Now get the deoptee with a valid map
504 frame deoptee = stub_frame.sender(&map);
505 // Set the deoptee nmethod
506 assert(current->deopt_compiled_method() == nullptr, "Pending deopt!");
507 CompiledMethod* cm = deoptee.cb()->as_compiled_method_or_null();
508 current->set_deopt_compiled_method(cm);
509
510 if (VerifyStack) {
511 current->validate_frame_layout();
512 }
513
514 // Create a growable array of VFrames where each VFrame represents an inlined
515 // Java frame. This storage is allocated with the usual system arena.
516 assert(deoptee.is_compiled_frame(), "Wrong frame type");
517 GrowableArray<compiledVFrame*>* chunk = new GrowableArray<compiledVFrame*>(10);
518 vframe* vf = vframe::new_vframe(&deoptee, &map, current);
519 while (!vf->is_top()) {
520 assert(vf->is_compiled_frame(), "Wrong frame type");
521 chunk->push(compiledVFrame::cast(vf));
522 vf = vf->sender();
523 }
524 assert(vf->is_compiled_frame(), "Wrong frame type");
525 chunk->push(compiledVFrame::cast(vf));
526
527 bool realloc_failures = false;
528
529 #if COMPILER2_OR_JVMCI
530 bool const jvmci_enabled = JVMCI_ONLY(EnableJVMCI) NOT_JVMCI(false);
531
532 // Reallocate the non-escaping objects and restore their fields. Then
533 // relock objects if synchronization on them was eliminated.
534 if (jvmci_enabled COMPILER2_PRESENT( || (DoEscapeAnalysis && EliminateAllocations)
535 || EliminateAutoBox || EnableVectorAggressiveReboxing )) {
536 bool unused;
537 realloc_failures = rematerialize_objects(current, exec_mode, cm, deoptee, map, chunk, unused);
538 }
539 #endif // COMPILER2_OR_JVMCI
540
541 // Ensure that no safepoint is taken after pointers have been stored
542 // in fields of rematerialized objects. If a safepoint occurs from here on
543 // out the java state residing in the vframeArray will be missed.
544 // Locks may be rebaised in a safepoint.
545 NoSafepointVerifier no_safepoint;
546
547 #if COMPILER2_OR_JVMCI
548 if ((jvmci_enabled COMPILER2_PRESENT( || ((DoEscapeAnalysis || EliminateNestedLocks) && EliminateLocks) ))
549 && !EscapeBarrier::objs_are_deoptimized(current, deoptee.id())) {
550 bool unused = false;
551 restore_eliminated_locks(current, chunk, realloc_failures, deoptee, exec_mode, unused);
552 }
553 #endif // COMPILER2_OR_JVMCI
554
555 ScopeDesc* trap_scope = chunk->at(0)->scope();
556 Handle exceptionObject;
557 if (trap_scope->rethrow_exception()) {
558 #ifndef PRODUCT
559 if (PrintDeoptimizationDetails) {
560 tty->print_cr("Exception to be rethrown in the interpreter for method %s::%s at bci %d", trap_scope->method()->method_holder()->name()->as_C_string(), trap_scope->method()->name()->as_C_string(), trap_scope->bci());
561 }
562 #endif // !PRODUCT
563
564 GrowableArray<ScopeValue*>* expressions = trap_scope->expressions();
565 guarantee(expressions != nullptr && expressions->length() > 0, "must have exception to throw");
566 ScopeValue* topOfStack = expressions->top();
567 exceptionObject = StackValue::create_stack_value(&deoptee, &map, topOfStack)->get_obj();
568 guarantee(exceptionObject() != nullptr, "exception oop can not be null");
569 }
570
571 vframeArray* array = create_vframeArray(current, deoptee, &map, chunk, realloc_failures);
572 #if COMPILER2_OR_JVMCI
573 if (realloc_failures) {
574 // This destroys all ScopedValue bindings.
575 current->clear_scopedValueBindings();
576 pop_frames_failed_reallocs(current, array);
577 }
578 #endif
579
580 assert(current->vframe_array_head() == nullptr, "Pending deopt!");
581 current->set_vframe_array_head(array);
582
583 // Now that the vframeArray has been created if we have any deferred local writes
584 // added by jvmti then we can free up that structure as the data is now in the
585 // vframeArray
586
587 JvmtiDeferredUpdates::delete_updates_for_frame(current, array->original().id());
588
589 // Compute the caller frame based on the sender sp of stub_frame and stored frame sizes info.
590 CodeBlob* cb = stub_frame.cb();
591 // Verify we have the right vframeArray
592 assert(cb->frame_size() >= 0, "Unexpected frame size");
593 intptr_t* unpack_sp = stub_frame.sp() + cb->frame_size();
594
595 // If the deopt call site is a MethodHandle invoke call site we have
596 // to adjust the unpack_sp.
597 nmethod* deoptee_nm = deoptee.cb()->as_nmethod_or_null();
598 if (deoptee_nm != nullptr && deoptee_nm->is_method_handle_return(deoptee.pc()))
599 unpack_sp = deoptee.unextended_sp();
600
601 #ifdef ASSERT
602 assert(cb->is_deoptimization_stub() ||
603 cb->is_uncommon_trap_stub() ||
604 strcmp("Stub<DeoptimizationStub.deoptimizationHandler>", cb->name()) == 0 ||
605 strcmp("Stub<UncommonTrapStub.uncommonTrapHandler>", cb->name()) == 0,
606 "unexpected code blob: %s", cb->name());
607 #endif
608
609 // This is a guarantee instead of an assert because if vframe doesn't match
610 // we will unpack the wrong deoptimized frame and wind up in strange places
611 // where it will be very difficult to figure out what went wrong. Better
612 // to die an early death here than some very obscure death later when the
613 // trail is cold.
614 // Note: on ia64 this guarantee can be fooled by frames with no memory stack
615 // in that it will fail to detect a problem when there is one. This needs
616 // more work in tiger timeframe.
617 guarantee(array->unextended_sp() == unpack_sp, "vframe_array_head must contain the vframeArray to unpack");
618
619 int number_of_frames = array->frames();
620
621 // Compute the vframes' sizes. Note that frame_sizes[] entries are ordered from outermost to innermost
622 // virtual activation, which is the reverse of the elements in the vframes array.
623 intptr_t* frame_sizes = NEW_C_HEAP_ARRAY(intptr_t, number_of_frames, mtCompiler);
624 // +1 because we always have an interpreter return address for the final slot.
625 address* frame_pcs = NEW_C_HEAP_ARRAY(address, number_of_frames + 1, mtCompiler);
626 int popframe_extra_args = 0;
627 // Create an interpreter return address for the stub to use as its return
628 // address so the skeletal frames are perfectly walkable
629 frame_pcs[number_of_frames] = Interpreter::deopt_entry(vtos, 0);
630
631 // PopFrame requires that the preserved incoming arguments from the recently-popped topmost
632 // activation be put back on the expression stack of the caller for reexecution
633 if (JvmtiExport::can_pop_frame() && current->popframe_forcing_deopt_reexecution()) {
634 popframe_extra_args = in_words(current->popframe_preserved_args_size_in_words());
635 }
636
637 // Find the current pc for sender of the deoptee. Since the sender may have been deoptimized
638 // itself since the deoptee vframeArray was created we must get a fresh value of the pc rather
639 // than simply use array->sender.pc(). This requires us to walk the current set of frames
640 //
641 frame deopt_sender = stub_frame.sender(&dummy_map); // First is the deoptee frame
642 deopt_sender = deopt_sender.sender(&dummy_map); // Now deoptee caller
643
644 // It's possible that the number of parameters at the call site is
645 // different than number of arguments in the callee when method
646 // handles are used. If the caller is interpreted get the real
647 // value so that the proper amount of space can be added to it's
648 // frame.
649 bool caller_was_method_handle = false;
650 if (deopt_sender.is_interpreted_frame()) {
651 methodHandle method(current, deopt_sender.interpreter_frame_method());
652 Bytecode_invoke cur = Bytecode_invoke_check(method, deopt_sender.interpreter_frame_bci());
653 if (cur.is_invokedynamic() || cur.is_invokehandle()) {
654 // Method handle invokes may involve fairly arbitrary chains of
655 // calls so it's impossible to know how much actual space the
656 // caller has for locals.
657 caller_was_method_handle = true;
658 }
659 }
660
661 //
662 // frame_sizes/frame_pcs[0] oldest frame (int or c2i)
663 // frame_sizes/frame_pcs[1] next oldest frame (int)
664 // frame_sizes/frame_pcs[n] youngest frame (int)
665 //
666 // Now a pc in frame_pcs is actually the return address to the frame's caller (a frame
667 // owns the space for the return address to it's caller). Confusing ain't it.
668 //
669 // The vframe array can address vframes with indices running from
670 // 0.._frames-1. Index 0 is the youngest frame and _frame - 1 is the oldest (root) frame.
671 // When we create the skeletal frames we need the oldest frame to be in the zero slot
672 // in the frame_sizes/frame_pcs so the assembly code can do a trivial walk.
673 // so things look a little strange in this loop.
674 //
675 int callee_parameters = 0;
676 int callee_locals = 0;
677 for (int index = 0; index < array->frames(); index++ ) {
678 // frame[number_of_frames - 1 ] = on_stack_size(youngest)
679 // frame[number_of_frames - 2 ] = on_stack_size(sender(youngest))
680 // frame[number_of_frames - 3 ] = on_stack_size(sender(sender(youngest)))
681 frame_sizes[number_of_frames - 1 - index] = BytesPerWord * array->element(index)->on_stack_size(callee_parameters,
682 callee_locals,
683 index == 0,
684 popframe_extra_args);
685 // This pc doesn't have to be perfect just good enough to identify the frame
686 // as interpreted so the skeleton frame will be walkable
687 // The correct pc will be set when the skeleton frame is completely filled out
688 // The final pc we store in the loop is wrong and will be overwritten below
689 frame_pcs[number_of_frames - 1 - index ] = Interpreter::deopt_entry(vtos, 0) - frame::pc_return_offset;
690
691 callee_parameters = array->element(index)->method()->size_of_parameters();
692 callee_locals = array->element(index)->method()->max_locals();
693 popframe_extra_args = 0;
694 }
695
696 // Compute whether the root vframe returns a float or double value.
697 BasicType return_type;
698 {
699 methodHandle method(current, array->element(0)->method());
700 Bytecode_invoke invoke = Bytecode_invoke_check(method, array->element(0)->bci());
701 return_type = invoke.is_valid() ? invoke.result_type() : T_ILLEGAL;
702 }
703
704 // Compute information for handling adapters and adjusting the frame size of the caller.
705 int caller_adjustment = 0;
706
707 // Compute the amount the oldest interpreter frame will have to adjust
708 // its caller's stack by. If the caller is a compiled frame then
709 // we pretend that the callee has no parameters so that the
710 // extension counts for the full amount of locals and not just
711 // locals-parms. This is because without a c2i adapter the parm
712 // area as created by the compiled frame will not be usable by
713 // the interpreter. (Depending on the calling convention there
714 // may not even be enough space).
715
716 // QQQ I'd rather see this pushed down into last_frame_adjust
717 // and have it take the sender (aka caller).
718
719 if (!deopt_sender.is_interpreted_frame() || caller_was_method_handle) {
720 caller_adjustment = last_frame_adjust(0, callee_locals);
721 } else if (callee_locals > callee_parameters) {
722 // The caller frame may need extending to accommodate
723 // non-parameter locals of the first unpacked interpreted frame.
724 // Compute that adjustment.
725 caller_adjustment = last_frame_adjust(callee_parameters, callee_locals);
726 }
727
728 // If the sender is deoptimized the we must retrieve the address of the handler
729 // since the frame will "magically" show the original pc before the deopt
730 // and we'd undo the deopt.
731
732 frame_pcs[0] = Continuation::is_cont_barrier_frame(deoptee) ? StubRoutines::cont_returnBarrier() : deopt_sender.raw_pc();
733 if (Continuation::is_continuation_enterSpecial(deopt_sender)) {
734 ContinuationEntry::from_frame(deopt_sender)->set_argsize(0);
735 }
736
737 assert(CodeCache::find_blob(frame_pcs[0]) != nullptr, "bad pc");
738
739 #if INCLUDE_JVMCI
740 if (exceptionObject() != nullptr) {
741 current->set_exception_oop(exceptionObject());
742 exec_mode = Unpack_exception;
743 }
744 #endif
745
746 if (current->frames_to_pop_failed_realloc() > 0 && exec_mode != Unpack_uncommon_trap) {
747 assert(current->has_pending_exception(), "should have thrown OOME");
748 current->set_exception_oop(current->pending_exception());
749 current->clear_pending_exception();
750 exec_mode = Unpack_exception;
751 }
752
753 #if INCLUDE_JVMCI
754 if (current->frames_to_pop_failed_realloc() > 0) {
755 current->set_pending_monitorenter(false);
756 }
757 #endif
758
759 UnrollBlock* info = new UnrollBlock(array->frame_size() * BytesPerWord,
760 caller_adjustment * BytesPerWord,
761 caller_was_method_handle ? 0 : callee_parameters,
762 number_of_frames,
763 frame_sizes,
764 frame_pcs,
765 return_type,
766 exec_mode);
767 // On some platforms, we need a way to pass some platform dependent
768 // information to the unpacking code so the skeletal frames come out
769 // correct (initial fp value, unextended sp, ...)
770 info->set_initial_info((intptr_t) array->sender().initial_deoptimization_info());
771
772 if (array->frames() > 1) {
773 if (VerifyStack && TraceDeoptimization) {
774 tty->print_cr("Deoptimizing method containing inlining");
775 }
776 }
777
778 array->set_unroll_block(info);
779 return info;
780 }
781
782 // Called to cleanup deoptimization data structures in normal case
783 // after unpacking to stack and when stack overflow error occurs
784 void Deoptimization::cleanup_deopt_info(JavaThread *thread,
785 vframeArray *array) {
786
787 // Get array if coming from exception
788 if (array == nullptr) {
789 array = thread->vframe_array_head();
790 }
791 thread->set_vframe_array_head(nullptr);
792
793 // Free the previous UnrollBlock
794 vframeArray* old_array = thread->vframe_array_last();
795 thread->set_vframe_array_last(array);
796
797 if (old_array != nullptr) {
798 UnrollBlock* old_info = old_array->unroll_block();
799 old_array->set_unroll_block(nullptr);
800 delete old_info;
801 delete old_array;
802 }
803
804 // Deallocate any resource creating in this routine and any ResourceObjs allocated
805 // inside the vframeArray (StackValueCollections)
806
807 delete thread->deopt_mark();
808 thread->set_deopt_mark(nullptr);
809 thread->set_deopt_compiled_method(nullptr);
810
811
812 if (JvmtiExport::can_pop_frame()) {
813 // Regardless of whether we entered this routine with the pending
814 // popframe condition bit set, we should always clear it now
815 thread->clear_popframe_condition();
816 }
817
818 // unpack_frames() is called at the end of the deoptimization handler
819 // and (in C2) at the end of the uncommon trap handler. Note this fact
820 // so that an asynchronous stack walker can work again. This counter is
821 // incremented at the beginning of fetch_unroll_info() and (in C2) at
822 // the beginning of uncommon_trap().
823 thread->dec_in_deopt_handler();
824 }
825
826 // Moved from cpu directories because none of the cpus has callee save values.
827 // If a cpu implements callee save values, move this to deoptimization_<cpu>.cpp.
828 void Deoptimization::unwind_callee_save_values(frame* f, vframeArray* vframe_array) {
829
830 // This code is sort of the equivalent of C2IAdapter::setup_stack_frame back in
831 // the days we had adapter frames. When we deoptimize a situation where a
832 // compiled caller calls a compiled caller will have registers it expects
833 // to survive the call to the callee. If we deoptimize the callee the only
834 // way we can restore these registers is to have the oldest interpreter
835 // frame that we create restore these values. That is what this routine
836 // will accomplish.
837
838 // At the moment we have modified c2 to not have any callee save registers
839 // so this problem does not exist and this routine is just a place holder.
840
841 assert(f->is_interpreted_frame(), "must be interpreted");
842 }
843
844 #ifndef PRODUCT
845 static bool falls_through(Bytecodes::Code bc) {
846 switch (bc) {
847 // List may be incomplete. Here we really only care about bytecodes where compiled code
848 // can deoptimize.
849 case Bytecodes::_goto:
850 case Bytecodes::_goto_w:
851 case Bytecodes::_athrow:
852 return false;
853 default:
854 return true;
855 }
856 }
857 #endif
858
859 // Return BasicType of value being returned
860 JRT_LEAF(BasicType, Deoptimization::unpack_frames(JavaThread* thread, int exec_mode))
861 assert(thread == JavaThread::current(), "pre-condition");
862
863 // We are already active in the special DeoptResourceMark any ResourceObj's we
864 // allocate will be freed at the end of the routine.
865
866 // JRT_LEAF methods don't normally allocate handles and there is a
867 // NoHandleMark to enforce that. It is actually safe to use Handles
868 // in a JRT_LEAF method, and sometimes desirable, but to do so we
869 // must use ResetNoHandleMark to bypass the NoHandleMark, and
870 // then use a HandleMark to ensure any Handles we do create are
871 // cleaned up in this scope.
872 ResetNoHandleMark rnhm;
873 HandleMark hm(thread);
874
875 frame stub_frame = thread->last_frame();
876
877 Continuation::notify_deopt(thread, stub_frame.sp());
878
879 // Since the frame to unpack is the top frame of this thread, the vframe_array_head
880 // must point to the vframeArray for the unpack frame.
881 vframeArray* array = thread->vframe_array_head();
882 UnrollBlock* info = array->unroll_block();
883
884 // We set the last_Java frame. But the stack isn't really parsable here. So we
885 // clear it to make sure JFR understands not to try and walk stacks from events
886 // in here.
887 intptr_t* sp = thread->frame_anchor()->last_Java_sp();
888 thread->frame_anchor()->set_last_Java_sp(nullptr);
889
890 // Unpack the interpreter frames and any adapter frame (c2 only) we might create.
891 array->unpack_to_stack(stub_frame, exec_mode, info->caller_actual_parameters());
892
893 thread->frame_anchor()->set_last_Java_sp(sp);
894
895 BasicType bt = info->return_type();
896
897 // If we have an exception pending, claim that the return type is an oop
898 // so the deopt_blob does not overwrite the exception_oop.
899
900 if (exec_mode == Unpack_exception)
901 bt = T_OBJECT;
902
903 // Cleanup thread deopt data
904 cleanup_deopt_info(thread, array);
905
906 #ifndef PRODUCT
907 if (VerifyStack) {
908 ResourceMark res_mark;
909 // Clear pending exception to not break verification code (restored afterwards)
910 PreserveExceptionMark pm(thread);
911
912 thread->validate_frame_layout();
913
914 // Verify that the just-unpacked frames match the interpreter's
915 // notions of expression stack and locals
916 vframeArray* cur_array = thread->vframe_array_last();
917 RegisterMap rm(thread,
918 RegisterMap::UpdateMap::skip,
919 RegisterMap::ProcessFrames::include,
920 RegisterMap::WalkContinuation::skip);
921 rm.set_include_argument_oops(false);
922 bool is_top_frame = true;
923 int callee_size_of_parameters = 0;
924 int callee_max_locals = 0;
925 for (int i = 0; i < cur_array->frames(); i++) {
926 vframeArrayElement* el = cur_array->element(i);
927 frame* iframe = el->iframe();
928 guarantee(iframe->is_interpreted_frame(), "Wrong frame type");
929
930 // Get the oop map for this bci
931 InterpreterOopMap mask;
932 int cur_invoke_parameter_size = 0;
933 bool try_next_mask = false;
934 int next_mask_expression_stack_size = -1;
935 int top_frame_expression_stack_adjustment = 0;
936 methodHandle mh(thread, iframe->interpreter_frame_method());
937 OopMapCache::compute_one_oop_map(mh, iframe->interpreter_frame_bci(), &mask);
938 BytecodeStream str(mh, iframe->interpreter_frame_bci());
939 int max_bci = mh->code_size();
940 // Get to the next bytecode if possible
941 assert(str.bci() < max_bci, "bci in interpreter frame out of bounds");
942 // Check to see if we can grab the number of outgoing arguments
943 // at an uncommon trap for an invoke (where the compiler
944 // generates debug info before the invoke has executed)
945 Bytecodes::Code cur_code = str.next();
946 Bytecodes::Code next_code = Bytecodes::_shouldnotreachhere;
947 if (Bytecodes::is_invoke(cur_code)) {
948 Bytecode_invoke invoke(mh, iframe->interpreter_frame_bci());
949 cur_invoke_parameter_size = invoke.size_of_parameters();
950 if (i != 0 && !invoke.is_invokedynamic() && MethodHandles::has_member_arg(invoke.klass(), invoke.name())) {
951 callee_size_of_parameters++;
952 }
953 }
954 if (str.bci() < max_bci) {
955 next_code = str.next();
956 if (next_code >= 0) {
957 // The interpreter oop map generator reports results before
958 // the current bytecode has executed except in the case of
959 // calls. It seems to be hard to tell whether the compiler
960 // has emitted debug information matching the "state before"
961 // a given bytecode or the state after, so we try both
962 if (!Bytecodes::is_invoke(cur_code) && falls_through(cur_code)) {
963 // Get expression stack size for the next bytecode
964 InterpreterOopMap next_mask;
965 OopMapCache::compute_one_oop_map(mh, str.bci(), &next_mask);
966 next_mask_expression_stack_size = next_mask.expression_stack_size();
967 if (Bytecodes::is_invoke(next_code)) {
968 Bytecode_invoke invoke(mh, str.bci());
969 next_mask_expression_stack_size += invoke.size_of_parameters();
970 }
971 // Need to subtract off the size of the result type of
972 // the bytecode because this is not described in the
973 // debug info but returned to the interpreter in the TOS
974 // caching register
975 BasicType bytecode_result_type = Bytecodes::result_type(cur_code);
976 if (bytecode_result_type != T_ILLEGAL) {
977 top_frame_expression_stack_adjustment = type2size[bytecode_result_type];
978 }
979 assert(top_frame_expression_stack_adjustment >= 0, "stack adjustment must be positive");
980 try_next_mask = true;
981 }
982 }
983 }
984
985 // Verify stack depth and oops in frame
986 // This assertion may be dependent on the platform we're running on and may need modification (tested on x86 and sparc)
987 if (!(
988 /* SPARC */
989 (iframe->interpreter_frame_expression_stack_size() == mask.expression_stack_size() + callee_size_of_parameters) ||
990 /* x86 */
991 (iframe->interpreter_frame_expression_stack_size() == mask.expression_stack_size() + callee_max_locals) ||
992 (try_next_mask &&
993 (iframe->interpreter_frame_expression_stack_size() == (next_mask_expression_stack_size -
994 top_frame_expression_stack_adjustment))) ||
995 (is_top_frame && (exec_mode == Unpack_exception) && iframe->interpreter_frame_expression_stack_size() == 0) ||
996 (is_top_frame && (exec_mode == Unpack_uncommon_trap || exec_mode == Unpack_reexecute || el->should_reexecute()) &&
997 (iframe->interpreter_frame_expression_stack_size() == mask.expression_stack_size() + cur_invoke_parameter_size))
998 )) {
999 {
1000 // Print out some information that will help us debug the problem
1001 tty->print_cr("Wrong number of expression stack elements during deoptimization");
1002 tty->print_cr(" Error occurred while verifying frame %d (0..%d, 0 is topmost)", i, cur_array->frames() - 1);
1003 tty->print_cr(" Current code %s", Bytecodes::name(cur_code));
1004 if (try_next_mask) {
1005 tty->print_cr(" Next code %s", Bytecodes::name(next_code));
1006 }
1007 tty->print_cr(" Fabricated interpreter frame had %d expression stack elements",
1008 iframe->interpreter_frame_expression_stack_size());
1009 tty->print_cr(" Interpreter oop map had %d expression stack elements", mask.expression_stack_size());
1010 tty->print_cr(" try_next_mask = %d", try_next_mask);
1011 tty->print_cr(" next_mask_expression_stack_size = %d", next_mask_expression_stack_size);
1012 tty->print_cr(" callee_size_of_parameters = %d", callee_size_of_parameters);
1013 tty->print_cr(" callee_max_locals = %d", callee_max_locals);
1014 tty->print_cr(" top_frame_expression_stack_adjustment = %d", top_frame_expression_stack_adjustment);
1015 tty->print_cr(" exec_mode = %d", exec_mode);
1016 tty->print_cr(" cur_invoke_parameter_size = %d", cur_invoke_parameter_size);
1017 tty->print_cr(" Thread = " INTPTR_FORMAT ", thread ID = %d", p2i(thread), thread->osthread()->thread_id());
1018 tty->print_cr(" Interpreted frames:");
1019 for (int k = 0; k < cur_array->frames(); k++) {
1020 vframeArrayElement* el = cur_array->element(k);
1021 tty->print_cr(" %s (bci %d)", el->method()->name_and_sig_as_C_string(), el->bci());
1022 }
1023 cur_array->print_on_2(tty);
1024 }
1025 guarantee(false, "wrong number of expression stack elements during deopt");
1026 }
1027 VerifyOopClosure verify;
1028 iframe->oops_interpreted_do(&verify, &rm, false);
1029 callee_size_of_parameters = mh->size_of_parameters();
1030 callee_max_locals = mh->max_locals();
1031 is_top_frame = false;
1032 }
1033 }
1034 #endif // !PRODUCT
1035
1036 return bt;
1037 JRT_END
1038
1039 class DeoptimizeMarkedClosure : public HandshakeClosure {
1040 public:
1041 DeoptimizeMarkedClosure() : HandshakeClosure("Deoptimize") {}
1042 void do_thread(Thread* thread) {
1043 JavaThread* jt = JavaThread::cast(thread);
1044 jt->deoptimize_marked_methods();
1045 }
1046 };
1047
1048 void Deoptimization::deoptimize_all_marked() {
1049 ResourceMark rm;
1050
1051 // Make the dependent methods not entrant
1052 CodeCache::make_marked_nmethods_deoptimized();
1053
1054 DeoptimizeMarkedClosure deopt;
1055 if (SafepointSynchronize::is_at_safepoint()) {
1056 Threads::java_threads_do(&deopt);
1057 } else {
1058 Handshake::execute(&deopt);
1059 }
1060 }
1061
1062 Deoptimization::DeoptAction Deoptimization::_unloaded_action
1063 = Deoptimization::Action_reinterpret;
1064
1065 #if INCLUDE_JVMCI
1066 template<typename CacheType>
1067 class BoxCacheBase : public CHeapObj<mtCompiler> {
1068 protected:
1069 static InstanceKlass* find_cache_klass(Thread* thread, Symbol* klass_name) {
1070 ResourceMark rm(thread);
1071 char* klass_name_str = klass_name->as_C_string();
1072 InstanceKlass* ik = SystemDictionary::find_instance_klass(thread, klass_name, Handle(), Handle());
1073 guarantee(ik != nullptr, "%s must be loaded", klass_name_str);
1074 if (!ik->is_in_error_state()) {
1075 guarantee(ik->is_initialized(), "%s must be initialized", klass_name_str);
1076 CacheType::compute_offsets(ik);
1077 }
1078 return ik;
1079 }
1080 };
1081
1082 template<typename PrimitiveType, typename CacheType, typename BoxType> class BoxCache : public BoxCacheBase<CacheType> {
1083 PrimitiveType _low;
1084 PrimitiveType _high;
1085 jobject _cache;
1086 protected:
1087 static BoxCache<PrimitiveType, CacheType, BoxType> *_singleton;
1088 BoxCache(Thread* thread) {
1089 InstanceKlass* ik = BoxCacheBase<CacheType>::find_cache_klass(thread, CacheType::symbol());
1090 if (ik->is_in_error_state()) {
1091 _low = 1;
1092 _high = 0;
1093 _cache = nullptr;
1094 } else {
1095 objArrayOop cache = CacheType::cache(ik);
1096 assert(cache->length() > 0, "Empty cache");
1097 _low = BoxType::value(cache->obj_at(0));
1098 _high = _low + cache->length() - 1;
1099 _cache = JNIHandles::make_global(Handle(thread, cache));
1100 }
1101 }
1102 ~BoxCache() {
1103 JNIHandles::destroy_global(_cache);
1104 }
1105 public:
1106 static BoxCache<PrimitiveType, CacheType, BoxType>* singleton(Thread* thread) {
1107 if (_singleton == nullptr) {
1108 BoxCache<PrimitiveType, CacheType, BoxType>* s = new BoxCache<PrimitiveType, CacheType, BoxType>(thread);
1109 if (!Atomic::replace_if_null(&_singleton, s)) {
1110 delete s;
1111 }
1112 }
1113 return _singleton;
1114 }
1115 oop lookup(PrimitiveType value) {
1116 if (_low <= value && value <= _high) {
1117 int offset = value - _low;
1118 return objArrayOop(JNIHandles::resolve_non_null(_cache))->obj_at(offset);
1119 }
1120 return nullptr;
1121 }
1122 oop lookup_raw(intptr_t raw_value, bool& cache_init_error) {
1123 if (_cache == nullptr) {
1124 cache_init_error = true;
1125 return nullptr;
1126 }
1127 // Have to cast to avoid little/big-endian problems.
1128 if (sizeof(PrimitiveType) > sizeof(jint)) {
1129 jlong value = (jlong)raw_value;
1130 return lookup(value);
1131 }
1132 PrimitiveType value = (PrimitiveType)*((jint*)&raw_value);
1133 return lookup(value);
1134 }
1135 };
1136
1137 typedef BoxCache<jint, java_lang_Integer_IntegerCache, java_lang_Integer> IntegerBoxCache;
1138 typedef BoxCache<jlong, java_lang_Long_LongCache, java_lang_Long> LongBoxCache;
1139 typedef BoxCache<jchar, java_lang_Character_CharacterCache, java_lang_Character> CharacterBoxCache;
1140 typedef BoxCache<jshort, java_lang_Short_ShortCache, java_lang_Short> ShortBoxCache;
1141 typedef BoxCache<jbyte, java_lang_Byte_ByteCache, java_lang_Byte> ByteBoxCache;
1142
1143 template<> BoxCache<jint, java_lang_Integer_IntegerCache, java_lang_Integer>* BoxCache<jint, java_lang_Integer_IntegerCache, java_lang_Integer>::_singleton = nullptr;
1144 template<> BoxCache<jlong, java_lang_Long_LongCache, java_lang_Long>* BoxCache<jlong, java_lang_Long_LongCache, java_lang_Long>::_singleton = nullptr;
1145 template<> BoxCache<jchar, java_lang_Character_CharacterCache, java_lang_Character>* BoxCache<jchar, java_lang_Character_CharacterCache, java_lang_Character>::_singleton = nullptr;
1146 template<> BoxCache<jshort, java_lang_Short_ShortCache, java_lang_Short>* BoxCache<jshort, java_lang_Short_ShortCache, java_lang_Short>::_singleton = nullptr;
1147 template<> BoxCache<jbyte, java_lang_Byte_ByteCache, java_lang_Byte>* BoxCache<jbyte, java_lang_Byte_ByteCache, java_lang_Byte>::_singleton = nullptr;
1148
1149 class BooleanBoxCache : public BoxCacheBase<java_lang_Boolean> {
1150 jobject _true_cache;
1151 jobject _false_cache;
1152 protected:
1153 static BooleanBoxCache *_singleton;
1154 BooleanBoxCache(Thread *thread) {
1155 InstanceKlass* ik = find_cache_klass(thread, java_lang_Boolean::symbol());
1156 if (ik->is_in_error_state()) {
1157 _true_cache = nullptr;
1158 _false_cache = nullptr;
1159 } else {
1160 _true_cache = JNIHandles::make_global(Handle(thread, java_lang_Boolean::get_TRUE(ik)));
1161 _false_cache = JNIHandles::make_global(Handle(thread, java_lang_Boolean::get_FALSE(ik)));
1162 }
1163 }
1164 ~BooleanBoxCache() {
1165 JNIHandles::destroy_global(_true_cache);
1166 JNIHandles::destroy_global(_false_cache);
1167 }
1168 public:
1169 static BooleanBoxCache* singleton(Thread* thread) {
1170 if (_singleton == nullptr) {
1171 BooleanBoxCache* s = new BooleanBoxCache(thread);
1172 if (!Atomic::replace_if_null(&_singleton, s)) {
1173 delete s;
1174 }
1175 }
1176 return _singleton;
1177 }
1178 oop lookup_raw(intptr_t raw_value, bool& cache_in_error) {
1179 if (_true_cache == nullptr) {
1180 cache_in_error = true;
1181 return nullptr;
1182 }
1183 // Have to cast to avoid little/big-endian problems.
1184 jboolean value = (jboolean)*((jint*)&raw_value);
1185 return lookup(value);
1186 }
1187 oop lookup(jboolean value) {
1188 if (value != 0) {
1189 return JNIHandles::resolve_non_null(_true_cache);
1190 }
1191 return JNIHandles::resolve_non_null(_false_cache);
1192 }
1193 };
1194
1195 BooleanBoxCache* BooleanBoxCache::_singleton = nullptr;
1196
1197 oop Deoptimization::get_cached_box(AutoBoxObjectValue* bv, frame* fr, RegisterMap* reg_map, bool& cache_init_error, TRAPS) {
1198 Klass* k = java_lang_Class::as_Klass(bv->klass()->as_ConstantOopReadValue()->value()());
1199 BasicType box_type = vmClasses::box_klass_type(k);
1200 if (box_type != T_OBJECT) {
1201 StackValue* value = StackValue::create_stack_value(fr, reg_map, bv->field_at(box_type == T_LONG ? 1 : 0));
1202 switch(box_type) {
1203 case T_INT: return IntegerBoxCache::singleton(THREAD)->lookup_raw(value->get_int(), cache_init_error);
1204 case T_CHAR: return CharacterBoxCache::singleton(THREAD)->lookup_raw(value->get_int(), cache_init_error);
1205 case T_SHORT: return ShortBoxCache::singleton(THREAD)->lookup_raw(value->get_int(), cache_init_error);
1206 case T_BYTE: return ByteBoxCache::singleton(THREAD)->lookup_raw(value->get_int(), cache_init_error);
1207 case T_BOOLEAN: return BooleanBoxCache::singleton(THREAD)->lookup_raw(value->get_int(), cache_init_error);
1208 case T_LONG: return LongBoxCache::singleton(THREAD)->lookup_raw(value->get_int(), cache_init_error);
1209 default:;
1210 }
1211 }
1212 return nullptr;
1213 }
1214 #endif // INCLUDE_JVMCI
1215
1216 #if COMPILER2_OR_JVMCI
1217 bool Deoptimization::realloc_objects(JavaThread* thread, frame* fr, RegisterMap* reg_map, GrowableArray<ScopeValue*>* objects, TRAPS) {
1218 Handle pending_exception(THREAD, thread->pending_exception());
1219 const char* exception_file = thread->exception_file();
1220 int exception_line = thread->exception_line();
1221 thread->clear_pending_exception();
1222
1223 bool failures = false;
1224
1225 for (int i = 0; i < objects->length(); i++) {
1226 assert(objects->at(i)->is_object(), "invalid debug information");
1227 ObjectValue* sv = (ObjectValue*) objects->at(i);
1228
1229 Klass* k = java_lang_Class::as_Klass(sv->klass()->as_ConstantOopReadValue()->value()());
1230 oop obj = nullptr;
1231
1232 bool cache_init_error = false;
1233 if (k->is_instance_klass()) {
1234 #if INCLUDE_JVMCI
1235 CompiledMethod* cm = fr->cb()->as_compiled_method_or_null();
1236 if (cm->is_compiled_by_jvmci() && sv->is_auto_box()) {
1237 AutoBoxObjectValue* abv = (AutoBoxObjectValue*) sv;
1238 obj = get_cached_box(abv, fr, reg_map, cache_init_error, THREAD);
1239 if (obj != nullptr) {
1240 // Set the flag to indicate the box came from a cache, so that we can skip the field reassignment for it.
1241 abv->set_cached(true);
1242 } else if (cache_init_error) {
1243 // Results in an OOME which is valid (as opposed to a class initialization error)
1244 // and is fine for the rare case a cache initialization failing.
1245 failures = true;
1246 }
1247 }
1248 #endif // INCLUDE_JVMCI
1249
1250 InstanceKlass* ik = InstanceKlass::cast(k);
1251 if (obj == nullptr && !cache_init_error) {
1252 #ifdef COMPILER2
1253 if (EnableVectorSupport && VectorSupport::is_vector(ik)) {
1254 obj = VectorSupport::allocate_vector(ik, fr, reg_map, sv, THREAD);
1255 } else {
1256 obj = ik->allocate_instance(THREAD);
1257 }
1258 #else
1259 obj = ik->allocate_instance(THREAD);
1260 #endif // COMPILER2
1261 }
1262 } else if (k->is_typeArray_klass()) {
1263 TypeArrayKlass* ak = TypeArrayKlass::cast(k);
1264 assert(sv->field_size() % type2size[ak->element_type()] == 0, "non-integral array length");
1265 int len = sv->field_size() / type2size[ak->element_type()];
1266 obj = ak->allocate(len, THREAD);
1267 } else if (k->is_objArray_klass()) {
1268 ObjArrayKlass* ak = ObjArrayKlass::cast(k);
1269 obj = ak->allocate(sv->field_size(), THREAD);
1270 }
1271
1272 if (obj == nullptr) {
1273 failures = true;
1274 }
1275
1276 assert(sv->value().is_null(), "redundant reallocation");
1277 assert(obj != nullptr || HAS_PENDING_EXCEPTION || cache_init_error, "allocation should succeed or we should get an exception");
1278 CLEAR_PENDING_EXCEPTION;
1279 sv->set_value(obj);
1280 }
1281
1282 if (failures) {
1283 THROW_OOP_(Universe::out_of_memory_error_realloc_objects(), failures);
1284 } else if (pending_exception.not_null()) {
1285 thread->set_pending_exception(pending_exception(), exception_file, exception_line);
1286 }
1287
1288 return failures;
1289 }
1290
1291 #if INCLUDE_JVMCI
1292 /**
1293 * For primitive types whose kind gets "erased" at runtime (shorts become stack ints),
1294 * we need to somehow be able to recover the actual kind to be able to write the correct
1295 * amount of bytes.
1296 * For that purpose, this method assumes that, for an entry spanning n bytes at index i,
1297 * the entries at index n + 1 to n + i are 'markers'.
1298 * For example, if we were writing a short at index 4 of a byte array of size 8, the
1299 * expected form of the array would be:
1300 *
1301 * {b0, b1, b2, b3, INT, marker, b6, b7}
1302 *
1303 * Thus, in order to get back the size of the entry, we simply need to count the number
1304 * of marked entries
1305 *
1306 * @param virtualArray the virtualized byte array
1307 * @param i index of the virtual entry we are recovering
1308 * @return The number of bytes the entry spans
1309 */
1310 static int count_number_of_bytes_for_entry(ObjectValue *virtualArray, int i) {
1311 int index = i;
1312 while (++index < virtualArray->field_size() &&
1313 virtualArray->field_at(index)->is_marker()) {}
1314 return index - i;
1315 }
1316
1317 /**
1318 * If there was a guarantee for byte array to always start aligned to a long, we could
1319 * do a simple check on the parity of the index. Unfortunately, that is not always the
1320 * case. Thus, we check alignment of the actual address we are writing to.
1321 * In the unlikely case index 0 is 5-aligned for example, it would then be possible to
1322 * write a long to index 3.
1323 */
1324 static jbyte* check_alignment_get_addr(typeArrayOop obj, int index, int expected_alignment) {
1325 jbyte* res = obj->byte_at_addr(index);
1326 assert((((intptr_t) res) % expected_alignment) == 0, "Non-aligned write");
1327 return res;
1328 }
1329
1330 static void byte_array_put(typeArrayOop obj, intptr_t val, int index, int byte_count) {
1331 switch (byte_count) {
1332 case 1:
1333 obj->byte_at_put(index, (jbyte) *((jint *) &val));
1334 break;
1335 case 2:
1336 *((jshort *) check_alignment_get_addr(obj, index, 2)) = (jshort) *((jint *) &val);
1337 break;
1338 case 4:
1339 *((jint *) check_alignment_get_addr(obj, index, 4)) = (jint) *((jint *) &val);
1340 break;
1341 case 8:
1342 *((jlong *) check_alignment_get_addr(obj, index, 8)) = (jlong) *((jlong *) &val);
1343 break;
1344 default:
1345 ShouldNotReachHere();
1346 }
1347 }
1348 #endif // INCLUDE_JVMCI
1349
1350
1351 // restore elements of an eliminated type array
1352 void Deoptimization::reassign_type_array_elements(frame* fr, RegisterMap* reg_map, ObjectValue* sv, typeArrayOop obj, BasicType type) {
1353 int index = 0;
1354 intptr_t val;
1355
1356 for (int i = 0; i < sv->field_size(); i++) {
1357 StackValue* value = StackValue::create_stack_value(fr, reg_map, sv->field_at(i));
1358 switch(type) {
1359 case T_LONG: case T_DOUBLE: {
1360 assert(value->type() == T_INT, "Agreement.");
1361 StackValue* low =
1362 StackValue::create_stack_value(fr, reg_map, sv->field_at(++i));
1363 #ifdef _LP64
1364 jlong res = (jlong)low->get_int();
1365 #else
1366 jlong res = jlong_from((jint)value->get_int(), (jint)low->get_int());
1367 #endif
1368 obj->long_at_put(index, res);
1369 break;
1370 }
1371
1372 // Have to cast to INT (32 bits) pointer to avoid little/big-endian problem.
1373 case T_INT: case T_FLOAT: { // 4 bytes.
1374 assert(value->type() == T_INT, "Agreement.");
1375 bool big_value = false;
1376 if (i + 1 < sv->field_size() && type == T_INT) {
1377 if (sv->field_at(i)->is_location()) {
1378 Location::Type type = ((LocationValue*) sv->field_at(i))->location().type();
1379 if (type == Location::dbl || type == Location::lng) {
1380 big_value = true;
1381 }
1382 } else if (sv->field_at(i)->is_constant_int()) {
1383 ScopeValue* next_scope_field = sv->field_at(i + 1);
1384 if (next_scope_field->is_constant_long() || next_scope_field->is_constant_double()) {
1385 big_value = true;
1386 }
1387 }
1388 }
1389
1390 if (big_value) {
1391 StackValue* low = StackValue::create_stack_value(fr, reg_map, sv->field_at(++i));
1392 #ifdef _LP64
1393 jlong res = (jlong)low->get_int();
1394 #else
1395 jlong res = jlong_from((jint)value->get_int(), (jint)low->get_int());
1396 #endif
1397 obj->int_at_put(index, (jint)*((jint*)&res));
1398 obj->int_at_put(++index, (jint)*(((jint*)&res) + 1));
1399 } else {
1400 val = value->get_int();
1401 obj->int_at_put(index, (jint)*((jint*)&val));
1402 }
1403 break;
1404 }
1405
1406 case T_SHORT:
1407 assert(value->type() == T_INT, "Agreement.");
1408 val = value->get_int();
1409 obj->short_at_put(index, (jshort)*((jint*)&val));
1410 break;
1411
1412 case T_CHAR:
1413 assert(value->type() == T_INT, "Agreement.");
1414 val = value->get_int();
1415 obj->char_at_put(index, (jchar)*((jint*)&val));
1416 break;
1417
1418 case T_BYTE: {
1419 assert(value->type() == T_INT, "Agreement.");
1420 // The value we get is erased as a regular int. We will need to find its actual byte count 'by hand'.
1421 val = value->get_int();
1422 #if INCLUDE_JVMCI
1423 int byte_count = count_number_of_bytes_for_entry(sv, i);
1424 byte_array_put(obj, val, index, byte_count);
1425 // According to byte_count contract, the values from i + 1 to i + byte_count are illegal values. Skip.
1426 i += byte_count - 1; // Balance the loop counter.
1427 index += byte_count;
1428 // index has been updated so continue at top of loop
1429 continue;
1430 #else
1431 obj->byte_at_put(index, (jbyte)*((jint*)&val));
1432 break;
1433 #endif // INCLUDE_JVMCI
1434 }
1435
1436 case T_BOOLEAN: {
1437 assert(value->type() == T_INT, "Agreement.");
1438 val = value->get_int();
1439 obj->bool_at_put(index, (jboolean)*((jint*)&val));
1440 break;
1441 }
1442
1443 default:
1444 ShouldNotReachHere();
1445 }
1446 index++;
1447 }
1448 }
1449
1450 // restore fields of an eliminated object array
1451 void Deoptimization::reassign_object_array_elements(frame* fr, RegisterMap* reg_map, ObjectValue* sv, objArrayOop obj) {
1452 for (int i = 0; i < sv->field_size(); i++) {
1453 StackValue* value = StackValue::create_stack_value(fr, reg_map, sv->field_at(i));
1454 assert(value->type() == T_OBJECT, "object element expected");
1455 obj->obj_at_put(i, value->get_obj()());
1456 }
1457 }
1458
1459 class ReassignedField {
1460 public:
1461 int _offset;
1462 BasicType _type;
1463 public:
1464 ReassignedField() {
1465 _offset = 0;
1466 _type = T_ILLEGAL;
1467 }
1468 };
1469
1470 int compare(ReassignedField* left, ReassignedField* right) {
1471 return left->_offset - right->_offset;
1472 }
1473
1474 // Restore fields of an eliminated instance object using the same field order
1475 // returned by HotSpotResolvedObjectTypeImpl.getInstanceFields(true)
1476 static int reassign_fields_by_klass(InstanceKlass* klass, frame* fr, RegisterMap* reg_map, ObjectValue* sv, int svIndex, oop obj, bool skip_internal) {
1477 GrowableArray<ReassignedField>* fields = new GrowableArray<ReassignedField>();
1478 InstanceKlass* ik = klass;
1479 while (ik != nullptr) {
1480 for (AllFieldStream fs(ik); !fs.done(); fs.next()) {
1481 if (!fs.access_flags().is_static() && (!skip_internal || !fs.field_flags().is_injected())) {
1482 ReassignedField field;
1483 field._offset = fs.offset();
1484 field._type = Signature::basic_type(fs.signature());
1485 fields->append(field);
1486 }
1487 }
1488 ik = ik->superklass();
1489 }
1490 fields->sort(compare);
1491 for (int i = 0; i < fields->length(); i++) {
1492 intptr_t val;
1493 ScopeValue* scope_field = sv->field_at(svIndex);
1494 StackValue* value = StackValue::create_stack_value(fr, reg_map, scope_field);
1495 int offset = fields->at(i)._offset;
1496 BasicType type = fields->at(i)._type;
1497 switch (type) {
1498 case T_OBJECT: case T_ARRAY:
1499 assert(value->type() == T_OBJECT, "Agreement.");
1500 obj->obj_field_put(offset, value->get_obj()());
1501 break;
1502
1503 // Have to cast to INT (32 bits) pointer to avoid little/big-endian problem.
1504 case T_INT: case T_FLOAT: { // 4 bytes.
1505 assert(value->type() == T_INT, "Agreement.");
1506 bool big_value = false;
1507 if (i+1 < fields->length() && fields->at(i+1)._type == T_INT) {
1508 if (scope_field->is_location()) {
1509 Location::Type type = ((LocationValue*) scope_field)->location().type();
1510 if (type == Location::dbl || type == Location::lng) {
1511 big_value = true;
1512 }
1513 }
1514 if (scope_field->is_constant_int()) {
1515 ScopeValue* next_scope_field = sv->field_at(svIndex + 1);
1516 if (next_scope_field->is_constant_long() || next_scope_field->is_constant_double()) {
1517 big_value = true;
1518 }
1519 }
1520 }
1521
1522 if (big_value) {
1523 i++;
1524 assert(i < fields->length(), "second T_INT field needed");
1525 assert(fields->at(i)._type == T_INT, "T_INT field needed");
1526 } else {
1527 val = value->get_int();
1528 obj->int_field_put(offset, (jint)*((jint*)&val));
1529 break;
1530 }
1531 }
1532 /* no break */
1533
1534 case T_LONG: case T_DOUBLE: {
1535 assert(value->type() == T_INT, "Agreement.");
1536 StackValue* low = StackValue::create_stack_value(fr, reg_map, sv->field_at(++svIndex));
1537 #ifdef _LP64
1538 jlong res = (jlong)low->get_int();
1539 #else
1540 jlong res = jlong_from((jint)value->get_int(), (jint)low->get_int());
1541 #endif
1542 obj->long_field_put(offset, res);
1543 break;
1544 }
1545
1546 case T_SHORT:
1547 assert(value->type() == T_INT, "Agreement.");
1548 val = value->get_int();
1549 obj->short_field_put(offset, (jshort)*((jint*)&val));
1550 break;
1551
1552 case T_CHAR:
1553 assert(value->type() == T_INT, "Agreement.");
1554 val = value->get_int();
1555 obj->char_field_put(offset, (jchar)*((jint*)&val));
1556 break;
1557
1558 case T_BYTE:
1559 assert(value->type() == T_INT, "Agreement.");
1560 val = value->get_int();
1561 obj->byte_field_put(offset, (jbyte)*((jint*)&val));
1562 break;
1563
1564 case T_BOOLEAN:
1565 assert(value->type() == T_INT, "Agreement.");
1566 val = value->get_int();
1567 obj->bool_field_put(offset, (jboolean)*((jint*)&val));
1568 break;
1569
1570 default:
1571 ShouldNotReachHere();
1572 }
1573 svIndex++;
1574 }
1575 return svIndex;
1576 }
1577
1578 // restore fields of all eliminated objects and arrays
1579 void Deoptimization::reassign_fields(frame* fr, RegisterMap* reg_map, GrowableArray<ScopeValue*>* objects, bool realloc_failures, bool skip_internal) {
1580 for (int i = 0; i < objects->length(); i++) {
1581 ObjectValue* sv = (ObjectValue*) objects->at(i);
1582 Klass* k = java_lang_Class::as_Klass(sv->klass()->as_ConstantOopReadValue()->value()());
1583 Handle obj = sv->value();
1584 assert(obj.not_null() || realloc_failures, "reallocation was missed");
1585 #ifndef PRODUCT
1586 if (PrintDeoptimizationDetails) {
1587 tty->print_cr("reassign fields for object of type %s!", k->name()->as_C_string());
1588 }
1589 #endif // !PRODUCT
1590
1591 if (obj.is_null()) {
1592 continue;
1593 }
1594
1595 #if INCLUDE_JVMCI
1596 // Don't reassign fields of boxes that came from a cache. Caches may be in CDS.
1597 if (sv->is_auto_box() && ((AutoBoxObjectValue*) sv)->is_cached()) {
1598 continue;
1599 }
1600 #endif // INCLUDE_JVMCI
1601 #ifdef COMPILER2
1602 if (EnableVectorSupport && VectorSupport::is_vector(k)) {
1603 assert(sv->field_size() == 1, "%s not a vector", k->name()->as_C_string());
1604 ScopeValue* payload = sv->field_at(0);
1605 if (payload->is_location() &&
1606 payload->as_LocationValue()->location().type() == Location::vector) {
1607 #ifndef PRODUCT
1608 if (PrintDeoptimizationDetails) {
1609 tty->print_cr("skip field reassignment for this vector - it should be assigned already");
1610 if (Verbose) {
1611 Handle obj = sv->value();
1612 k->oop_print_on(obj(), tty);
1613 }
1614 }
1615 #endif // !PRODUCT
1616 continue; // Such vector's value was already restored in VectorSupport::allocate_vector().
1617 }
1618 // Else fall-through to do assignment for scalar-replaced boxed vector representation
1619 // which could be restored after vector object allocation.
1620 }
1621 #endif /* !COMPILER2 */
1622 if (k->is_instance_klass()) {
1623 InstanceKlass* ik = InstanceKlass::cast(k);
1624 reassign_fields_by_klass(ik, fr, reg_map, sv, 0, obj(), skip_internal);
1625 } else if (k->is_typeArray_klass()) {
1626 TypeArrayKlass* ak = TypeArrayKlass::cast(k);
1627 reassign_type_array_elements(fr, reg_map, sv, (typeArrayOop) obj(), ak->element_type());
1628 } else if (k->is_objArray_klass()) {
1629 reassign_object_array_elements(fr, reg_map, sv, (objArrayOop) obj());
1630 }
1631 }
1632 // These objects may escape when we return to Interpreter after deoptimization.
1633 // We need barrier so that stores that initialize these objects can't be reordered
1634 // with subsequent stores that make these objects accessible by other threads.
1635 OrderAccess::storestore();
1636 }
1637
1638
1639 // relock objects for which synchronization was eliminated
1640 bool Deoptimization::relock_objects(JavaThread* thread, GrowableArray<MonitorInfo*>* monitors,
1641 JavaThread* deoptee_thread, frame& fr, int exec_mode, bool realloc_failures) {
1642 bool relocked_objects = false;
1643 for (int i = 0; i < monitors->length(); i++) {
1644 MonitorInfo* mon_info = monitors->at(i);
1645 if (mon_info->eliminated()) {
1646 assert(!mon_info->owner_is_scalar_replaced() || realloc_failures, "reallocation was missed");
1647 relocked_objects = true;
1648 if (!mon_info->owner_is_scalar_replaced()) {
1649 Handle obj(thread, mon_info->owner());
1650 markWord mark = obj->mark();
1651 if (exec_mode == Unpack_none) {
1652 if (LockingMode == LM_LEGACY && mark.has_locker() && fr.sp() > (intptr_t*)mark.locker()) {
1653 // With exec_mode == Unpack_none obj may be thread local and locked in
1654 // a callee frame. Make the lock in the callee a recursive lock and restore the displaced header.
1655 markWord dmw = mark.displaced_mark_helper();
1656 mark.locker()->set_displaced_header(markWord::encode((BasicLock*) nullptr));
1657 obj->set_mark(dmw);
1658 }
1659 if (mark.has_monitor()) {
1660 // defer relocking if the deoptee thread is currently waiting for obj
1661 ObjectMonitor* waiting_monitor = deoptee_thread->current_waiting_monitor();
1662 if (waiting_monitor != nullptr && waiting_monitor->object() == obj()) {
1663 assert(fr.is_deoptimized_frame(), "frame must be scheduled for deoptimization");
1664 mon_info->lock()->set_displaced_header(markWord::unused_mark());
1665 JvmtiDeferredUpdates::inc_relock_count_after_wait(deoptee_thread);
1666 continue;
1667 }
1668 }
1669 }
1670 if (LockingMode == LM_LIGHTWEIGHT) {
1671 // We have lost information about the correct state of the lock stack.
1672 // Inflate the locks instead. Enter then inflate to avoid races with
1673 // deflation.
1674 ObjectSynchronizer::enter_for(obj, nullptr, deoptee_thread);
1675 assert(mon_info->owner()->is_locked(), "object must be locked now");
1676 ObjectMonitor* mon = ObjectSynchronizer::inflate_for(deoptee_thread, obj(), ObjectSynchronizer::inflate_cause_vm_internal);
1677 assert(mon->owner() == deoptee_thread, "must be");
1678 } else {
1679 BasicLock* lock = mon_info->lock();
1680 ObjectSynchronizer::enter_for(obj, lock, deoptee_thread);
1681 assert(mon_info->owner()->is_locked(), "object must be locked now");
1682 }
1683 }
1684 }
1685 }
1686 return relocked_objects;
1687 }
1688 #endif // COMPILER2_OR_JVMCI
1689
1690 vframeArray* Deoptimization::create_vframeArray(JavaThread* thread, frame fr, RegisterMap *reg_map, GrowableArray<compiledVFrame*>* chunk, bool realloc_failures) {
1691 Events::log_deopt_message(thread, "DEOPT PACKING pc=" INTPTR_FORMAT " sp=" INTPTR_FORMAT, p2i(fr.pc()), p2i(fr.sp()));
1692
1693 // Register map for next frame (used for stack crawl). We capture
1694 // the state of the deopt'ing frame's caller. Thus if we need to
1695 // stuff a C2I adapter we can properly fill in the callee-save
1696 // register locations.
1697 frame caller = fr.sender(reg_map);
1698 int frame_size = caller.sp() - fr.sp();
1699
1700 frame sender = caller;
1701
1702 // Since the Java thread being deoptimized will eventually adjust it's own stack,
1703 // the vframeArray containing the unpacking information is allocated in the C heap.
1704 // For Compiler1, the caller of the deoptimized frame is saved for use by unpack_frames().
1705 vframeArray* array = vframeArray::allocate(thread, frame_size, chunk, reg_map, sender, caller, fr, realloc_failures);
1706
1707 // Compare the vframeArray to the collected vframes
1708 assert(array->structural_compare(thread, chunk), "just checking");
1709
1710 if (TraceDeoptimization) {
1711 ResourceMark rm;
1712 stringStream st;
1713 st.print_cr("DEOPT PACKING thread=" INTPTR_FORMAT " vframeArray=" INTPTR_FORMAT, p2i(thread), p2i(array));
1714 st.print(" ");
1715 fr.print_on(&st);
1716 st.print_cr(" Virtual frames (innermost/newest first):");
1717 for (int index = 0; index < chunk->length(); index++) {
1718 compiledVFrame* vf = chunk->at(index);
1719 int bci = vf->raw_bci();
1720 const char* code_name;
1721 if (bci == SynchronizationEntryBCI) {
1722 code_name = "sync entry";
1723 } else {
1724 Bytecodes::Code code = vf->method()->code_at(bci);
1725 code_name = Bytecodes::name(code);
1726 }
1727
1728 st.print(" VFrame %d (" INTPTR_FORMAT ")", index, p2i(vf));
1729 st.print(" - %s", vf->method()->name_and_sig_as_C_string());
1730 st.print(" - %s", code_name);
1731 st.print_cr(" @ bci=%d ", bci);
1732 }
1733 tty->print_raw(st.freeze());
1734 tty->cr();
1735 }
1736
1737 return array;
1738 }
1739
1740 #if COMPILER2_OR_JVMCI
1741 void Deoptimization::pop_frames_failed_reallocs(JavaThread* thread, vframeArray* array) {
1742 // Reallocation of some scalar replaced objects failed. Record
1743 // that we need to pop all the interpreter frames for the
1744 // deoptimized compiled frame.
1745 assert(thread->frames_to_pop_failed_realloc() == 0, "missed frames to pop?");
1746 thread->set_frames_to_pop_failed_realloc(array->frames());
1747 // Unlock all monitors here otherwise the interpreter will see a
1748 // mix of locked and unlocked monitors (because of failed
1749 // reallocations of synchronized objects) and be confused.
1750 for (int i = 0; i < array->frames(); i++) {
1751 MonitorChunk* monitors = array->element(i)->monitors();
1752 if (monitors != nullptr) {
1753 // Unlock in reverse order starting from most nested monitor.
1754 for (int j = (monitors->number_of_monitors() - 1); j >= 0; j--) {
1755 BasicObjectLock* src = monitors->at(j);
1756 if (src->obj() != nullptr) {
1757 ObjectSynchronizer::exit(src->obj(), src->lock(), thread);
1758 }
1759 }
1760 array->element(i)->free_monitors();
1761 #ifdef ASSERT
1762 array->element(i)->set_removed_monitors();
1763 #endif
1764 }
1765 }
1766 }
1767 #endif
1768
1769 void Deoptimization::deoptimize_single_frame(JavaThread* thread, frame fr, Deoptimization::DeoptReason reason) {
1770 assert(fr.can_be_deoptimized(), "checking frame type");
1771
1772 gather_statistics(reason, Action_none, Bytecodes::_illegal);
1773
1774 if (LogCompilation && xtty != nullptr) {
1775 CompiledMethod* cm = fr.cb()->as_compiled_method_or_null();
1776 assert(cm != nullptr, "only compiled methods can deopt");
1777
1778 ttyLocker ttyl;
1779 xtty->begin_head("deoptimized thread='" UINTX_FORMAT "' reason='%s' pc='" INTPTR_FORMAT "'",(uintx)thread->osthread()->thread_id(), trap_reason_name(reason), p2i(fr.pc()));
1780 cm->log_identity(xtty);
1781 xtty->end_head();
1782 for (ScopeDesc* sd = cm->scope_desc_at(fr.pc()); ; sd = sd->sender()) {
1783 xtty->begin_elem("jvms bci='%d'", sd->bci());
1784 xtty->method(sd->method());
1785 xtty->end_elem();
1786 if (sd->is_top()) break;
1787 }
1788 xtty->tail("deoptimized");
1789 }
1790
1791 Continuation::notify_deopt(thread, fr.sp());
1792
1793 // Patch the compiled method so that when execution returns to it we will
1794 // deopt the execution state and return to the interpreter.
1795 fr.deoptimize(thread);
1796 }
1797
1798 void Deoptimization::deoptimize(JavaThread* thread, frame fr, DeoptReason reason) {
1799 // Deoptimize only if the frame comes from compile code.
1800 // Do not deoptimize the frame which is already patched
1801 // during the execution of the loops below.
1802 if (!fr.is_compiled_frame() || fr.is_deoptimized_frame()) {
1803 return;
1804 }
1805 ResourceMark rm;
1806 deoptimize_single_frame(thread, fr, reason);
1807 }
1808
1809 #if INCLUDE_JVMCI
1810 address Deoptimization::deoptimize_for_missing_exception_handler(CompiledMethod* cm) {
1811 // there is no exception handler for this pc => deoptimize
1812 cm->make_not_entrant();
1813
1814 // Use Deoptimization::deoptimize for all of its side-effects:
1815 // gathering traps statistics, logging...
1816 // it also patches the return pc but we do not care about that
1817 // since we return a continuation to the deopt_blob below.
1818 JavaThread* thread = JavaThread::current();
1819 RegisterMap reg_map(thread,
1820 RegisterMap::UpdateMap::skip,
1821 RegisterMap::ProcessFrames::include,
1822 RegisterMap::WalkContinuation::skip);
1823 frame runtime_frame = thread->last_frame();
1824 frame caller_frame = runtime_frame.sender(®_map);
1825 assert(caller_frame.cb()->as_compiled_method_or_null() == cm, "expect top frame compiled method");
1826 vframe* vf = vframe::new_vframe(&caller_frame, ®_map, thread);
1827 compiledVFrame* cvf = compiledVFrame::cast(vf);
1828 ScopeDesc* imm_scope = cvf->scope();
1829 MethodData* imm_mdo = get_method_data(thread, methodHandle(thread, imm_scope->method()), true);
1830 if (imm_mdo != nullptr) {
1831 ProfileData* pdata = imm_mdo->allocate_bci_to_data(imm_scope->bci(), nullptr);
1832 if (pdata != nullptr && pdata->is_BitData()) {
1833 BitData* bit_data = (BitData*) pdata;
1834 bit_data->set_exception_seen();
1835 }
1836 }
1837
1838 Deoptimization::deoptimize(thread, caller_frame, Deoptimization::Reason_not_compiled_exception_handler);
1839
1840 MethodData* trap_mdo = get_method_data(thread, methodHandle(thread, cm->method()), true);
1841 if (trap_mdo != nullptr) {
1842 trap_mdo->inc_trap_count(Deoptimization::Reason_not_compiled_exception_handler);
1843 }
1844
1845 return SharedRuntime::deopt_blob()->unpack_with_exception_in_tls();
1846 }
1847 #endif
1848
1849 void Deoptimization::deoptimize_frame_internal(JavaThread* thread, intptr_t* id, DeoptReason reason) {
1850 assert(thread == Thread::current() ||
1851 thread->is_handshake_safe_for(Thread::current()) ||
1852 SafepointSynchronize::is_at_safepoint(),
1853 "can only deoptimize other thread at a safepoint/handshake");
1854 // Compute frame and register map based on thread and sp.
1855 RegisterMap reg_map(thread,
1856 RegisterMap::UpdateMap::skip,
1857 RegisterMap::ProcessFrames::include,
1858 RegisterMap::WalkContinuation::skip);
1859 frame fr = thread->last_frame();
1860 while (fr.id() != id) {
1861 fr = fr.sender(®_map);
1862 }
1863 deoptimize(thread, fr, reason);
1864 }
1865
1866
1867 void Deoptimization::deoptimize_frame(JavaThread* thread, intptr_t* id, DeoptReason reason) {
1868 Thread* current = Thread::current();
1869 if (thread == current || thread->is_handshake_safe_for(current)) {
1870 Deoptimization::deoptimize_frame_internal(thread, id, reason);
1871 } else {
1872 VM_DeoptimizeFrame deopt(thread, id, reason);
1873 VMThread::execute(&deopt);
1874 }
1875 }
1876
1877 void Deoptimization::deoptimize_frame(JavaThread* thread, intptr_t* id) {
1878 deoptimize_frame(thread, id, Reason_constraint);
1879 }
1880
1881 // JVMTI PopFrame support
1882 JRT_LEAF(void, Deoptimization::popframe_preserve_args(JavaThread* thread, int bytes_to_save, void* start_address))
1883 {
1884 assert(thread == JavaThread::current(), "pre-condition");
1885 thread->popframe_preserve_args(in_ByteSize(bytes_to_save), start_address);
1886 }
1887 JRT_END
1888
1889 MethodData*
1890 Deoptimization::get_method_data(JavaThread* thread, const methodHandle& m,
1891 bool create_if_missing) {
1892 JavaThread* THREAD = thread; // For exception macros.
1893 MethodData* mdo = m()->method_data();
1894 if (mdo == nullptr && create_if_missing && !HAS_PENDING_EXCEPTION) {
1895 // Build an MDO. Ignore errors like OutOfMemory;
1896 // that simply means we won't have an MDO to update.
1897 Method::build_profiling_method_data(m, THREAD);
1898 if (HAS_PENDING_EXCEPTION) {
1899 // Only metaspace OOM is expected. No Java code executed.
1900 assert((PENDING_EXCEPTION->is_a(vmClasses::OutOfMemoryError_klass())), "we expect only an OOM error here");
1901 CLEAR_PENDING_EXCEPTION;
1902 }
1903 mdo = m()->method_data();
1904 }
1905 return mdo;
1906 }
1907
1908 #if COMPILER2_OR_JVMCI
1909 void Deoptimization::load_class_by_index(const constantPoolHandle& constant_pool, int index, TRAPS) {
1910 // In case of an unresolved klass entry, load the class.
1911 // This path is exercised from case _ldc in Parse::do_one_bytecode,
1912 // and probably nowhere else.
1913 // Even that case would benefit from simply re-interpreting the
1914 // bytecode, without paying special attention to the class index.
1915 // So this whole "class index" feature should probably be removed.
1916
1917 if (constant_pool->tag_at(index).is_unresolved_klass()) {
1918 Klass* tk = constant_pool->klass_at(index, THREAD);
1919 if (HAS_PENDING_EXCEPTION) {
1920 // Exception happened during classloading. We ignore the exception here, since it
1921 // is going to be rethrown since the current activation is going to be deoptimized and
1922 // the interpreter will re-execute the bytecode.
1923 // Do not clear probable Async Exceptions.
1924 CLEAR_PENDING_NONASYNC_EXCEPTION;
1925 // Class loading called java code which may have caused a stack
1926 // overflow. If the exception was thrown right before the return
1927 // to the runtime the stack is no longer guarded. Reguard the
1928 // stack otherwise if we return to the uncommon trap blob and the
1929 // stack bang causes a stack overflow we crash.
1930 JavaThread* jt = THREAD;
1931 bool guard_pages_enabled = jt->stack_overflow_state()->reguard_stack_if_needed();
1932 assert(guard_pages_enabled, "stack banging in uncommon trap blob may cause crash");
1933 }
1934 return;
1935 }
1936
1937 assert(!constant_pool->tag_at(index).is_symbol(),
1938 "no symbolic names here, please");
1939 }
1940
1941 #if INCLUDE_JFR
1942
1943 class DeoptReasonSerializer : public JfrSerializer {
1944 public:
1945 void serialize(JfrCheckpointWriter& writer) {
1946 writer.write_count((u4)(Deoptimization::Reason_LIMIT + 1)); // + Reason::many (-1)
1947 for (int i = -1; i < Deoptimization::Reason_LIMIT; ++i) {
1948 writer.write_key((u8)i);
1949 writer.write(Deoptimization::trap_reason_name(i));
1950 }
1951 }
1952 };
1953
1954 class DeoptActionSerializer : public JfrSerializer {
1955 public:
1956 void serialize(JfrCheckpointWriter& writer) {
1957 static const u4 nof_actions = Deoptimization::Action_LIMIT;
1958 writer.write_count(nof_actions);
1959 for (u4 i = 0; i < Deoptimization::Action_LIMIT; ++i) {
1960 writer.write_key(i);
1961 writer.write(Deoptimization::trap_action_name((int)i));
1962 }
1963 }
1964 };
1965
1966 static void register_serializers() {
1967 static int critical_section = 0;
1968 if (1 == critical_section || Atomic::cmpxchg(&critical_section, 0, 1) == 1) {
1969 return;
1970 }
1971 JfrSerializer::register_serializer(TYPE_DEOPTIMIZATIONREASON, true, new DeoptReasonSerializer());
1972 JfrSerializer::register_serializer(TYPE_DEOPTIMIZATIONACTION, true, new DeoptActionSerializer());
1973 }
1974
1975 static void post_deoptimization_event(CompiledMethod* nm,
1976 const Method* method,
1977 int trap_bci,
1978 int instruction,
1979 Deoptimization::DeoptReason reason,
1980 Deoptimization::DeoptAction action) {
1981 assert(nm != nullptr, "invariant");
1982 assert(method != nullptr, "invariant");
1983 if (EventDeoptimization::is_enabled()) {
1984 static bool serializers_registered = false;
1985 if (!serializers_registered) {
1986 register_serializers();
1987 serializers_registered = true;
1988 }
1989 EventDeoptimization event;
1990 event.set_compileId(nm->compile_id());
1991 event.set_compiler(nm->compiler_type());
1992 event.set_method(method);
1993 event.set_lineNumber(method->line_number_from_bci(trap_bci));
1994 event.set_bci(trap_bci);
1995 event.set_instruction(instruction);
1996 event.set_reason(reason);
1997 event.set_action(action);
1998 event.commit();
1999 }
2000 }
2001
2002 #endif // INCLUDE_JFR
2003
2004 static void log_deopt(CompiledMethod* nm, Method* tm, intptr_t pc, frame& fr, int trap_bci,
2005 const char* reason_name, const char* reason_action) {
2006 LogTarget(Debug, deoptimization) lt;
2007 if (lt.is_enabled()) {
2008 LogStream ls(lt);
2009 bool is_osr = nm->is_osr_method();
2010 ls.print("cid=%4d %s level=%d",
2011 nm->compile_id(), (is_osr ? "osr" : " "), nm->comp_level());
2012 ls.print(" %s", tm->name_and_sig_as_C_string());
2013 ls.print(" trap_bci=%d ", trap_bci);
2014 if (is_osr) {
2015 ls.print("osr_bci=%d ", nm->osr_entry_bci());
2016 }
2017 ls.print("%s ", reason_name);
2018 ls.print("%s ", reason_action);
2019 ls.print_cr("pc=" INTPTR_FORMAT " relative_pc=" INTPTR_FORMAT,
2020 pc, fr.pc() - nm->code_begin());
2021 }
2022 }
2023
2024 JRT_ENTRY(void, Deoptimization::uncommon_trap_inner(JavaThread* current, jint trap_request)) {
2025 HandleMark hm(current);
2026
2027 // uncommon_trap() is called at the beginning of the uncommon trap
2028 // handler. Note this fact before we start generating temporary frames
2029 // that can confuse an asynchronous stack walker. This counter is
2030 // decremented at the end of unpack_frames().
2031
2032 current->inc_in_deopt_handler();
2033
2034 #if INCLUDE_JVMCI
2035 // JVMCI might need to get an exception from the stack, which in turn requires the register map to be valid
2036 RegisterMap reg_map(current,
2037 RegisterMap::UpdateMap::include,
2038 RegisterMap::ProcessFrames::include,
2039 RegisterMap::WalkContinuation::skip);
2040 #else
2041 RegisterMap reg_map(current,
2042 RegisterMap::UpdateMap::skip,
2043 RegisterMap::ProcessFrames::include,
2044 RegisterMap::WalkContinuation::skip);
2045 #endif
2046 frame stub_frame = current->last_frame();
2047 frame fr = stub_frame.sender(®_map);
2048
2049 // Log a message
2050 Events::log_deopt_message(current, "Uncommon trap: trap_request=" INT32_FORMAT_X_0 " fr.pc=" INTPTR_FORMAT " relative=" INTPTR_FORMAT,
2051 trap_request, p2i(fr.pc()), fr.pc() - fr.cb()->code_begin());
2052
2053 {
2054 ResourceMark rm;
2055
2056 DeoptReason reason = trap_request_reason(trap_request);
2057 DeoptAction action = trap_request_action(trap_request);
2058 #if INCLUDE_JVMCI
2059 int debug_id = trap_request_debug_id(trap_request);
2060 #endif
2061 jint unloaded_class_index = trap_request_index(trap_request); // CP idx or -1
2062
2063 vframe* vf = vframe::new_vframe(&fr, ®_map, current);
2064 compiledVFrame* cvf = compiledVFrame::cast(vf);
2065
2066 CompiledMethod* nm = cvf->code();
2067
2068 ScopeDesc* trap_scope = cvf->scope();
2069
2070 bool is_receiver_constraint_failure = COMPILER2_PRESENT(VerifyReceiverTypes &&) (reason == Deoptimization::Reason_receiver_constraint);
2071
2072 if (is_receiver_constraint_failure) {
2073 tty->print_cr(" bci=%d pc=" INTPTR_FORMAT ", relative_pc=" INTPTR_FORMAT ", method=%s" JVMCI_ONLY(", debug_id=%d"),
2074 trap_scope->bci(), p2i(fr.pc()), fr.pc() - nm->code_begin(), trap_scope->method()->name_and_sig_as_C_string()
2075 JVMCI_ONLY(COMMA debug_id));
2076 }
2077
2078 methodHandle trap_method(current, trap_scope->method());
2079 int trap_bci = trap_scope->bci();
2080 #if INCLUDE_JVMCI
2081 jlong speculation = current->pending_failed_speculation();
2082 if (nm->is_compiled_by_jvmci()) {
2083 nm->as_nmethod()->update_speculation(current);
2084 } else {
2085 assert(speculation == 0, "There should not be a speculation for methods compiled by non-JVMCI compilers");
2086 }
2087
2088 if (trap_bci == SynchronizationEntryBCI) {
2089 trap_bci = 0;
2090 current->set_pending_monitorenter(true);
2091 }
2092
2093 if (reason == Deoptimization::Reason_transfer_to_interpreter) {
2094 current->set_pending_transfer_to_interpreter(true);
2095 }
2096 #endif
2097
2098 Bytecodes::Code trap_bc = trap_method->java_code_at(trap_bci);
2099 // Record this event in the histogram.
2100 gather_statistics(reason, action, trap_bc);
2101
2102 // Ensure that we can record deopt. history:
2103 // Need MDO to record RTM code generation state.
2104 bool create_if_missing = ProfileTraps RTM_OPT_ONLY( || UseRTMLocking );
2105
2106 methodHandle profiled_method;
2107 #if INCLUDE_JVMCI
2108 if (nm->is_compiled_by_jvmci()) {
2109 profiled_method = methodHandle(current, nm->method());
2110 } else {
2111 profiled_method = trap_method;
2112 }
2113 #else
2114 profiled_method = trap_method;
2115 #endif
2116
2117 MethodData* trap_mdo =
2118 get_method_data(current, profiled_method, create_if_missing);
2119
2120 { // Log Deoptimization event for JFR, UL and event system
2121 Method* tm = trap_method();
2122 const char* reason_name = trap_reason_name(reason);
2123 const char* reason_action = trap_action_name(action);
2124 intptr_t pc = p2i(fr.pc());
2125
2126 JFR_ONLY(post_deoptimization_event(nm, tm, trap_bci, trap_bc, reason, action);)
2127 log_deopt(nm, tm, pc, fr, trap_bci, reason_name, reason_action);
2128 Events::log_deopt_message(current, "Uncommon trap: reason=%s action=%s pc=" INTPTR_FORMAT " method=%s @ %d %s",
2129 reason_name, reason_action, pc,
2130 tm->name_and_sig_as_C_string(), trap_bci, nm->compiler_name());
2131 }
2132
2133 // Print a bunch of diagnostics, if requested.
2134 if (TraceDeoptimization || LogCompilation || is_receiver_constraint_failure) {
2135 ResourceMark rm;
2136 ttyLocker ttyl;
2137 char buf[100];
2138 if (xtty != nullptr) {
2139 xtty->begin_head("uncommon_trap thread='" UINTX_FORMAT "' %s",
2140 os::current_thread_id(),
2141 format_trap_request(buf, sizeof(buf), trap_request));
2142 #if INCLUDE_JVMCI
2143 if (speculation != 0) {
2144 xtty->print(" speculation='" JLONG_FORMAT "'", speculation);
2145 }
2146 #endif
2147 nm->log_identity(xtty);
2148 }
2149 Symbol* class_name = nullptr;
2150 bool unresolved = false;
2151 if (unloaded_class_index >= 0) {
2152 constantPoolHandle constants (current, trap_method->constants());
2153 if (constants->tag_at(unloaded_class_index).is_unresolved_klass()) {
2154 class_name = constants->klass_name_at(unloaded_class_index);
2155 unresolved = true;
2156 if (xtty != nullptr)
2157 xtty->print(" unresolved='1'");
2158 } else if (constants->tag_at(unloaded_class_index).is_symbol()) {
2159 class_name = constants->symbol_at(unloaded_class_index);
2160 }
2161 if (xtty != nullptr)
2162 xtty->name(class_name);
2163 }
2164 if (xtty != nullptr && trap_mdo != nullptr && (int)reason < (int)MethodData::_trap_hist_limit) {
2165 // Dump the relevant MDO state.
2166 // This is the deopt count for the current reason, any previous
2167 // reasons or recompiles seen at this point.
2168 int dcnt = trap_mdo->trap_count(reason);
2169 if (dcnt != 0)
2170 xtty->print(" count='%d'", dcnt);
2171 ProfileData* pdata = trap_mdo->bci_to_data(trap_bci);
2172 int dos = (pdata == nullptr)? 0: pdata->trap_state();
2173 if (dos != 0) {
2174 xtty->print(" state='%s'", format_trap_state(buf, sizeof(buf), dos));
2175 if (trap_state_is_recompiled(dos)) {
2176 int recnt2 = trap_mdo->overflow_recompile_count();
2177 if (recnt2 != 0)
2178 xtty->print(" recompiles2='%d'", recnt2);
2179 }
2180 }
2181 }
2182 if (xtty != nullptr) {
2183 xtty->stamp();
2184 xtty->end_head();
2185 }
2186 if (TraceDeoptimization) { // make noise on the tty
2187 stringStream st;
2188 st.print("UNCOMMON TRAP method=%s", trap_scope->method()->name_and_sig_as_C_string());
2189 st.print(" bci=%d pc=" INTPTR_FORMAT ", relative_pc=" INTPTR_FORMAT JVMCI_ONLY(", debug_id=%d"),
2190 trap_scope->bci(), p2i(fr.pc()), fr.pc() - nm->code_begin() JVMCI_ONLY(COMMA debug_id));
2191 st.print(" compiler=%s compile_id=%d", nm->compiler_name(), nm->compile_id());
2192 #if INCLUDE_JVMCI
2193 if (nm->is_nmethod()) {
2194 const char* installed_code_name = nm->as_nmethod()->jvmci_name();
2195 if (installed_code_name != nullptr) {
2196 st.print(" (JVMCI: installed code name=%s) ", installed_code_name);
2197 }
2198 }
2199 #endif
2200 st.print(" (@" INTPTR_FORMAT ") thread=" UINTX_FORMAT " reason=%s action=%s unloaded_class_index=%d" JVMCI_ONLY(" debug_id=%d"),
2201 p2i(fr.pc()),
2202 os::current_thread_id(),
2203 trap_reason_name(reason),
2204 trap_action_name(action),
2205 unloaded_class_index
2206 #if INCLUDE_JVMCI
2207 , debug_id
2208 #endif
2209 );
2210 if (class_name != nullptr) {
2211 st.print(unresolved ? " unresolved class: " : " symbol: ");
2212 class_name->print_symbol_on(&st);
2213 }
2214 st.cr();
2215 tty->print_raw(st.freeze());
2216 }
2217 if (xtty != nullptr) {
2218 // Log the precise location of the trap.
2219 for (ScopeDesc* sd = trap_scope; ; sd = sd->sender()) {
2220 xtty->begin_elem("jvms bci='%d'", sd->bci());
2221 xtty->method(sd->method());
2222 xtty->end_elem();
2223 if (sd->is_top()) break;
2224 }
2225 xtty->tail("uncommon_trap");
2226 }
2227 }
2228 // (End diagnostic printout.)
2229
2230 if (is_receiver_constraint_failure) {
2231 fatal("missing receiver type check");
2232 }
2233
2234 // Load class if necessary
2235 if (unloaded_class_index >= 0) {
2236 constantPoolHandle constants(current, trap_method->constants());
2237 load_class_by_index(constants, unloaded_class_index, THREAD);
2238 }
2239
2240 // Flush the nmethod if necessary and desirable.
2241 //
2242 // We need to avoid situations where we are re-flushing the nmethod
2243 // because of a hot deoptimization site. Repeated flushes at the same
2244 // point need to be detected by the compiler and avoided. If the compiler
2245 // cannot avoid them (or has a bug and "refuses" to avoid them), this
2246 // module must take measures to avoid an infinite cycle of recompilation
2247 // and deoptimization. There are several such measures:
2248 //
2249 // 1. If a recompilation is ordered a second time at some site X
2250 // and for the same reason R, the action is adjusted to 'reinterpret',
2251 // to give the interpreter time to exercise the method more thoroughly.
2252 // If this happens, the method's overflow_recompile_count is incremented.
2253 //
2254 // 2. If the compiler fails to reduce the deoptimization rate, then
2255 // the method's overflow_recompile_count will begin to exceed the set
2256 // limit PerBytecodeRecompilationCutoff. If this happens, the action
2257 // is adjusted to 'make_not_compilable', and the method is abandoned
2258 // to the interpreter. This is a performance hit for hot methods,
2259 // but is better than a disastrous infinite cycle of recompilations.
2260 // (Actually, only the method containing the site X is abandoned.)
2261 //
2262 // 3. In parallel with the previous measures, if the total number of
2263 // recompilations of a method exceeds the much larger set limit
2264 // PerMethodRecompilationCutoff, the method is abandoned.
2265 // This should only happen if the method is very large and has
2266 // many "lukewarm" deoptimizations. The code which enforces this
2267 // limit is elsewhere (class nmethod, class Method).
2268 //
2269 // Note that the per-BCI 'is_recompiled' bit gives the compiler one chance
2270 // to recompile at each bytecode independently of the per-BCI cutoff.
2271 //
2272 // The decision to update code is up to the compiler, and is encoded
2273 // in the Action_xxx code. If the compiler requests Action_none
2274 // no trap state is changed, no compiled code is changed, and the
2275 // computation suffers along in the interpreter.
2276 //
2277 // The other action codes specify various tactics for decompilation
2278 // and recompilation. Action_maybe_recompile is the loosest, and
2279 // allows the compiled code to stay around until enough traps are seen,
2280 // and until the compiler gets around to recompiling the trapping method.
2281 //
2282 // The other actions cause immediate removal of the present code.
2283
2284 // Traps caused by injected profile shouldn't pollute trap counts.
2285 bool injected_profile_trap = trap_method->has_injected_profile() &&
2286 (reason == Reason_intrinsic || reason == Reason_unreached);
2287
2288 bool update_trap_state = (reason != Reason_tenured) && !injected_profile_trap;
2289 bool make_not_entrant = false;
2290 bool make_not_compilable = false;
2291 bool reprofile = false;
2292 switch (action) {
2293 case Action_none:
2294 // Keep the old code.
2295 update_trap_state = false;
2296 break;
2297 case Action_maybe_recompile:
2298 // Do not need to invalidate the present code, but we can
2299 // initiate another
2300 // Start compiler without (necessarily) invalidating the nmethod.
2301 // The system will tolerate the old code, but new code should be
2302 // generated when possible.
2303 break;
2304 case Action_reinterpret:
2305 // Go back into the interpreter for a while, and then consider
2306 // recompiling form scratch.
2307 make_not_entrant = true;
2308 // Reset invocation counter for outer most method.
2309 // This will allow the interpreter to exercise the bytecodes
2310 // for a while before recompiling.
2311 // By contrast, Action_make_not_entrant is immediate.
2312 //
2313 // Note that the compiler will track null_check, null_assert,
2314 // range_check, and class_check events and log them as if they
2315 // had been traps taken from compiled code. This will update
2316 // the MDO trap history so that the next compilation will
2317 // properly detect hot trap sites.
2318 reprofile = true;
2319 break;
2320 case Action_make_not_entrant:
2321 // Request immediate recompilation, and get rid of the old code.
2322 // Make them not entrant, so next time they are called they get
2323 // recompiled. Unloaded classes are loaded now so recompile before next
2324 // time they are called. Same for uninitialized. The interpreter will
2325 // link the missing class, if any.
2326 make_not_entrant = true;
2327 break;
2328 case Action_make_not_compilable:
2329 // Give up on compiling this method at all.
2330 make_not_entrant = true;
2331 make_not_compilable = true;
2332 break;
2333 default:
2334 ShouldNotReachHere();
2335 }
2336
2337 // Setting +ProfileTraps fixes the following, on all platforms:
2338 // 4852688: ProfileInterpreter is off by default for ia64. The result is
2339 // infinite heroic-opt-uncommon-trap/deopt/recompile cycles, since the
2340 // recompile relies on a MethodData* to record heroic opt failures.
2341
2342 // Whether the interpreter is producing MDO data or not, we also need
2343 // to use the MDO to detect hot deoptimization points and control
2344 // aggressive optimization.
2345 bool inc_recompile_count = false;
2346 ProfileData* pdata = nullptr;
2347 if (ProfileTraps && CompilerConfig::is_c2_or_jvmci_compiler_enabled() && update_trap_state && trap_mdo != nullptr) {
2348 assert(trap_mdo == get_method_data(current, profiled_method, false), "sanity");
2349 uint this_trap_count = 0;
2350 bool maybe_prior_trap = false;
2351 bool maybe_prior_recompile = false;
2352 pdata = query_update_method_data(trap_mdo, trap_bci, reason, true,
2353 #if INCLUDE_JVMCI
2354 nm->is_compiled_by_jvmci() && nm->is_osr_method(),
2355 #endif
2356 nm->method(),
2357 //outputs:
2358 this_trap_count,
2359 maybe_prior_trap,
2360 maybe_prior_recompile);
2361 // Because the interpreter also counts null, div0, range, and class
2362 // checks, these traps from compiled code are double-counted.
2363 // This is harmless; it just means that the PerXTrapLimit values
2364 // are in effect a little smaller than they look.
2365
2366 DeoptReason per_bc_reason = reason_recorded_per_bytecode_if_any(reason);
2367 if (per_bc_reason != Reason_none) {
2368 // Now take action based on the partially known per-BCI history.
2369 if (maybe_prior_trap
2370 && this_trap_count >= (uint)PerBytecodeTrapLimit) {
2371 // If there are too many traps at this BCI, force a recompile.
2372 // This will allow the compiler to see the limit overflow, and
2373 // take corrective action, if possible. The compiler generally
2374 // does not use the exact PerBytecodeTrapLimit value, but instead
2375 // changes its tactics if it sees any traps at all. This provides
2376 // a little hysteresis, delaying a recompile until a trap happens
2377 // several times.
2378 //
2379 // Actually, since there is only one bit of counter per BCI,
2380 // the possible per-BCI counts are {0,1,(per-method count)}.
2381 // This produces accurate results if in fact there is only
2382 // one hot trap site, but begins to get fuzzy if there are
2383 // many sites. For example, if there are ten sites each
2384 // trapping two or more times, they each get the blame for
2385 // all of their traps.
2386 make_not_entrant = true;
2387 }
2388
2389 // Detect repeated recompilation at the same BCI, and enforce a limit.
2390 if (make_not_entrant && maybe_prior_recompile) {
2391 // More than one recompile at this point.
2392 inc_recompile_count = maybe_prior_trap;
2393 }
2394 } else {
2395 // For reasons which are not recorded per-bytecode, we simply
2396 // force recompiles unconditionally.
2397 // (Note that PerMethodRecompilationCutoff is enforced elsewhere.)
2398 make_not_entrant = true;
2399 }
2400
2401 // Go back to the compiler if there are too many traps in this method.
2402 if (this_trap_count >= per_method_trap_limit(reason)) {
2403 // If there are too many traps in this method, force a recompile.
2404 // This will allow the compiler to see the limit overflow, and
2405 // take corrective action, if possible.
2406 // (This condition is an unlikely backstop only, because the
2407 // PerBytecodeTrapLimit is more likely to take effect first,
2408 // if it is applicable.)
2409 make_not_entrant = true;
2410 }
2411
2412 // Here's more hysteresis: If there has been a recompile at
2413 // this trap point already, run the method in the interpreter
2414 // for a while to exercise it more thoroughly.
2415 if (make_not_entrant && maybe_prior_recompile && maybe_prior_trap) {
2416 reprofile = true;
2417 }
2418 }
2419
2420 // Take requested actions on the method:
2421
2422 // Recompile
2423 if (make_not_entrant) {
2424 if (!nm->make_not_entrant()) {
2425 return; // the call did not change nmethod's state
2426 }
2427
2428 if (pdata != nullptr) {
2429 // Record the recompilation event, if any.
2430 int tstate0 = pdata->trap_state();
2431 int tstate1 = trap_state_set_recompiled(tstate0, true);
2432 if (tstate1 != tstate0)
2433 pdata->set_trap_state(tstate1);
2434 }
2435
2436 #if INCLUDE_RTM_OPT
2437 // Restart collecting RTM locking abort statistic if the method
2438 // is recompiled for a reason other than RTM state change.
2439 // Assume that in new recompiled code the statistic could be different,
2440 // for example, due to different inlining.
2441 if ((reason != Reason_rtm_state_change) && (trap_mdo != nullptr) &&
2442 UseRTMDeopt && (nm->as_nmethod()->rtm_state() != ProfileRTM)) {
2443 trap_mdo->atomic_set_rtm_state(ProfileRTM);
2444 }
2445 #endif
2446 // For code aging we count traps separately here, using make_not_entrant()
2447 // as a guard against simultaneous deopts in multiple threads.
2448 if (reason == Reason_tenured && trap_mdo != nullptr) {
2449 trap_mdo->inc_tenure_traps();
2450 }
2451 }
2452
2453 if (inc_recompile_count) {
2454 trap_mdo->inc_overflow_recompile_count();
2455 if ((uint)trap_mdo->overflow_recompile_count() >
2456 (uint)PerBytecodeRecompilationCutoff) {
2457 // Give up on the method containing the bad BCI.
2458 if (trap_method() == nm->method()) {
2459 make_not_compilable = true;
2460 } else {
2461 trap_method->set_not_compilable("overflow_recompile_count > PerBytecodeRecompilationCutoff", CompLevel_full_optimization);
2462 // But give grace to the enclosing nm->method().
2463 }
2464 }
2465 }
2466
2467 // Reprofile
2468 if (reprofile) {
2469 CompilationPolicy::reprofile(trap_scope, nm->is_osr_method());
2470 }
2471
2472 // Give up compiling
2473 if (make_not_compilable && !nm->method()->is_not_compilable(CompLevel_full_optimization)) {
2474 assert(make_not_entrant, "consistent");
2475 nm->method()->set_not_compilable("give up compiling", CompLevel_full_optimization);
2476 }
2477
2478 } // Free marked resources
2479
2480 }
2481 JRT_END
2482
2483 ProfileData*
2484 Deoptimization::query_update_method_data(MethodData* trap_mdo,
2485 int trap_bci,
2486 Deoptimization::DeoptReason reason,
2487 bool update_total_trap_count,
2488 #if INCLUDE_JVMCI
2489 bool is_osr,
2490 #endif
2491 Method* compiled_method,
2492 //outputs:
2493 uint& ret_this_trap_count,
2494 bool& ret_maybe_prior_trap,
2495 bool& ret_maybe_prior_recompile) {
2496 bool maybe_prior_trap = false;
2497 bool maybe_prior_recompile = false;
2498 uint this_trap_count = 0;
2499 if (update_total_trap_count) {
2500 uint idx = reason;
2501 #if INCLUDE_JVMCI
2502 if (is_osr) {
2503 // Upper half of history array used for traps in OSR compilations
2504 idx += Reason_TRAP_HISTORY_LENGTH;
2505 }
2506 #endif
2507 uint prior_trap_count = trap_mdo->trap_count(idx);
2508 this_trap_count = trap_mdo->inc_trap_count(idx);
2509
2510 // If the runtime cannot find a place to store trap history,
2511 // it is estimated based on the general condition of the method.
2512 // If the method has ever been recompiled, or has ever incurred
2513 // a trap with the present reason , then this BCI is assumed
2514 // (pessimistically) to be the culprit.
2515 maybe_prior_trap = (prior_trap_count != 0);
2516 maybe_prior_recompile = (trap_mdo->decompile_count() != 0);
2517 }
2518 ProfileData* pdata = nullptr;
2519
2520
2521 // For reasons which are recorded per bytecode, we check per-BCI data.
2522 DeoptReason per_bc_reason = reason_recorded_per_bytecode_if_any(reason);
2523 assert(per_bc_reason != Reason_none || update_total_trap_count, "must be");
2524 if (per_bc_reason != Reason_none) {
2525 // Find the profile data for this BCI. If there isn't one,
2526 // try to allocate one from the MDO's set of spares.
2527 // This will let us detect a repeated trap at this point.
2528 pdata = trap_mdo->allocate_bci_to_data(trap_bci, reason_is_speculate(reason) ? compiled_method : nullptr);
2529
2530 if (pdata != nullptr) {
2531 if (reason_is_speculate(reason) && !pdata->is_SpeculativeTrapData()) {
2532 if (LogCompilation && xtty != nullptr) {
2533 ttyLocker ttyl;
2534 // no more room for speculative traps in this MDO
2535 xtty->elem("speculative_traps_oom");
2536 }
2537 }
2538 // Query the trap state of this profile datum.
2539 int tstate0 = pdata->trap_state();
2540 if (!trap_state_has_reason(tstate0, per_bc_reason))
2541 maybe_prior_trap = false;
2542 if (!trap_state_is_recompiled(tstate0))
2543 maybe_prior_recompile = false;
2544
2545 // Update the trap state of this profile datum.
2546 int tstate1 = tstate0;
2547 // Record the reason.
2548 tstate1 = trap_state_add_reason(tstate1, per_bc_reason);
2549 // Store the updated state on the MDO, for next time.
2550 if (tstate1 != tstate0)
2551 pdata->set_trap_state(tstate1);
2552 } else {
2553 if (LogCompilation && xtty != nullptr) {
2554 ttyLocker ttyl;
2555 // Missing MDP? Leave a small complaint in the log.
2556 xtty->elem("missing_mdp bci='%d'", trap_bci);
2557 }
2558 }
2559 }
2560
2561 // Return results:
2562 ret_this_trap_count = this_trap_count;
2563 ret_maybe_prior_trap = maybe_prior_trap;
2564 ret_maybe_prior_recompile = maybe_prior_recompile;
2565 return pdata;
2566 }
2567
2568 void
2569 Deoptimization::update_method_data_from_interpreter(MethodData* trap_mdo, int trap_bci, int reason) {
2570 ResourceMark rm;
2571 // Ignored outputs:
2572 uint ignore_this_trap_count;
2573 bool ignore_maybe_prior_trap;
2574 bool ignore_maybe_prior_recompile;
2575 assert(!reason_is_speculate(reason), "reason speculate only used by compiler");
2576 // JVMCI uses the total counts to determine if deoptimizations are happening too frequently -> do not adjust total counts
2577 bool update_total_counts = true JVMCI_ONLY( && !UseJVMCICompiler);
2578 query_update_method_data(trap_mdo, trap_bci,
2579 (DeoptReason)reason,
2580 update_total_counts,
2581 #if INCLUDE_JVMCI
2582 false,
2583 #endif
2584 nullptr,
2585 ignore_this_trap_count,
2586 ignore_maybe_prior_trap,
2587 ignore_maybe_prior_recompile);
2588 }
2589
2590 Deoptimization::UnrollBlock* Deoptimization::uncommon_trap(JavaThread* current, jint trap_request, jint exec_mode) {
2591 // Enable WXWrite: current function is called from methods compiled by C2 directly
2592 MACOS_AARCH64_ONLY(ThreadWXEnable wx(WXWrite, current));
2593
2594 // Still in Java no safepoints
2595 {
2596 // This enters VM and may safepoint
2597 uncommon_trap_inner(current, trap_request);
2598 }
2599 HandleMark hm(current);
2600 return fetch_unroll_info_helper(current, exec_mode);
2601 }
2602
2603 // Local derived constants.
2604 // Further breakdown of DataLayout::trap_state, as promised by DataLayout.
2605 const int DS_REASON_MASK = ((uint)DataLayout::trap_mask) >> 1;
2606 const int DS_RECOMPILE_BIT = DataLayout::trap_mask - DS_REASON_MASK;
2607
2608 //---------------------------trap_state_reason---------------------------------
2609 Deoptimization::DeoptReason
2610 Deoptimization::trap_state_reason(int trap_state) {
2611 // This assert provides the link between the width of DataLayout::trap_bits
2612 // and the encoding of "recorded" reasons. It ensures there are enough
2613 // bits to store all needed reasons in the per-BCI MDO profile.
2614 assert(DS_REASON_MASK >= Reason_RECORDED_LIMIT, "enough bits");
2615 int recompile_bit = (trap_state & DS_RECOMPILE_BIT);
2616 trap_state -= recompile_bit;
2617 if (trap_state == DS_REASON_MASK) {
2618 return Reason_many;
2619 } else {
2620 assert((int)Reason_none == 0, "state=0 => Reason_none");
2621 return (DeoptReason)trap_state;
2622 }
2623 }
2624 //-------------------------trap_state_has_reason-------------------------------
2625 int Deoptimization::trap_state_has_reason(int trap_state, int reason) {
2626 assert(reason_is_recorded_per_bytecode((DeoptReason)reason), "valid reason");
2627 assert(DS_REASON_MASK >= Reason_RECORDED_LIMIT, "enough bits");
2628 int recompile_bit = (trap_state & DS_RECOMPILE_BIT);
2629 trap_state -= recompile_bit;
2630 if (trap_state == DS_REASON_MASK) {
2631 return -1; // true, unspecifically (bottom of state lattice)
2632 } else if (trap_state == reason) {
2633 return 1; // true, definitely
2634 } else if (trap_state == 0) {
2635 return 0; // false, definitely (top of state lattice)
2636 } else {
2637 return 0; // false, definitely
2638 }
2639 }
2640 //-------------------------trap_state_add_reason-------------------------------
2641 int Deoptimization::trap_state_add_reason(int trap_state, int reason) {
2642 assert(reason_is_recorded_per_bytecode((DeoptReason)reason) || reason == Reason_many, "valid reason");
2643 int recompile_bit = (trap_state & DS_RECOMPILE_BIT);
2644 trap_state -= recompile_bit;
2645 if (trap_state == DS_REASON_MASK) {
2646 return trap_state + recompile_bit; // already at state lattice bottom
2647 } else if (trap_state == reason) {
2648 return trap_state + recompile_bit; // the condition is already true
2649 } else if (trap_state == 0) {
2650 return reason + recompile_bit; // no condition has yet been true
2651 } else {
2652 return DS_REASON_MASK + recompile_bit; // fall to state lattice bottom
2653 }
2654 }
2655 //-----------------------trap_state_is_recompiled------------------------------
2656 bool Deoptimization::trap_state_is_recompiled(int trap_state) {
2657 return (trap_state & DS_RECOMPILE_BIT) != 0;
2658 }
2659 //-----------------------trap_state_set_recompiled-----------------------------
2660 int Deoptimization::trap_state_set_recompiled(int trap_state, bool z) {
2661 if (z) return trap_state | DS_RECOMPILE_BIT;
2662 else return trap_state & ~DS_RECOMPILE_BIT;
2663 }
2664 //---------------------------format_trap_state---------------------------------
2665 // This is used for debugging and diagnostics, including LogFile output.
2666 const char* Deoptimization::format_trap_state(char* buf, size_t buflen,
2667 int trap_state) {
2668 assert(buflen > 0, "sanity");
2669 DeoptReason reason = trap_state_reason(trap_state);
2670 bool recomp_flag = trap_state_is_recompiled(trap_state);
2671 // Re-encode the state from its decoded components.
2672 int decoded_state = 0;
2673 if (reason_is_recorded_per_bytecode(reason) || reason == Reason_many)
2674 decoded_state = trap_state_add_reason(decoded_state, reason);
2675 if (recomp_flag)
2676 decoded_state = trap_state_set_recompiled(decoded_state, recomp_flag);
2677 // If the state re-encodes properly, format it symbolically.
2678 // Because this routine is used for debugging and diagnostics,
2679 // be robust even if the state is a strange value.
2680 size_t len;
2681 if (decoded_state != trap_state) {
2682 // Random buggy state that doesn't decode??
2683 len = jio_snprintf(buf, buflen, "#%d", trap_state);
2684 } else {
2685 len = jio_snprintf(buf, buflen, "%s%s",
2686 trap_reason_name(reason),
2687 recomp_flag ? " recompiled" : "");
2688 }
2689 return buf;
2690 }
2691
2692
2693 //--------------------------------statics--------------------------------------
2694 const char* Deoptimization::_trap_reason_name[] = {
2695 // Note: Keep this in sync. with enum DeoptReason.
2696 "none",
2697 "null_check",
2698 "null_assert" JVMCI_ONLY("_or_unreached0"),
2699 "range_check",
2700 "class_check",
2701 "array_check",
2702 "intrinsic" JVMCI_ONLY("_or_type_checked_inlining"),
2703 "bimorphic" JVMCI_ONLY("_or_optimized_type_check"),
2704 "profile_predicate",
2705 "unloaded",
2706 "uninitialized",
2707 "initialized",
2708 "unreached",
2709 "unhandled",
2710 "constraint",
2711 "div0_check",
2712 "age",
2713 "predicate",
2714 "loop_limit_check",
2715 "speculate_class_check",
2716 "speculate_null_check",
2717 "speculate_null_assert",
2718 "rtm_state_change",
2719 "unstable_if",
2720 "unstable_fused_if",
2721 "receiver_constraint",
2722 #if INCLUDE_JVMCI
2723 "aliasing",
2724 "transfer_to_interpreter",
2725 "not_compiled_exception_handler",
2726 "unresolved",
2727 "jsr_mismatch",
2728 #endif
2729 "tenured"
2730 };
2731 const char* Deoptimization::_trap_action_name[] = {
2732 // Note: Keep this in sync. with enum DeoptAction.
2733 "none",
2734 "maybe_recompile",
2735 "reinterpret",
2736 "make_not_entrant",
2737 "make_not_compilable"
2738 };
2739
2740 const char* Deoptimization::trap_reason_name(int reason) {
2741 // Check that every reason has a name
2742 STATIC_ASSERT(sizeof(_trap_reason_name)/sizeof(const char*) == Reason_LIMIT);
2743
2744 if (reason == Reason_many) return "many";
2745 if ((uint)reason < Reason_LIMIT)
2746 return _trap_reason_name[reason];
2747 static char buf[20];
2748 os::snprintf_checked(buf, sizeof(buf), "reason%d", reason);
2749 return buf;
2750 }
2751 const char* Deoptimization::trap_action_name(int action) {
2752 // Check that every action has a name
2753 STATIC_ASSERT(sizeof(_trap_action_name)/sizeof(const char*) == Action_LIMIT);
2754
2755 if ((uint)action < Action_LIMIT)
2756 return _trap_action_name[action];
2757 static char buf[20];
2758 os::snprintf_checked(buf, sizeof(buf), "action%d", action);
2759 return buf;
2760 }
2761
2762 // This is used for debugging and diagnostics, including LogFile output.
2763 const char* Deoptimization::format_trap_request(char* buf, size_t buflen,
2764 int trap_request) {
2765 jint unloaded_class_index = trap_request_index(trap_request);
2766 const char* reason = trap_reason_name(trap_request_reason(trap_request));
2767 const char* action = trap_action_name(trap_request_action(trap_request));
2768 #if INCLUDE_JVMCI
2769 int debug_id = trap_request_debug_id(trap_request);
2770 #endif
2771 size_t len;
2772 if (unloaded_class_index < 0) {
2773 len = jio_snprintf(buf, buflen, "reason='%s' action='%s'" JVMCI_ONLY(" debug_id='%d'"),
2774 reason, action
2775 #if INCLUDE_JVMCI
2776 ,debug_id
2777 #endif
2778 );
2779 } else {
2780 len = jio_snprintf(buf, buflen, "reason='%s' action='%s' index='%d'" JVMCI_ONLY(" debug_id='%d'"),
2781 reason, action, unloaded_class_index
2782 #if INCLUDE_JVMCI
2783 ,debug_id
2784 #endif
2785 );
2786 }
2787 return buf;
2788 }
2789
2790 juint Deoptimization::_deoptimization_hist
2791 [Deoptimization::Reason_LIMIT]
2792 [1 + Deoptimization::Action_LIMIT]
2793 [Deoptimization::BC_CASE_LIMIT]
2794 = {0};
2795
2796 enum {
2797 LSB_BITS = 8,
2798 LSB_MASK = right_n_bits(LSB_BITS)
2799 };
2800
2801 void Deoptimization::gather_statistics(DeoptReason reason, DeoptAction action,
2802 Bytecodes::Code bc) {
2803 assert(reason >= 0 && reason < Reason_LIMIT, "oob");
2804 assert(action >= 0 && action < Action_LIMIT, "oob");
2805 _deoptimization_hist[Reason_none][0][0] += 1; // total
2806 _deoptimization_hist[reason][0][0] += 1; // per-reason total
2807 juint* cases = _deoptimization_hist[reason][1+action];
2808 juint* bc_counter_addr = nullptr;
2809 juint bc_counter = 0;
2810 // Look for an unused counter, or an exact match to this BC.
2811 if (bc != Bytecodes::_illegal) {
2812 for (int bc_case = 0; bc_case < BC_CASE_LIMIT; bc_case++) {
2813 juint* counter_addr = &cases[bc_case];
2814 juint counter = *counter_addr;
2815 if ((counter == 0 && bc_counter_addr == nullptr)
2816 || (Bytecodes::Code)(counter & LSB_MASK) == bc) {
2817 // this counter is either free or is already devoted to this BC
2818 bc_counter_addr = counter_addr;
2819 bc_counter = counter | bc;
2820 }
2821 }
2822 }
2823 if (bc_counter_addr == nullptr) {
2824 // Overflow, or no given bytecode.
2825 bc_counter_addr = &cases[BC_CASE_LIMIT-1];
2826 bc_counter = (*bc_counter_addr & ~LSB_MASK); // clear LSB
2827 }
2828 *bc_counter_addr = bc_counter + (1 << LSB_BITS);
2829 }
2830
2831 jint Deoptimization::total_deoptimization_count() {
2832 return _deoptimization_hist[Reason_none][0][0];
2833 }
2834
2835 // Get the deopt count for a specific reason and a specific action. If either
2836 // one of 'reason' or 'action' is null, the method returns the sum of all
2837 // deoptimizations with the specific 'action' or 'reason' respectively.
2838 // If both arguments are null, the method returns the total deopt count.
2839 jint Deoptimization::deoptimization_count(const char *reason_str, const char *action_str) {
2840 if (reason_str == nullptr && action_str == nullptr) {
2841 return total_deoptimization_count();
2842 }
2843 juint counter = 0;
2844 for (int reason = 0; reason < Reason_LIMIT; reason++) {
2845 if (reason_str == nullptr || !strcmp(reason_str, trap_reason_name(reason))) {
2846 for (int action = 0; action < Action_LIMIT; action++) {
2847 if (action_str == nullptr || !strcmp(action_str, trap_action_name(action))) {
2848 juint* cases = _deoptimization_hist[reason][1+action];
2849 for (int bc_case = 0; bc_case < BC_CASE_LIMIT; bc_case++) {
2850 counter += cases[bc_case] >> LSB_BITS;
2851 }
2852 }
2853 }
2854 }
2855 }
2856 return counter;
2857 }
2858
2859 void Deoptimization::print_statistics() {
2860 juint total = total_deoptimization_count();
2861 juint account = total;
2862 if (total != 0) {
2863 ttyLocker ttyl;
2864 if (xtty != nullptr) xtty->head("statistics type='deoptimization'");
2865 tty->print_cr("Deoptimization traps recorded:");
2866 #define PRINT_STAT_LINE(name, r) \
2867 tty->print_cr(" %4d (%4.1f%%) %s", (int)(r), ((r) * 100.0) / total, name);
2868 PRINT_STAT_LINE("total", total);
2869 // For each non-zero entry in the histogram, print the reason,
2870 // the action, and (if specifically known) the type of bytecode.
2871 for (int reason = 0; reason < Reason_LIMIT; reason++) {
2872 for (int action = 0; action < Action_LIMIT; action++) {
2873 juint* cases = _deoptimization_hist[reason][1+action];
2874 for (int bc_case = 0; bc_case < BC_CASE_LIMIT; bc_case++) {
2875 juint counter = cases[bc_case];
2876 if (counter != 0) {
2877 char name[1*K];
2878 Bytecodes::Code bc = (Bytecodes::Code)(counter & LSB_MASK);
2879 if (bc_case == BC_CASE_LIMIT && (int)bc == 0)
2880 bc = Bytecodes::_illegal;
2881 os::snprintf_checked(name, sizeof(name), "%s/%s/%s",
2882 trap_reason_name(reason),
2883 trap_action_name(action),
2884 Bytecodes::is_defined(bc)? Bytecodes::name(bc): "other");
2885 juint r = counter >> LSB_BITS;
2886 tty->print_cr(" %40s: " UINT32_FORMAT " (%.1f%%)", name, r, (r * 100.0) / total);
2887 account -= r;
2888 }
2889 }
2890 }
2891 }
2892 if (account != 0) {
2893 PRINT_STAT_LINE("unaccounted", account);
2894 }
2895 #undef PRINT_STAT_LINE
2896 if (xtty != nullptr) xtty->tail("statistics");
2897 }
2898 }
2899
2900 #else // COMPILER2_OR_JVMCI
2901
2902
2903 // Stubs for C1 only system.
2904 bool Deoptimization::trap_state_is_recompiled(int trap_state) {
2905 return false;
2906 }
2907
2908 const char* Deoptimization::trap_reason_name(int reason) {
2909 return "unknown";
2910 }
2911
2912 jint Deoptimization::total_deoptimization_count() {
2913 return 0;
2914 }
2915
2916 jint Deoptimization::deoptimization_count(const char *reason_str, const char *action_str) {
2917 return 0;
2918 }
2919
2920 void Deoptimization::print_statistics() {
2921 // no output
2922 }
2923
2924 void
2925 Deoptimization::update_method_data_from_interpreter(MethodData* trap_mdo, int trap_bci, int reason) {
2926 // no update
2927 }
2928
2929 int Deoptimization::trap_state_has_reason(int trap_state, int reason) {
2930 return 0;
2931 }
2932
2933 void Deoptimization::gather_statistics(DeoptReason reason, DeoptAction action,
2934 Bytecodes::Code bc) {
2935 // no update
2936 }
2937
2938 const char* Deoptimization::format_trap_state(char* buf, size_t buflen,
2939 int trap_state) {
2940 jio_snprintf(buf, buflen, "#%d", trap_state);
2941 return buf;
2942 }
2943
2944 #endif // COMPILER2_OR_JVMCI