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