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