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