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