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