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